Remove unused files from vendor directory

This commit is contained in:
2014-10-13 22:55:59 +01:00
parent aa12a763c9
commit 75001496cf
146 changed files with 0 additions and 27904 deletions

View File

@@ -1,175 +0,0 @@
#include "stdafx.h"
#include "JXInputManager.h"
#include "JXInput.h"
//
// Globals
//
extern HINSTANCE g_hInst;
JXInputManager::JXInputManager( HWND hWnd ) :
mhWnd( hWnd ),
mDeviceCounter( 0 )
{
for ( int i = 0; i < MAX_JXINPUTS; ++i )
{
mDevices[ i ] = NULL;
}
if ( FAILED( InitDirectInput( hWnd ) ) )
{
FreeDirectInput();
}
}
JXInputManager::~JXInputManager()
{
for ( int i = 0; i < getNumberOfJXInputs(); ++i )
{
delete mDevices[ i ];
mDevices[ i ] = NULL;
}
FreeDirectInput();
}
int JXInputManager::getNumberOfJXInputs() const
{
return mDeviceCounter;
}
JXInput& JXInputManager::getJXInput( int idx ) const
{
assert( idx < mDeviceCounter );
return * mDevices[ idx ];
}
int JXInputManager::getMaxNumberOfAxes() const
{
return JXINPUT_MAX_AXES;
}
int JXInputManager::getMaxNumberOfButtons() const
{
return JXINPUT_MAX_BUTTONS;
}
int JXInputManager::getMaxNumberOfDirectionals() const
{
return JXINPUT_MAX_DIRECTIONALS;
}
//-----------------------------------------------------------------------------
// Name: InitDirectInput()
// Desc: Initialize the DirectInput variables.
//-----------------------------------------------------------------------------
HRESULT JXInputManager::InitDirectInput( HWND hWnd )
{
HRESULT hr;
// Register with the DirectInput subsystem and get a pointer
// to a IDirectInput interface we can use.
// Create a DInput object
if( FAILED( hr = DirectInput8Create( g_hInst, DIRECTINPUT_VERSION,
IID_IDirectInput8, (VOID**)&mpDI, NULL ) ) )
return hr;
// Look for a simple joystick we can use for this sample program.
if( FAILED( hr = mpDI->EnumDevices( DI8DEVCLASS_GAMECTRL,
EnumJoysticksCallback,
(VOID*)this, DIEDFL_ALLDEVICES /*| DIEDFL_INCLUDEPHANTOMS*/ ) ) )
return hr;
// Look for a other devices
if( FAILED( hr = mpDI->EnumDevices( DI8DEVCLASS_DEVICE,
EnumJoysticksCallback,
(VOID*)this, DIEDFL_ALLDEVICES /*| DIEDFL_INCLUDEPHANTOMS*/ ) ) )
return hr;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FreeDirectInput()
// Desc: Initialize the DirectInput variables.
//-----------------------------------------------------------------------------
HRESULT JXInputManager::FreeDirectInput()
{
if ( NULL != mpDI )
mpDI->Release();
mpDI = NULL;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: EnumJoysticksCallback()
// Desc: Called once for each enumerated joystick. If we find one, create a
// device interface on it so we can play with it.
//-----------------------------------------------------------------------------
BOOL CALLBACK JXInputManager::EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance,
VOID* pContext )
{
HRESULT hr;
LPDIRECTINPUTDEVICE8 pJoystick;
JXInputManager* pThis = (JXInputManager*)pContext;
//
// if the maximum number of devices is already registered,
// issue a warning and stop enumeration.
//
if( MAX_JXINPUTS == pThis->mDeviceCounter )
{
OutputDebugString( "Max. number of devices exceeded!" );
return DIENUM_STOP;
}
// Obtain an interface to the enumerated joystick.
hr = pThis->mpDI->CreateDevice( pdidInstance->guidInstance, &pJoystick, NULL );
// If it failed, then we can't use this joystick. (Maybe the user unplugged
// it while we were in the middle of enumerating it.)
if( FAILED(hr) )
return DIENUM_CONTINUE;
JXInput* pJ = new JXInput( pJoystick, pThis->mhWnd );
//
// only register useful devices
//
if( pJ->getNumberOfAxes() + pJ->getNumberOfButtons() + pJ->getNumberOfDirectionals() > 0 )
{
pThis->addJXInput( pJ );
}
else
{
delete pJ;
}
return DIENUM_CONTINUE;
}
/**
* Register a JXInput device.
*/
void JXInputManager::addJXInput( JXInput* pJ )
{
assert( mDeviceCounter < MAX_JXINPUTS );
if( mDeviceCounter < MAX_JXINPUTS )
mDevices[ mDeviceCounter++ ] = pJ;
}

View File

@@ -1,47 +0,0 @@
// JXInputManager.h: Schnittstelle f<>r die Klasse JXInputManager.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_JXINPUTMANAGER_H__24862402_14C9_407D_8532_A16A6E3A7D64__INCLUDED_)
#define AFX_JXINPUTMANAGER_H__24862402_14C9_407D_8532_A16A6E3A7D64__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_JXINPUTS 10
class JXInput;
class JXINPUT_API JXInputManager
{
public:
JXInputManager( HWND hWnd );
virtual ~JXInputManager();
int getNumberOfJXInputs() const;
JXInput& getJXInput( int idx ) const;
//
// Numbering methods
//
int getMaxNumberOfAxes() const;
int getMaxNumberOfButtons() const;
int getMaxNumberOfDirectionals() const;
private:
LPDIRECTINPUT8 mpDI;
HWND mhWnd;
JXInput* mDevices[ MAX_JXINPUTS ];
int mDeviceCounter;
HRESULT InitDirectInput( HWND hWnd = NULL );
HRESULT FreeDirectInput();
static BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance,
VOID* pContext );
void addJXInput( JXInput* pJ );
};
#endif // !defined(AFX_JXINPUTMANAGER_H__24862402_14C9_407D_8532_A16A6E3A7D64__INCLUDED_)

View File

@@ -1,37 +0,0 @@
========================================================================
DYNAMIC LINK LIBRARY : jxinput
========================================================================
Diese jxinput-DLL hat der Anwendungs-Assistent f<>r Sie erstellt.
Diese Datei enth<74>lt eine Zusammenfassung dessen, was Sie in jeder der Dateien
finden, die Ihre jxinput-Anwendung bilden.
jxinput.dsp
Diese Datei (Projektdatei) enth<74>lt Informationen auf Projektebene und wird zur
Erstellung eines einzelnen Projekts oder Teilprojekts verwendet. Andere Benutzer k<>nnen
die Projektdatei (.dsp) gemeinsam nutzen, sollten aber die Makefiles lokal exportieren.
jxinput.cpp
Dies ist die Hauptquellcodedatei f<>r die DLL.
jxinput.h
Diese Datei enth<74>lt Ihre DLL-Exporte.
/////////////////////////////////////////////////////////////////////////////
Weitere Standarddateien:
StdAfx.h, StdAfx.cpp
Diese Dateien werden zum Erstellen einer vorkompilierten Header-Datei (PCH) namens
jxinput.pch und einer vorkompilierten Typdatei namens StdAfx.obj verwendet.
/////////////////////////////////////////////////////////////////////////////
Weitere Hinweise:
Der Anwendungs-Assistent verwendet "ZU ERLEDIGEN:", um Bereiche des Quellcodes zu
kennzeichnen, die Sie hinzuf<75>gen oder anpassen sollten.
/////////////////////////////////////////////////////////////////////////////

View File

@@ -1,9 +0,0 @@
// stdafx.cpp : Quelltextdatei, die nur die Standard-Includes einbindet
// jxinput.pch ist die vorkompilierte Header-Datei
// stdafx.obj enth<74>lt die vorkompilierte Typinformation
#include "stdafx.h"
// ZU ERLEDIGEN: Verweis auf alle zus<75>tzlichen Header-Dateien, die Sie in STDAFX.H
// und nicht in dieser Datei ben<65>tigen

View File

@@ -1,32 +0,0 @@
// stdafx.h : Include-Datei f<>r Standard-System-Include-Dateien,
// oder projektspezifische Include-Dateien, die h<>ufig benutzt, aber
// in unregelm<6C><6D>igen Abst<73>nden ge<67>ndert werden.
//
#if !defined(AFX_STDAFX_H__68E14C76_098F_47ED_932B_4C01E8E9EFFB__INCLUDED_)
#define AFX_STDAFX_H__68E14C76_098F_47ED_932B_4C01E8E9EFFB__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// F<>gen Sie hier Ihre Header-Dateien ein
#define WIN32_LEAN_AND_MEAN // Selten benutzte Teile der Windows-Header nicht einbinden
#define STRICT
#include <windows.h>
// ZU ERLEDIGEN: Verweisen Sie hier auf zus<75>tzliche Header-Dateien, die Ihr Programm ben<65>tigt
#ifdef JXINPUT_EXPORTS
#define JXINPUT_API __declspec(dllexport)
#else
#define JXINPUT_API __declspec(dllimport)
#endif
#include <dinput.h>
#include <assert.h>
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ f<>gt zus<75>tzliche Deklarationen unmittelbar vor der vorherigen Zeile ein.
#endif // !defined(AFX_STDAFX_H__68E14C76_098F_47ED_932B_4C01E8E9EFFB__INCLUDED_)

View File

@@ -1,279 +0,0 @@
#include "stdafx.h"
#include "de_hardcode_jxinput_directinput_DirectInputDriver.h"
#include "jxinput.h"
#include "JXInputManager.h"
//
// Globals
//
extern HINSTANCE g_hInst;
static JXInputManager* pJXInputManager = NULL;
static JXInput* apJXInput[ MAX_JXINPUTS ];
static HWND hWndJava;
//
// IDs of the static Java arrays.
//
static jfieldID sAxesFieldID;
static jfieldID sButtonsFieldID;
static jfieldID sDirectionsFieldID;
/**
* Remove all resources allocated by the Java binding.
*/
void shutdownJavaResources()
{
if ( NULL != pJXInputManager )
delete pJXInputManager;
if ( NULL != hWndJava )
DestroyWindow( hWndJava );
pJXInputManager = NULL;
for( int i = 0; i < MAX_JXINPUTS; ++i )
apJXInput[ i ] = NULL;
hWndJava = NULL;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
return JNI_VERSION_1_2;
}
JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
{
shutdownJavaResources();
}
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeinit
(JNIEnv * penv, jclass pClazz )
{
//
// Create a non-visible window as 'owner' of the DI device.
//
hWndJava = CreateWindowEx(
0/*WS_EX_APPWINDOW*/, // DWORD dwExStyle, // extended window style
"STATIC", // LPCTSTR lpClassName, // pointer to registered class name
NULL, // LPCTSTR lpWindowName, // pointer to window name
0/*WS_CAPTION*/, // DWORD dwStyle, // window style
0, // int x, // horizontal position of window
0, // int y, // vertical position of window
0, // int nWidth, // window width
0, // int nHeight, // window height
NULL, // HWND hWndParent, // handle to parent or owner window
NULL, // HMENU hMenu, // handle to menu, or child-window identifier
g_hInst, // HINSTANCE hInstance, // handle to application instance
NULL // LPVOID lpParam // pointer to window-creation data
);
if ( NULL == pJXInputManager )
{
pJXInputManager = new JXInputManager( hWndJava );
for( int i = 0; i < MAX_JXINPUTS; ++i )
apJXInput[ i ] = NULL;
for ( int i = 0; i < pJXInputManager->getNumberOfJXInputs(); ++i )
{
apJXInput[ i ] = & pJXInputManager->getJXInput( i );
}
}
return true;
}
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeexit
(JNIEnv *, jclass )
{
shutdownJavaResources();
}
/**
* Bind my field IDs to the Java variables.
*/
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_bind
(JNIEnv * penv, jclass pClazz)
{
//
// All fields are static.
//
sAxesFieldID = penv->GetStaticFieldID( pClazz, "sAxisValues", "[[D" );
sButtonsFieldID = penv->GetStaticFieldID( pClazz, "sButtonStates", "[[Z" );
sDirectionsFieldID = penv->GetStaticFieldID( pClazz, "sDirectionalValues", "[[I" );
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfDevices
(JNIEnv *penv, jclass)
{
return pJXInputManager->getNumberOfJXInputs();
}
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getName
(JNIEnv *penv, jclass, jint dev)
{
return penv->NewStringUTF( apJXInput[ dev ]->getName() );
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfAxes
(JNIEnv *, jclass, jint dev)
{
return apJXInput[ dev ]->getNumberOfAxes();
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfButtons
(JNIEnv *, jclass, jint dev)
{
return apJXInput[ dev ]->getNumberOfButtons();
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfDirectionals
(JNIEnv *, jclass, jint dev)
{
return apJXInput[ dev ]->getNumberOfDirectionals();
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfAxes
(JNIEnv *, jclass)
{
return pJXInputManager->getMaxNumberOfAxes();
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfButtons
(JNIEnv *, jclass)
{
return pJXInputManager->getMaxNumberOfButtons();
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfDirectionals
(JNIEnv *, jclass)
{
return pJXInputManager->getMaxNumberOfDirectionals();
}
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isAxisAvailable
(JNIEnv *, jclass, jint dev, jint idx )
{
return apJXInput[ dev ]->isAxisAvailable( idx );
}
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getAxisName
(JNIEnv *penv, jclass, jint dev, jint idx )
{
return penv->NewStringUTF( apJXInput[ dev ]->getAxisName( idx ) );
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getAxisType
(JNIEnv *, jclass, jint dev, jint idx )
{
return apJXInput[ dev ]->getAxisType( idx );
}
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isButtonAvailable
(JNIEnv *, jclass, jint dev, jint idx )
{
return apJXInput[ dev ]->isButtonAvailable( idx );
}
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getButtonName
(JNIEnv *penv, jclass, jint dev, jint idx )
{
return penv->NewStringUTF( apJXInput[ dev ]->getButtonName( idx ) );
}
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getButtonType
(JNIEnv *, jclass, jint dev, jint idx )
{
return apJXInput[ dev ]->getButtonType( idx );
}
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isDirectionalAvailable
(JNIEnv *, jclass, jint dev, jint idx )
{
return apJXInput[ dev ]->isDirectionalAvailable( idx );
}
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getDirectionalName
(JNIEnv *penv, jclass, jint dev, jint idx )
{
return penv->NewStringUTF( apJXInput[ dev ]->getDirectionalName( idx ) );
}
/**
* The main update method.
* Here, the actual work is done.
*/
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeupdate
(JNIEnv * penv, jclass pClazz )
{
static jdouble axes [ MAX_JXINPUTS ][ JXINPUT_MAX_AXES ];
static jboolean buttons [ MAX_JXINPUTS ][ JXINPUT_MAX_BUTTONS ];
static jint directions [ MAX_JXINPUTS ][ JXINPUT_MAX_DIRECTIONALS ];
static jobjectArray axisarrayarray;
static jobjectArray buttonarrayarray;
static jobjectArray directionarrayarray;
static jdoubleArray axisarray;
static jbooleanArray buttonarray;
static jintArray directionarray;
axisarrayarray = (jobjectArray)penv->GetStaticObjectField( pClazz, sAxesFieldID );
buttonarrayarray = (jobjectArray)penv->GetStaticObjectField( pClazz, sButtonsFieldID );
directionarrayarray = (jobjectArray)penv->GetStaticObjectField( pClazz, sDirectionsFieldID );
//
// For each device....
//
for ( int dev = 0; dev < pJXInputManager->getNumberOfJXInputs(); ++dev )
{
// Do the update of the device.
apJXInput[ dev ]->update();
//
// Copy all values into my arrays.
//
for ( int i = 0; i < JXINPUT_MAX_AXES; ++i )
axes[ dev ][ i ] = apJXInput[ dev ]->getAxisValue( i );
for ( int i = 0; i < JXINPUT_MAX_BUTTONS; ++i )
buttons[ dev ][ i ] = apJXInput[ dev ]->isButtonDown( i );
for ( int i = 0; i < JXINPUT_MAX_DIRECTIONALS; ++i )
directions[ dev ][ i ] = apJXInput[ dev ]->getDirection( i );
//
// Move my arrays to the Java arrays.
//
axisarray = (jdoubleArray)penv->GetObjectArrayElement( axisarrayarray, dev );
penv->SetDoubleArrayRegion( axisarray, 0, JXINPUT_MAX_AXES, axes[ dev ] );
buttonarray = (jbooleanArray)penv->GetObjectArrayElement( buttonarrayarray, dev );
penv->SetBooleanArrayRegion( buttonarray, 0, JXINPUT_MAX_BUTTONS, buttons[ dev ] );
directionarray = (jintArray)penv->GetObjectArrayElement( directionarrayarray, dev );
penv->SetIntArrayRegion( directionarray, 0, JXINPUT_MAX_DIRECTIONALS, directions[ dev ] );
}
}

View File

@@ -1,183 +0,0 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class de_hardcode_jxinput_directinput_DirectInputDriver */
#ifndef _Included_de_hardcode_jxinput_directinput_DirectInputDriver
#define _Included_de_hardcode_jxinput_directinput_DirectInputDriver
#ifdef __cplusplus
extern "C" {
#endif
/* Inaccessible static: sIsOperational */
/* Inaccessible static: sAxisValues */
/* Inaccessible static: sButtonStates */
/* Inaccessible static: sDirectionalValues */
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: nativeinit
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeinit
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: nativeexit
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeexit
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: bind
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_bind
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getNumberOfDevices
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfDevices
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getName
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getName
(JNIEnv *, jclass, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getNumberOfAxes
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfAxes
(JNIEnv *, jclass, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getNumberOfButtons
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfButtons
(JNIEnv *, jclass, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getNumberOfDirectionals
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getNumberOfDirectionals
(JNIEnv *, jclass, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getMaxNumberOfAxes
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfAxes
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getMaxNumberOfButtons
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfButtons
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getMaxNumberOfDirectionals
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getMaxNumberOfDirectionals
(JNIEnv *, jclass);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: isAxisAvailable
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isAxisAvailable
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getAxisName
* Signature: (II)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getAxisName
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getAxisType
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getAxisType
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: isButtonAvailable
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isButtonAvailable
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getButtonName
* Signature: (II)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getButtonName
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getButtonType
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getButtonType
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: isDirectionalAvailable
* Signature: (II)Z
*/
JNIEXPORT jboolean JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_isDirectionalAvailable
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: getDirectionalName
* Signature: (II)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_getDirectionalName
(JNIEnv *, jclass, jint, jint);
/*
* Class: de_hardcode_jxinput_directinput_DirectInputDriver
* Method: nativeupdate
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_de_hardcode_jxinput_directinput_DirectInputDriver_nativeupdate
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,24 +0,0 @@
#include "stdafx.h"
HINSTANCE g_hInst;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_hInst = (HINSTANCE)hModule;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
g_hInst = NULL;
break;
}
return TRUE;
}

View File

@@ -1,600 +0,0 @@
//
// jxinput.cpp
//
#include "stdafx.h"
#include "jxinput.h"
//
// Globals
//
extern HINSTANCE g_hInst;
/**
* Ctor: Connect with DI
*/
JXInput::JXInput( LPDIRECTINPUTDEVICE8 pJoystick, HWND hWnd ) :
mpJoystick( pJoystick ),
mSliderCount( 0 ),
mPOVCount( 0 ),
mButtonCount( 0 )
{
initAxisConfig();
initButtonsConfig();
initDirectionalsConfig();
if ( FAILED( InitDirectInput( hWnd ) ) )
{
FreeDirectInput();
}
}
/**
* Destructor:
* Free DirectInput.
*/
JXInput::~JXInput()
{
FreeDirectInput();
}
void JXInput::update()
{
UpdateInputState();
}
TCHAR * const JXInput::getName() const
{
return (TCHAR*)mdiDevInfo.tszInstanceName;
}
int JXInput::getNumberOfAxes() const
{
return mdiDevCaps.dwAxes;
}
int JXInput::getNumberOfButtons() const
{
return mButtonCount;
}
int JXInput::getNumberOfDirectionals() const
{
return mPOVCount;
}
double JXInput::getAxisValueHelper( LONG val, int idx ) const
{
const AxisConfig& cfg = mAxisConfig[ idx ];
double span = (double)( cfg.mMaxValue - cfg.mMinValue );
double ret = (double)(val - cfg.mMinValue) / span;
if ( TYPE_SLIDER != cfg.mType )
return ret*2.0 - 1.0;
return ret;
}
double JXInput::getX() const
{
return getAxisValueHelper( mJS.lX, ID_X );
}
double JXInput::getY() const
{
return getAxisValueHelper( mJS.lY, ID_Y );
}
double JXInput::getZ() const
{
return getAxisValueHelper( mJS.lZ, ID_Z );
}
double JXInput::getRotX() const
{
return getAxisValueHelper( mJS.lRx, ID_ROTX );
}
double JXInput::getRotY() const
{
return getAxisValueHelper( mJS.lRy, ID_ROTY );
}
double JXInput::getRotZ() const
{
return getAxisValueHelper( mJS.lRz, ID_ROTZ );
}
double JXInput::getSlider0() const
{
return getAxisValueHelper( mJS.rglSlider[ 0 ], ID_SLIDER0 );
}
double JXInput::getSlider1() const
{
return getAxisValueHelper( mJS.rglSlider[ 1 ], ID_SLIDER1 );
}
bool JXInput::isAxisAvailable( int idx ) const
{
assert( idx < JXINPUT_MAX_AXES );
return mAxisConfig[ idx ].mIsAvailable;
}
TCHAR * const JXInput::getAxisName( int idx ) const
{
assert( idx < JXINPUT_MAX_AXES );
return (char*const)mAxisConfig[ idx ].mName;
}
int JXInput::getAxisType( int idx ) const
{
assert( idx < JXINPUT_MAX_AXES );
return mAxisConfig[ idx ].mType;
}
double JXInput::getAxisValue( int idx ) const
{
assert( idx < JXINPUT_MAX_AXES );
// Failsafe if called accidentally
if ( ! mAxisConfig[ idx ].mIsAvailable )
return 0.0;
return (this->*mAxisConfig[ idx ].mGetValueMethod)();
}
bool JXInput::isButtonAvailable( int idx ) const
{
assert( idx < JXINPUT_MAX_BUTTONS );
return mButtonConfig[ idx ].mIsAvailable;
}
TCHAR * const JXInput::getButtonName( int idx ) const
{
assert( idx < JXINPUT_MAX_BUTTONS );
return (char*const)mButtonConfig[ idx ].mName;
}
int JXInput::getButtonType( int idx ) const
{
assert( idx < JXINPUT_MAX_BUTTONS );
return mButtonConfig[ idx ].mType;
}
bool JXInput::isButtonDown( int idx ) const
{
assert( idx < JXINPUT_MAX_BUTTONS );
return 0 != mJS.rgbButtons[ idx ] ;
}
bool JXInput::isDirectionalAvailable( int idx ) const
{
assert( idx < JXINPUT_MAX_DIRECTIONALS );
return mDirectionalConfig[ idx ].mIsAvailable;
}
TCHAR * const JXInput::getDirectionalName( int idx ) const
{
assert( idx < JXINPUT_MAX_DIRECTIONALS );
return (char*const)mDirectionalConfig[ idx ].mName;
}
int JXInput::getDirection( int idx ) const
{
assert( idx < JXINPUT_MAX_DIRECTIONALS );
return mJS.rgdwPOV[ idx ] ;
}
/**
* Initialize axis configuration array.
*/
void JXInput::initAxisConfig()
{
mAxisConfig[ ID_X ].mIsAvailable = false;
mAxisConfig[ ID_X ].mType = TYPE_TRANSLATION;
mAxisConfig[ ID_X ].mGetValueMethod = &JXInput::getX;
mAxisConfig[ ID_Y ].mIsAvailable = false;
mAxisConfig[ ID_Y ].mType = TYPE_TRANSLATION;
mAxisConfig[ ID_Y ].mGetValueMethod = &JXInput::getY;
mAxisConfig[ ID_Z ].mIsAvailable = false;
mAxisConfig[ ID_Z ].mType = TYPE_TRANSLATION;
mAxisConfig[ ID_Z ].mGetValueMethod = &JXInput::getZ;
mAxisConfig[ ID_ROTX ].mIsAvailable = false;
mAxisConfig[ ID_ROTX ].mType = TYPE_ROTATION;
mAxisConfig[ ID_ROTX ].mGetValueMethod = &JXInput::getRotX;
mAxisConfig[ ID_ROTY ].mIsAvailable = false;
mAxisConfig[ ID_ROTY ].mType = TYPE_ROTATION;
mAxisConfig[ ID_ROTY ].mGetValueMethod = &JXInput::getRotY;
mAxisConfig[ ID_ROTZ ].mIsAvailable = false;
mAxisConfig[ ID_ROTZ ].mType = TYPE_ROTATION;
mAxisConfig[ ID_ROTZ ].mGetValueMethod = &JXInput::getRotZ;
mAxisConfig[ ID_SLIDER0 ].mIsAvailable = false;
mAxisConfig[ ID_SLIDER0 ].mType = TYPE_SLIDER;
mAxisConfig[ ID_SLIDER0 ].mGetValueMethod = &JXInput::getSlider0;
mAxisConfig[ ID_SLIDER1 ].mIsAvailable = false;
mAxisConfig[ ID_SLIDER1 ].mType = TYPE_SLIDER;
mAxisConfig[ ID_SLIDER1 ].mGetValueMethod = &JXInput::getSlider1;
}
/**
* Initialize buttons configuration array.
*/
void JXInput::initButtonsConfig()
{
for ( int i = 0; i < JXINPUT_MAX_BUTTONS; ++i )
{
mButtonConfig[ i ].mIsAvailable = false;
mButtonConfig[ i ].mName[ 0 ] = '\0';
mButtonConfig[ i ].mType = TYPE_PUSHBUTTON;
}
}
/**
* Initialize directionals configuration array.
*/
void JXInput::initDirectionalsConfig()
{
for ( int i = 0; i < JXINPUT_MAX_DIRECTIONALS; ++i )
{
mDirectionalConfig[ i ].mIsAvailable = false;
mDirectionalConfig[ i ].mName[ 0 ] = '\0';
}
}
//-----------------------------------------------------------------------------
// Name: EnumAxesCallback()
// Desc: Callback function for enumerating the axes on a joystick
//-----------------------------------------------------------------------------
BOOL CALLBACK JXInput::EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext )
{
JXInput* pThis = (JXInput*)pContext;
AxisConfig* pAxCfg = NULL;
// Set the UI to reflect what objects the joystick supports
// Code derived from M$ samples, really sucks, eh?
if (pdidoi->guidType == GUID_XAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_X ];
}
if (pdidoi->guidType == GUID_YAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_Y ];
}
if (pdidoi->guidType == GUID_ZAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_Z ];
}
if (pdidoi->guidType == GUID_RxAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_ROTX ];
}
if (pdidoi->guidType == GUID_RyAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_ROTY ];
}
if (pdidoi->guidType == GUID_RzAxis)
{
pAxCfg = & pThis->mAxisConfig[ ID_ROTZ ];
}
if (pdidoi->guidType == GUID_Slider)
{
switch( pThis->mSliderCount++ )
{
case 0 :
pAxCfg = & pThis->mAxisConfig[ ID_SLIDER0 ];
break;
case 1 :
pAxCfg = & pThis->mAxisConfig[ ID_SLIDER1 ];
break;
}
}
// fail-safe
if( NULL == pAxCfg ) // e.g. GUID_Unknown
return DIENUM_CONTINUE;
//
// Perform config.
//
DIPROPRANGE diprg;
diprg.diph.dwSize = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow = DIPH_BYID;
diprg.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis
// Get the range for the axis
if( FAILED( pThis->mpJoystick->GetProperty( DIPROP_RANGE, &diprg.diph ) ) )
return DIENUM_CONTINUE;
pAxCfg->mMinValue = diprg.lMin;
pAxCfg->mMaxValue = diprg.lMax;
strcpy( (char*)pAxCfg->mName, (char*)pdidoi->tszName );
pAxCfg->mIsAvailable = true;
return DIENUM_CONTINUE;
}
//-----------------------------------------------------------------------------
// Name: EnumButtonsCallback()
// Desc: Callback function for enumerating the axes on a joystick
//-----------------------------------------------------------------------------
BOOL CALLBACK JXInput::EnumButtonsCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext )
{
JXInput* pThis = (JXInput*)pContext;
//
// if the maximum number of buttons is already registered,
// issue a warning and stop enumeration.
//
if( JXINPUT_MAX_BUTTONS == pThis->mButtonCount )
{
OutputDebugString( "Max. number of buttons exceeded!" );
return DIENUM_STOP;
}
ButtonConfig* pBtCfg = NULL;
if ( pdidoi->guidType == GUID_Button )
{
assert( JXINPUT_MAX_BUTTONS > pThis->mButtonCount );
pBtCfg = & pThis->mButtonConfig[ pThis->mButtonCount++ ];
}
// fail-safe
if( NULL == pBtCfg ) // e.g. unknown stuff
return DIENUM_CONTINUE;
assert( NULL != pBtCfg );
//
// Perform config.
//
strcpy( (char*)pBtCfg->mName, (char*)pdidoi->tszName );
pBtCfg->mIsAvailable = true;
return DIENUM_CONTINUE;
}
//-----------------------------------------------------------------------------
// Name: EnumPOVsCallback()
// Desc: Callback function for enumerating the axes on a joystick
//-----------------------------------------------------------------------------
BOOL CALLBACK JXInput::EnumPOVsCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext )
{
JXInput* pThis = (JXInput*)pContext;
//
// if the maximum number of buttons is already registered,
// issue a warning and stop enumeration.
//
if( JXINPUT_MAX_DIRECTIONALS == pThis->mPOVCount )
{
OutputDebugString( "Max. number of POVs exceeded!" );
return DIENUM_STOP;
}
DirectionalConfig* pDirCfg = NULL;
if (pdidoi->guidType == GUID_POV)
{
assert( JXINPUT_MAX_DIRECTIONALS > pThis->mPOVCount );
pDirCfg = & pThis->mDirectionalConfig[ pThis->mPOVCount++ ];
}
// fail-safe
if( NULL == pDirCfg ) // e.g. unknown stuff
return DIENUM_CONTINUE;
assert( NULL != pDirCfg );
//
// Perform config.
//
strcpy( (char*)pDirCfg->mName, (char*)pdidoi->tszName );
pDirCfg->mIsAvailable = true;
return DIENUM_CONTINUE;
}
//-----------------------------------------------------------------------------
// Name: EnumEffectsCallback()
// Desc: Callback function for enumerating the effects of a joystick
//-----------------------------------------------------------------------------
BOOL CALLBACK JXInput::EnumEffectsCallback( const DIEFFECTINFO* pdidoi,
VOID* pContext )
{
JXInput* pThis = (JXInput*)pContext;
//
// Work on that!!
//
return DIENUM_CONTINUE;
}
//-----------------------------------------------------------------------------
// Name: InitDirectInput()
// Desc: Initialize the DirectInput variables.
//-----------------------------------------------------------------------------
HRESULT JXInput::InitDirectInput( HWND hWnd )
{
HRESULT hr;
// Make sure we got a joystick
if( NULL == mpJoystick )
{
return E_FAIL;
}
//
// Ask the device for some useful information.
//
mdiDevInfo.dwSize = sizeof( DIDEVICEINSTANCE );
hr = mpJoystick->GetDeviceInfo( &mdiDevInfo );
if( FAILED(hr) )
return hr;
// Set the data format to "simple joystick" - a predefined data format
//
// A data format specifies which controls on a device we are interested in,
// and how they should be reported. This tells DInput that we will be
// passing a DIJOYSTATE structure to IDirectInputDevice::GetDeviceState().
hr = mpJoystick->SetDataFormat( &c_dfDIJoystick2 );
if( FAILED(hr) )
return hr;
// Set the cooperative level to let DInput know how this device should
// interact with the system and with other DInput applications.
// hr = g_pJoystick->SetCooperativeLevel( hDlg, DISCL_EXCLUSIVE|DISCL_FOREGROUND );
DWORD mode = ( NULL == hWnd ? DISCL_NONEXCLUSIVE|DISCL_BACKGROUND : DISCL_EXCLUSIVE|DISCL_BACKGROUND );
hr = mpJoystick->SetCooperativeLevel( hWnd, mode );
if( FAILED(hr) )
return hr;
// Determine how many axis the joystick has (so we don't error out setting
// properties for unavailable axis)
mdiDevCaps.dwSize = sizeof(DIDEVCAPS);
hr = mpJoystick->GetCapabilities(&mdiDevCaps);
if ( FAILED(hr) )
return hr;
// Enumerate the axes of the joyctick and set the range of each axis. Note:
// we could just use the defaults, but we're just trying to show an example
// of enumerating device objects (axes, buttons, etc.).
mpJoystick->EnumObjects( EnumAxesCallback, (VOID*)this, DIDFT_AXIS );
mpJoystick->EnumObjects( EnumButtonsCallback, (VOID*)this, DIDFT_BUTTON );
mpJoystick->EnumObjects( EnumPOVsCallback, (VOID*)this, DIDFT_POV );
mpJoystick->EnumEffects( EnumEffectsCallback, (VOID*)this, DIEFT_ALL );
// For FF sticks, switch on autocenter as long as we do not use real FF
SwitchAutoCenter( true );
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: UpdateInputState()
// Desc: Get the input device's state and display it.
//-----------------------------------------------------------------------------
HRESULT JXInput::UpdateInputState()
{
HRESULT hr;
if( mpJoystick )
{
// Poll the device to read the current state
hr = mpJoystick->Poll();
if( FAILED(hr) )
{
// DInput is telling us that the input stream has been
// interrupted. We aren't tracking any state between polls, so
// we don't have any special reset that needs to be done. We
// just re-acquire and try again.
hr = mpJoystick->Acquire();
while( hr == DIERR_INPUTLOST )
hr = mpJoystick->Acquire();
// hr may be DIERR_OTHERAPPHASPRIO or other errors. This
// may occur when the app is minimized or in the process of
// switching, so just try again later
return S_OK;
}
// Get the input's device state
if( FAILED( hr = mpJoystick->GetDeviceState( sizeof(DIJOYSTATE2), &mJS ) ) )
return hr; // The device should have been acquired during the Poll()
}
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FreeDirectInput()
// Desc: Initialize the DirectInput variables.
//-----------------------------------------------------------------------------
HRESULT JXInput::FreeDirectInput()
{
// Unacquire and release any DirectInputDevice objects.
if( NULL != mpJoystick )
{
// Unacquire the device one last time just in case
// the app tried to exit while the device is still acquired.
mpJoystick->Unacquire();
mpJoystick->Release();
mpJoystick = NULL;
}
return S_OK;
}
HRESULT JXInput::SwitchAutoCenter( bool onoff )
{
HRESULT hr;
DIPROPDWORD DIPropAutoCenter;
DIPropAutoCenter.diph.dwSize = sizeof(DIPropAutoCenter);
DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
DIPropAutoCenter.diph.dwObj = 0;
DIPropAutoCenter.diph.dwHow = DIPH_DEVICE;
DIPropAutoCenter.dwData = ( onoff ? DIPROPAUTOCENTER_ON : DIPROPAUTOCENTER_OFF );
hr = mpJoystick->SetProperty( DIPROP_AUTOCENTER, &DIPropAutoCenter.diph );
return hr;
}

View File

@@ -1,175 +0,0 @@
# Microsoft Developer Studio Project File - Name="jxinput" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** NICHT BEARBEITEN **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
CFG=jxinput - Win32 Debug
!MESSAGE Dies ist kein g<>ltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE
!MESSAGE verwenden Sie den Befehl "Makefile exportieren" und f<>hren Sie den Befehl
!MESSAGE
!MESSAGE NMAKE /f "jxinput.mak".
!MESSAGE
!MESSAGE Sie k<>nnen beim Ausf<73>hren von NMAKE eine Konfiguration angeben
!MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel:
!MESSAGE
!MESSAGE NMAKE /f "jxinput.mak" CFG="jxinput - Win32 Debug"
!MESSAGE
!MESSAGE F<>r die Konfiguration stehen zur Auswahl:
!MESSAGE
!MESSAGE "jxinput - Win32 Release" (basierend auf "Win32 (x86) Dynamic-Link Library")
!MESSAGE "jxinput - Win32 Debug" (basierend auf "Win32 (x86) Dynamic-Link Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
MTL=midl.exe
RSC=rc.exe
!IF "$(CFG)" == "jxinput - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JXINPUT_EXPORTS" /Yu"stdafx.h" /FD /c
# ADD CPP /nologo /MT /W3 /GX /O2 /I "C:\j2sdk1.4.2\include" /I "C:\j2sdk1.4.2\include\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JXINPUT_EXPORTS" /FR /Yu"stdafx.h" /FD /c
# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x407 /d "NDEBUG"
# ADD RSC /l 0x407 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
# ADD LINK32 dxguid.lib dinput8.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"..\build\jxinput.dll"
!ELSEIF "$(CFG)" == "jxinput - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Ignore_Export_Lib 0
# PROP Target_Dir ""
# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JXINPUT_EXPORTS" /Yu"stdafx.h" /FD /GZ /c
# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "C:\j2sdk1.4.2\include" /I "C:\j2sdk1.4.2\include\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "JXINPUT_EXPORTS" /FR /Yu"stdafx.h" /FD /GZ /c
# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
# ADD BASE RSC /l 0x407 /d "_DEBUG"
# ADD RSC /l 0x407 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
# ADD LINK32 dxguid.lib dinput8.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"..\Classes\jxinput.dll" /pdbtype:sept
!ENDIF
# Begin Target
# Name "jxinput - Win32 Release"
# Name "jxinput - Win32 Debug"
# Begin Group "Quellcodedateien"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=.\de_hardcode_jxinput_directinput_DirectInputDriver.cpp
# End Source File
# Begin Source File
SOURCE=.\dllmain.cpp
# End Source File
# Begin Source File
SOURCE=.\jxinput.cpp
# End Source File
# Begin Source File
SOURCE=.\JXInputManager.cpp
# End Source File
# Begin Source File
SOURCE=.\StdAfx.cpp
# ADD CPP /Yc"stdafx.h"
# End Source File
# End Group
# Begin Group "Header-Dateien"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=.\de_hardcode_jxinput_directinput_DirectInputDriver.h
!IF "$(CFG)" == "jxinput - Win32 Release"
# PROP Ignore_Default_Tool 1
USERDEP__DE_HA="..\classes\de\hardcode\jxinput\directinput\DirectInputDriver.class"
# Begin Custom Build
InputPath=.\de_hardcode_jxinput_directinput_DirectInputDriver.h
"de_hardcode_jxinput_directinput_DirectInputDriver.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
cd ..\Classes
C:\j2sdk1.4.2\bin\javah -classpath . -d ..\win32 de.hardcode.jxinput.directinput.DirectInputDriver
cd ..\win32
# End Custom Build
!ELSEIF "$(CFG)" == "jxinput - Win32 Debug"
# PROP Ignore_Default_Tool 1
USERDEP__DE_HA="..\classes\de\hardcode\jxinput\directinput\DirectInputDriver.class"
# Begin Custom Build
InputPath=.\de_hardcode_jxinput_directinput_DirectInputDriver.h
"de_hardcode_jxinput_directinput_DirectInputDriver.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
cd ..\Classes
C:\j2sdk1.4.2\bin\javah -classpath . -d ..\win32 de.hardcode.jxinput.directinput.DirectInputDriver
cd ..\win32
# End Custom Build
!ENDIF
# End Source File
# Begin Source File
SOURCE=.\jxinput.h
# End Source File
# Begin Source File
SOURCE=.\JXInputManager.h
# End Source File
# Begin Source File
SOURCE=.\StdAfx.h
# End Source File
# End Group
# Begin Group "Ressourcendateien"
# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
# End Group
# Begin Source File
SOURCE=.\ReadMe.txt
# End Source File
# End Target
# End Project

View File

@@ -1,29 +0,0 @@
Microsoft Developer Studio Workspace File, Format Version 6.00
# WARNUNG: DIESE ARBEITSBEREICHSDATEI DARF NICHT BEARBEITET ODER GEL<45>SCHT WERDEN!
###############################################################################
Project: "jxinput"=".\jxinput.dsp" - Package Owner=<4>
Package=<5>
{{{
}}}
Package=<4>
{{{
}}}
###############################################################################
Global:
Package=<5>
{{{
}}}
Package=<3>
{{{
}}}
###############################################################################

View File

@@ -1,183 +0,0 @@
#define JXINPUT_MAX_AXES 8
#define JXINPUT_MAX_BUTTONS 256
#define JXINPUT_MAX_DIRECTIONALS 4
/**
* This class will be exported by jxinput.dll.
*/
class JXINPUT_API JXInput
{
public:
typedef enum AXISTYPE
{
TYPE_TRANSLATION,
TYPE_ROTATION,
TYPE_SLIDER
};
typedef enum BUTTONTYPE
{
TYPE_PUSHBUTTON,
TYPE_TOGGLEBUTTON
};
typedef enum AXISID
{
ID_X, ID_Y, ID_Z,
ID_ROTX, ID_ROTY, ID_ROTZ,
ID_SLIDER0, ID_SLIDER1
};
//
// Ctor
//
JXInput( LPDIRECTINPUTDEVICE8 pJoystick, HWND hWnd = NULL );
//
// Dtor
//
virtual ~JXInput();
//
// Operational methods
//
void update();
// Ask for the name
TCHAR * const getName() const;
//
// Numbering methods
//
int getNumberOfAxes() const;
int getNumberOfButtons() const;
int getNumberOfDirectionals() const;
//
// Access axes
//
double getX() const; /** -1.0 .... 1.0 */
double getY() const; /** -1.0 .... 1.0 */
double getZ() const; /** -1.0 .... 1.0 */
double getRotX() const; /** -1.0 .... 1.0 */
double getRotY() const; /** -1.0 .... 1.0 */
double getRotZ() const; /** -1.0 .... 1.0 */
double getSlider0() const; /** 0.0 .... 1.0 */
double getSlider1() const; /** 0.0 .... 1.0 */
//
// Axis methods
//
bool isAxisAvailable( int idx ) const;
TCHAR* const getAxisName( int idx ) const;
int getAxisType( int idx ) const;
double getAxisValue( int idx ) const;
//
// Button methods
//
bool isButtonAvailable( int idx ) const;
TCHAR* const getButtonName( int idx ) const;
int getButtonType( int idx ) const;
bool isButtonDown( int idx ) const;
//
// Directional methods
//
bool isDirectionalAvailable( int idx ) const;
TCHAR* const getDirectionalName( int idx ) const;
int getDirection( int idx ) const;
private://-----------------------------------------------------------------------------------------
LPDIRECTINPUTDEVICE8 mpJoystick;
DIDEVICEINSTANCE mdiDevInfo;
DIDEVCAPS mdiDevCaps;
DIJOYSTATE2 mJS; // DInput joystick state
int mSliderCount;
int mPOVCount;
int mButtonCount;
double getAxisValueHelper( LONG val, int idx ) const;
HRESULT SwitchAutoCenter( bool onoff = true );
HRESULT InitDirectInput( HWND hWnd = NULL );
HRESULT FreeDirectInput();
HRESULT UpdateInputState();
static BOOL CALLBACK EnumAxesCallback
(
const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext
);
static BOOL CALLBACK EnumButtonsCallback
(
const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext
);
static BOOL CALLBACK EnumPOVsCallback
(
const DIDEVICEOBJECTINSTANCE* pdidoi,
VOID* pContext
);
static BOOL CALLBACK EnumEffectsCallback
(
const DIEFFECTINFO* pdidoi,
VOID* pContext
);
class JXINPUT_API AxisConfig
{
public:
bool mIsAvailable;
CHAR mName[MAX_PATH];
AXISTYPE mType;
LONG mMinValue;
LONG mMaxValue;
double (JXInput::*mGetValueMethod)() const;
} mAxisConfig [ JXINPUT_MAX_AXES ];
void initAxisConfig();
class JXINPUT_API ButtonConfig
{
public:
bool mIsAvailable;
CHAR mName[MAX_PATH];
BUTTONTYPE mType;
} mButtonConfig[ JXINPUT_MAX_BUTTONS ];
void initButtonsConfig();
class JXINPUT_API DirectionalConfig
{
public:
bool mIsAvailable;
CHAR mName[MAX_PATH];
} mDirectionalConfig[ JXINPUT_MAX_DIRECTIONALS ];
void initDirectionalsConfig();
};

View File

@@ -1,20 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 9.00
# Visual C++ Express 2005
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jxinput", "jxinput.vcproj", "{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}.Debug|Win32.ActiveCfg = Debug|Win32
{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}.Debug|Win32.Build.0 = Debug|Win32
{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}.Release|Win32.ActiveCfg = Release|Win32
{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,367 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8,00"
Name="jxinput"
ProjectGUID="{8AEA84DC-D8F0-4425-BEBF-A84E91115F76}"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Release|Win32"
OutputDirectory=".\Release"
IntermediateDirectory=".\Release"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="NDEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Release/jxinput.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="C:\Programme\Java\jdk1.5.0_06\include;C:\Programme\Java\jdk1.5.0_06\include\win32"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;JXINPUT_EXPORTS"
StringPooling="true"
RuntimeLibrary="0"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="stdafx.h"
PrecompiledHeaderFile=".\Release/jxinput.pch"
AssemblerListingLocation=".\Release/"
ObjectFile=".\Release/"
ProgramDataBaseFileName=".\Release/"
BrowseInformation="1"
WarningLevel="3"
SuppressStartupBanner="true"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="1031"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="dxguid.lib dinput8.lib user32.lib"
OutputFile="..\build\jxinput.dll"
LinkIncremental="1"
SuppressStartupBanner="true"
ProgramDatabaseFile=".\Release/jxinput.pdb"
ImportLibrary=".\Release/jxinput.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Release/jxinput.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Debug|Win32"
OutputDirectory="..\classes"
IntermediateDirectory=".\Debug"
ConfigurationType="2"
InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC60.vsprops"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="false"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
PreprocessorDefinitions="_DEBUG"
MkTypLibCompatible="true"
SuppressStartupBanner="true"
TargetEnvironment="1"
TypeLibraryName=".\Debug/jxinput.tlb"
HeaderFileName=""
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="C:\Programme\Java\jdk1.5.0_06\include;C:\Programme\Java\jdk1.5.0_06\include\win32"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;JXINPUT_EXPORTS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="2"
PrecompiledHeaderThrough="stdafx.h"
PrecompiledHeaderFile=".\Debug/jxinput.pch"
AssemblerListingLocation=".\Debug/"
ObjectFile=".\Debug/"
ProgramDataBaseFileName=".\Debug/"
BrowseInformation="1"
WarningLevel="3"
SuppressStartupBanner="true"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="1031"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="dxguid.lib dinput8.lib user32.lib"
OutputFile="..\Classes\jxinput.dll"
LinkIncremental="2"
SuppressStartupBanner="true"
GenerateDebugInformation="true"
ProgramDatabaseFile=".\Debug/jxinput.pdb"
ImportLibrary=".\Debug/jxinput.lib"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile=".\Debug/jxinput.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCWebDeploymentTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Quellcodedateien"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
>
<File
RelativePath="de_hardcode_jxinput_directinput_DirectInputDriver.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<File
RelativePath="dllmain.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<File
RelativePath="jxinput.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<File
RelativePath="JXInputManager.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
/>
</FileConfiguration>
</File>
<File
RelativePath="StdAfx.cpp"
>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
UsePrecompiledHeader="1"
/>
</FileConfiguration>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
AdditionalIncludeDirectories=""
PreprocessorDefinitions=""
UsePrecompiledHeader="1"
/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header-Dateien"
Filter="h;hpp;hxx;hm;inl"
>
<File
RelativePath="de_hardcode_jxinput_directinput_DirectInputDriver.h"
>
</File>
<File
RelativePath="jxinput.h"
>
</File>
<File
RelativePath="JXInputManager.h"
>
</File>
<File
RelativePath="StdAfx.h"
>
</File>
</Filter>
<Filter
Name="Ressourcendateien"
Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
>
</Filter>
<File
RelativePath="ReadMe.txt"
>
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -1,72 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 19. Dezember 2001, 21:58
//**********************************************************************************************
package de.hardcode.jxinput;
/**
* The Axis interface describes the most common feature of a joystick or other input devices.
*
* @author Herkules
*/
public interface Axis extends Feature
{
// Enumeration of axes.
final static int ID_X = 0;
final static int ID_Y = 1;
final static int ID_Z = 2;
final static int ID_ROTX = 3;
final static int ID_ROTY = 4;
final static int ID_ROTZ = 5;
final static int ID_SLIDER0 = 6;
final static int ID_SLIDER1 = 7;
final static int NUMBER_OF_ID = 8;
// Enumeration of axis types
final static int TRANSLATION = 0;
final static int ROTATION = 1;
final static int SLIDER = 2;
/**
* Retrieve the type of the axis.
* The type is describes the meaning and the range of values of the axis.
* <p>
* <code>TRANSLATION</code> typed axes denote a translational deviation from a center
* position. This can be e.g. the common, basic joystick axes.
* The range of <code>getValue()</code> is <code>[-1.0,1.0]</code>.
* <p>
* <code>ROTATION</code> typed axes denote a rotational deviation from a center
* position. Something on the stick is turned or twisted.
* The range of <code>getValue()</code> is <code>[-1.0,1.0]</code>.
* <p>
* <code>SLIDER</code> typed axes denote a shifting device without a center position.
* A good sample is a throttle control.
* The range of <code>getValue()</code> is <code>[0.0,1.0]</code>.
*
* @return [ TRANSLATION | ROTATION | SLIDER ]
*/
int getType();
/**
* Returns the current value of the axis.
* The range of the result depends on the axis type.
*
* @return value [-1.0,1.0] or [0.0,1.0]
*/
double getValue();
/**
* Inform about the resolution of the axis.
*
* @return resolution, e.g. 2^-16
*/
double getResolution();
}

View File

@@ -1,35 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 19. Dezember 2001, 21:58
//**********************************************************************************************
package de.hardcode.jxinput;
/**
*
* @author Herkules
*/
public interface Button extends Feature
{
// Enumeration of button types
final static int PUSHBUTTON = 0;
final static int TOGGLEBUTTON = 1;
/**
* Retrieve the type of the button.
* Pushbutton will deliver <code>true==getState()</code> as long as they are pressed down.
* Togglebuttons will change their state once they are pressed and keep that state
* until they are pressed again.
* @return [ PUSHBUTTON | TOGGLEBUTTON ]
*/
int getType();
/**
* Tells the state of the button at last update.
*/
boolean getState();
}

View File

@@ -1,45 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 27. Dezember 2001, 23:33
//**********************************************************************************************
package de.hardcode.jxinput;
/**
*
* @author Herkules
*/
public interface Directional extends Feature
{
/**
* If the Directional has a center position where it points to no direction, this
* flag is true when this position is reached.
*/
boolean isCentered();
/**
* Retrieve the direction pointed to.
* Value is given in 1/100 degree, [0,36000]
*/
int getDirection();
/**
* Retrieve the analog value pointing to the angle described by
* <code>getDirection()</code>.
* For coolie hats this will be either 1,0 for any direction or 0.0
* when <code>isCentered()==true</code>.
*/
double getValue();
/**
* Inform about the resolution of the value returned by <code>getValue()</code>.
*
* @return resolution, e.g. 1.0 for coolie hats
*/
double getResolution();
}

View File

@@ -1,38 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 27. Dezember 2001, 00:19
//**********************************************************************************************
package de.hardcode.jxinput;
/**
* An input device offers a set of features (otherwise it would be pretty useless).
* Features in this sense can be axes, buttons and a feature callede <e>directional</e> here.
* Coolie hats are typical directionals because they control a direction (to look at e.g.).
* <p>
* There are no concrete classes directly derived from <code>Feature</code> - it only
* provides a basis for other interfaces.
*
* @see Axis
* @see Button
* @see Directional
*
* @author Herkules
*/
public abstract interface Feature
{
/**
* Features may have a name provided e.g. by the driver.
*/
String getName();
/**
* Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
boolean hasChanged();
}

View File

@@ -1,71 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 19. Dezember 2001, 21:47
//**********************************************************************************************
package de.hardcode.jxinput;
/**
* The <code>JXInputDevise</code> is the main entrypoint to the jxinput package.
* <p>
* A JXInputDevice represents one physical device like a joystick, a gamepad or
* even some emulation (e.g. using keyboard) that implements the interface.
* <p>
* The basis task of a <code>JXInputDevise</code> is to maintain a consistent state of all its features.
* <br>
* It is save to distribute the <code>Feature</code> objects into application without worrying
* about someone else performing an <code>update</code> method and thereby destructing the consistent state.
* <p>
* An additional task is to provide basic device features information like number of axes, buttons
* and directional features.
*
* @see Feature
* @see JXInputManager
*
* @author Herkules
* @version 0.2beta
*/
public interface JXInputDevice
{
/**
* @directed
*/
/*#Features lnkFeatures;*/
/**
*@link aggregationByValue
*/
/*#Feature lnkFeature;*/
/**
* Devices may have a name.
* This name might be provided by a system dependant driver.
*/
String getName();
/** Actual number of available axes. */
int getNumberOfAxes();
/** Actual number of available buttons. */
int getNumberOfButtons();
/** Actual number of available directional features. */
int getNumberOfDirectionals();
/** Maximum number of axes as an upper bound for index values. */
int getMaxNumberOfAxes();
/** Maximum number of buttons as an upper bound for index values. */
int getMaxNumberOfButtons();
/** Maximum number of directional features as an upper bound for index values. */
int getMaxNumberOfDirectionals();
Axis getAxis( int idx );
Button getButton( int idx );
Directional getDirectional( int idx );
}

View File

@@ -1,233 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 29. Dezember 2001, 02:17
//**********************************************************************************************
package de.hardcode.jxinput;
//
// Import driver stuff
//
import de.hardcode.jxinput.directinput.DirectInputDevice;
import de.hardcode.jxinput.event.JXInputEventManager;
import de.hardcode.jxinput.keyboard.JXKeyboardInputDevice;
import de.hardcode.jxinput.virtual.JXVirtualInputDevice;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.Component;
/**
* Manages the available instances of JXInputDevice.
* It holds the one central update method which synchronizes with the physical device.
* @author Herkules
*/
public class JXInputManager
{
/** Remember when the last update took place. */
private static long mTimeOfLastUpdate;
/** Maintain a list of devices. */
private final static ArrayList mDevices = new ArrayList();
/** Maintain a list of direct input devices. */
private final static ArrayList mDIDevices = new ArrayList();
/** Maintain a list of virtual devices. */
private final static ArrayList mVirtualDevices = new ArrayList();
/** Maintain a list of keyboard devices. */
private final static ArrayList mKBDevices = new ArrayList();
/**
* Statically retrieve all DirectInputDevices available.
*/
static
{
reset();
}
/**
* @directed
*/
/*#JXInputDevice lnkJXInputDevice;*/
/**
* Creates a new instance of JXInputManager.
* This is prohibited - it only has static members.
*/
private JXInputManager()
{
}
/**
* Retrieve the number of available input devices.
*/
public static int getNumberOfDevices()
{
return mDevices.size();
}
/**
* Delivers the JXInputDevice with the desired index.
* <p>
* Take care that <code>idx < getNumberOfDevices()</code>!
*/
public static JXInputDevice getJXInputDevice( int idx )
{
//
// Be well-behaved even if idx is out of range.
//
if ( idx >= mDevices.size() )
return null;
return (JXInputDevice)mDevices.get( idx );
}
/**
* Master reset for all devices and events.
* After calling reset(), better forget all devices created or retrieved.
* They are no longer valid.
* Event listeners will no longer be called and should be discarded.
*/
synchronized public static void reset()
{
JXInputEventManager.reset();
mDevices.clear();
mVirtualDevices.clear();
mDIDevices.clear();
DirectInputDevice.reset();
for ( int i = 0; i < DirectInputDevice.getNumberOfDevices(); ++i )
{
DirectInputDevice dev = new DirectInputDevice( i );
mDevices.add( dev );
mDIDevices.add( dev );
}
// I have to call updateFeatures one time here during initialization
// bc. I experienced difficulties otherwise while running with the
// J3D sensoring stuff!
// updateFeatures();
DirectInputDevice.update();
int n = mKBDevices.size();
for ( int i = 0; i < n; ++i )
((JXKeyboardInputDevice)mKBDevices.get( i )).shutdown();
mKBDevices.clear();
}
/**
* Update the (shared) state of all features in one step.
* This method asks the actual device for a consistant state.
* After calling this method, all features may have new values.
* updateFeatures() is meant to be called e.g. once per frame in a gaming environment.
*/
public static void updateFeatures()
{
// Get timing
long now = System.currentTimeMillis();
long deltaT = now - mTimeOfLastUpdate;
// Update available driver
DirectInputDevice.update();
//
// Update the virtual devices.
//
Iterator vdevices = mVirtualDevices.iterator();
while ( vdevices.hasNext() )
{
((JXVirtualInputDevice)vdevices.next()).update( deltaT );
}
// Remember time
mTimeOfLastUpdate = now;
// Fire all events.
JXInputEventManager.trigger();
}
/**
* Get time when last update occurred.
* @return tickervalue in milliseconds
*/
public static long getLastUpdateTime()
{
return mTimeOfLastUpdate;
}
/**
* Create a new pseudo-device.
*/
public static JXKeyboardInputDevice createKeyboardDevice()
{
JXKeyboardInputDevice d = new JXKeyboardInputDevice();
mDevices.add( d );
mKBDevices.add( d );
return d;
}
/**
* Create a new pseudo-device listening to a Swing component.
* Make sure that the component also has the keyboard focus!!
*/
public static JXKeyboardInputDevice createKeyboardDevice( Component comp )
{
JXKeyboardInputDevice d = new JXKeyboardInputDevice( comp );
mDevices.add( d );
mKBDevices.add( d );
return d;
}
/**
* Delete a keyboard device again e.g. when the corresponding
* JComponent gets deleted.
*/
public static void deleteKeyboardDevice( JXKeyboardInputDevice dev )
{
mDevices.remove( dev );
mKBDevices.remove( dev );
((JXKeyboardInputDevice)dev).shutdown();
}
/**
* Create a new pseudo-device.
*/
public static JXVirtualInputDevice createVirtualDevice()
{
JXVirtualInputDevice d = new JXVirtualInputDevice();
mDevices.add( d );
mVirtualDevices.add( d );
return d;
}
/**
* Delete a virtual device again.
*/
public static void deleteVirtualDevice( JXVirtualInputDevice dev )
{
mDevices.remove( dev );
mVirtualDevices.remove( dev );
}
}

View File

@@ -1,70 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 27. Dezember 2001, 00:14
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import de.hardcode.jxinput.Axis;
/**
*
* @author Herkules
*/
class DIAxis implements Axis
{
private final int mDeviceIdx;
private final int mIdx;
/**
* Creates a new instance of DIAxis.
*/
DIAxis( int devidx, int idx )
{
mDeviceIdx = devidx;
mIdx = idx;
}
public String getName()
{
return DirectInputDriver.getAxisName( mDeviceIdx, mIdx );
}
/**
* Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
public double getValue()
{
return DirectInputDriver.getAxisValue( mDeviceIdx, mIdx );
}
public int getType()
{
return DirectInputDriver.getAxisType( mDeviceIdx, mIdx );
}
/**
* Inform about the resolution of the axis.
*
* @return resolution, e.g. 2^-16
*/
public double getResolution()
{
// extend the driver here!!
// Here I assume typical 16 bit resolution
return ( getType() == Axis.SLIDER ? 1.0/65536.0 : 2.0/65536.0 ) ;
}
}

View File

@@ -1,55 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 27. Dezember 2001, 00:14
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import de.hardcode.jxinput.Button;
/**
*
* @author Herkules
*/
class DIButton implements Button
{
private final int mDeviceIdx;
private final int mIdx;
/**
* Creates a new instance of DIButton.
*/
DIButton( int devidx, int idx )
{
mDeviceIdx = devidx;
mIdx = idx;
}
public String getName()
{
return DirectInputDriver.getButtonName( mDeviceIdx, mIdx );
}
/**
* Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
public int getType()
{
return DirectInputDriver.getButtonType( mDeviceIdx, mIdx );
}
public boolean getState()
{
return DirectInputDriver.getButtonState( mDeviceIdx, mIdx );
}
}

View File

@@ -1,78 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 27. Dezember 2001, 23:40
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import de.hardcode.jxinput.Directional;
/**
*
* @author Herkules
*/
class DIDirectional implements Directional
{
private final int mDeviceIdx;
private final int mIdx;
/**
* Creates a new instance of DIDirectional.
*/
DIDirectional( int devidx, int idx )
{
mDeviceIdx = devidx;
mIdx = idx;
}
/** Features may have a name provided e.g. by the driver. */
public String getName()
{
return DirectInputDriver.getDirectionalName( mDeviceIdx, mIdx );
}
/**
* Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
public boolean isCentered()
{
return ( 0xffff == (DirectInputDriver.getDirection( mDeviceIdx, mIdx ) & 0xffff) );
}
public int getDirection()
{
return isCentered() ? 0 : DirectInputDriver.getDirection( mDeviceIdx, mIdx );
}
public double getValue()
{
if ( isCentered() )
return 0.0;
return 1.0;
}
/**
* Inform about the resolution of the value returned by <code>getValue()</code>.
*
* @return resolution, e.g. 1.0 for coolie hats
*/
public double getResolution()
{
// DI POV always return 0.0 or 1.0, so the resolution is 1.0.
return 1.0;
}
}

View File

@@ -1,170 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 26. Dezember 2001, 00:40
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import de.hardcode.jxinput.JXInputDevice;
import de.hardcode.jxinput.Axis;
import de.hardcode.jxinput.Directional;
import de.hardcode.jxinput.Button;
/**
*
* @author Herkules
*/
public class DirectInputDevice implements JXInputDevice
{
int mDeviceIdx;
private DIAxis[] mAxes;
private DIButton[] mButtons;
private DIDirectional[] mDirectionals;
/**
* The number of DirectInput devices available with the driver.
*/
public static int getNumberOfDevices()
{
if ( DirectInputDriver.isAvailable() )
return DirectInputDriver.getNumberOfDevices();
return 0;
}
/**
* Update the state of all devices.
*/
public static void update()
{
if ( DirectInputDriver.isAvailable() )
DirectInputDriver.nativeupdate();
}
/**
* Creates a new instance of DirectInputDevice.
*/
public DirectInputDevice( int devidx )
{
mDeviceIdx = devidx;
init();
}
/**
* Reset the DirectInput connection.
*/
public static void reset()
{
if ( DirectInputDriver.isAvailable() )
DirectInputDriver.reset();
}
/**
* Initialisation of fields.
*/
private final void init()
{
//
// Allocate arrays for max. number of features
//
mAxes = new DIAxis [ getMaxNumberOfAxes() ];
mButtons = new DIButton [ getMaxNumberOfButtons() ];
mDirectionals = new DIDirectional [ getMaxNumberOfDirectionals() ];
//
// Fill arrays due to the state of the driver.
//
for ( int i = 0; i < mAxes.length; ++i )
{
if ( DirectInputDriver.isAxisAvailable( mDeviceIdx, i ) )
mAxes[ i ] = new DIAxis( mDeviceIdx, i );
}
for ( int i = 0; i < mButtons.length; ++i )
{
if ( DirectInputDriver.isButtonAvailable( mDeviceIdx, i ) )
mButtons[ i ] = new DIButton( mDeviceIdx, i );
}
for ( int i = 0; i < mDirectionals.length; ++i )
{
if ( DirectInputDriver.isDirectionalAvailable( mDeviceIdx, i ) )
mDirectionals[ i ] = new DIDirectional( mDeviceIdx, i );
}
}
/** Devices may have a name. */
public String getName()
{
String name = DirectInputDriver.getName( mDeviceIdx );
if ( null == name )
return "Win32 DirectInput Joystick";
return name;
}
/** Actual number of available buttons. */
public int getNumberOfButtons()
{
return DirectInputDriver.getNumberOfButtons( mDeviceIdx );
}
/** Actual number of available axes. */
public int getNumberOfAxes()
{
return DirectInputDriver.getNumberOfAxes( mDeviceIdx );
}
/** Actual number of available directional features. */
public int getNumberOfDirectionals()
{
return DirectInputDriver.getNumberOfDirectionals( mDeviceIdx );
}
/** Maximum number of buttons as an upper bound for index values. */
public int getMaxNumberOfButtons()
{
return DirectInputDriver.getMaxNumberOfButtons();
}
/** Maximum number of axes as an upper bound for index values. */
public int getMaxNumberOfAxes()
{
return DirectInputDriver.getMaxNumberOfAxes();
}
/** Maximum number of available directional features. */
public int getMaxNumberOfDirectionals()
{
return DirectInputDriver.getMaxNumberOfDirectionals();
}
public Axis getAxis(int idx)
{
return mAxes[ idx ];
}
public Button getButton(int idx)
{
return mButtons[ idx ];
}
public Directional getDirectional(int idx)
{
return mDirectionals[ idx ];
}
}

View File

@@ -1,184 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 19. Dezember 2001, 22:44
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import java.lang.reflect.Array;
/**
* DirectInputDriver: the connection to the Win32 joystick.
* There is only one allowed, so the layout of this class is merely static.
*
* History:
*
* Changes since 0.1beta:
* - support of multiple devices addressed by the <code>dev</code> index
*
*
* @author Herkules
* @version 0.2beta
*/
class DirectInputDriver
{
private final static String NATIVE_LIB_NAME = "jxinput";
/** Remember wether nativeinit() succeeded. */
static boolean sIsOperational = false;
//
// Static arrays to hold the values.
//
private static double [][] sAxisValues;
private static boolean [][] sButtonStates;
private static int [][] sDirectionalValues;
/**
* Perform the static initialization.
*/
static
{
try
{
// Load the native lib.
System.loadLibrary( NATIVE_LIB_NAME );
init();
}
catch( SecurityException e )
{
Log.logger.warning("Native library jxinput not loaded due to a SecurityException.");
}
catch( UnsatisfiedLinkError e )
{
Log.logger.info("Native library jxinput not loaded due to an UnsatisfiedLinkError.");
}
}
private final static void init()
{
sIsOperational = false;
//
// Initialize it.
//
if ( nativeinit() )
{
int devs = getNumberOfDevices();
sAxisValues = new double [ devs ][ DirectInputDriver.getMaxNumberOfAxes() ];
sButtonStates = new boolean [ devs ][ DirectInputDriver.getMaxNumberOfButtons() ];
sDirectionalValues = new int [ devs ][ DirectInputDriver.getMaxNumberOfDirectionals() ];
// Bind the native lib to my variables.
bind();
// Remember I am fine.
sIsOperational = true;
}
}
/**
* Static ctor of DirectInputDriver.
* No object will be created due to the static layout.
*/
private DirectInputDriver()
{
}
// Administration
private static native boolean nativeinit();
private static native void nativeexit();
private static native void bind();
static native int getNumberOfDevices();
// Configuration
static native String getName( int dev );
static native int getNumberOfAxes( int dev );
static native int getNumberOfButtons( int dev );
static native int getNumberOfDirectionals( int dev );
static native int getMaxNumberOfAxes();
static native int getMaxNumberOfButtons();
static native int getMaxNumberOfDirectionals();
static native boolean isAxisAvailable( int dev, int idx );
static native String getAxisName( int dev, int idx );
static native int getAxisType( int dev, int idx );
static native boolean isButtonAvailable( int dev, int idx );
static native String getButtonName( int dev, int idx );
static native int getButtonType( int dev, int idx );
static native boolean isDirectionalAvailable( int dev, int idx );
static native String getDirectionalName( int dev, int idx );
// Operation
static native void nativeupdate();
public static boolean isAvailable()
{
return sIsOperational;
}
/**
* Shutdown the device and free all Win32 resources.
* It is not a good idea to access any joystick features after
* <code>shutdown()</code>.
*/
static void shutdown()
{
nativeexit();
sAxisValues = null;
sButtonStates = null;
sDirectionalValues = null;
}
/**
* Reset the device and free all Win32 resources.
*/
static void reset()
{
shutdown();
init();
}
static double getAxisValue( int dev, int idx )
{
return sAxisValues[ dev ][ idx ];
}
static boolean getButtonState( int dev, int idx )
{
return sButtonStates[ dev ][ idx ];
}
static int getDirection( int dev, int idx )
{
return sDirectionalValues[ dev ][ idx ];
}
/**
* @param args the command line arguments
*/
public static void main (String args[])
{
if ( ! sIsOperational )
return;
for( int i = 0; i < 5000; ++i )
nativeupdate();
shutdown();
}
}

View File

@@ -1,34 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 29. Oktober 2002, 22:57
//**********************************************************************************************
package de.hardcode.jxinput.directinput;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Herkules
*/
public class Log
{
public final static Logger logger = Logger.getLogger( Log.class.getPackage().getName() );
// static
// {
// logger.setLevel( Level.ALL );
// }
/**
* Creates a new instance of Log.
*/
private Log()
{
}
}

View File

@@ -1,48 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:33
//**********************************************************************************************
package de.hardcode.jxinput.event;
import de.hardcode.jxinput.JXInputDevice;
import de.hardcode.jxinput.Axis;
/**
* Represents an event coming from an axis.
* @author Joerg Plewe
*/
public class JXInputAxisEvent
{
private final Axis mAxis;
double mDelta;
/**
* Creates a new instance of JXInputEvent.
*/
JXInputAxisEvent( Axis axis )
{
mAxis = axis;
}
/**
* The feature that caused the event.
*/
public final Axis getAxis()
{
return mAxis;
}
/**
* Return the change in value that caused the event.
*/
public double getDelta()
{
return mDelta;
}
}

View File

@@ -1,19 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:54
//**********************************************************************************************
package de.hardcode.jxinput.event;
/**
*
* @author Herkules
*/
public interface JXInputAxisEventListener
{
void changed( JXInputAxisEvent ev );
}

View File

@@ -1,38 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:33
//**********************************************************************************************
package de.hardcode.jxinput.event;
import de.hardcode.jxinput.JXInputDevice;
import de.hardcode.jxinput.Button;
/**
* Represents event coming from a button.
* @author Joerg Plewe
*/
public class JXInputButtonEvent
{
final Button mButton;
/**
* Creates a new instance of JXInputEvent.
*/
JXInputButtonEvent( Button button )
{
mButton = button;
}
/**
* The feature that caused the event.
*/
public final Button getButton()
{
return mButton;
}
}

View File

@@ -1,19 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:54
//**********************************************************************************************
package de.hardcode.jxinput.event;
/**
*
* @author Herkules
*/
public interface JXInputButtonEventListener
{
void changed( JXInputButtonEvent ev );
}

View File

@@ -1,56 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:33
//**********************************************************************************************
package de.hardcode.jxinput.event;
import de.hardcode.jxinput.JXInputDevice;
import de.hardcode.jxinput.Directional;
/**
* Represents an event coming from an axis.
* @author Joerg Plewe
*/
public class JXInputDirectionalEvent
{
private final Directional mDirectional;
double mValueDelta;
int mDirectionDelta;
/**
* Creates a new instance of JXInputEvent.
*/
JXInputDirectionalEvent( Directional directional )
{
mDirectional = directional;
}
/**
* The feature that caused the event.
*/
public final Directional getDirectional()
{
return mDirectional;
}
/**
* Return the change in value that caused the event.
*/
public double getValueDelta()
{
return mValueDelta;
}
/**
* Return the change in direction that caused the event.
*/
public int getDirectionDelta()
{
return mDirectionDelta;
}
}

View File

@@ -1,19 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:54
//**********************************************************************************************
package de.hardcode.jxinput.event;
/**
*
* @author Herkules
*/
public interface JXInputDirectionalEventListener
{
void changed( JXInputDirectionalEvent ev );
}

View File

@@ -1,284 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 31. Januar 2002, 23:42
//**********************************************************************************************
package de.hardcode.jxinput.event;
import de.hardcode.jxinput.JXInputManager;
import de.hardcode.jxinput.JXInputDevice;
import java.util.ArrayList;
import de.hardcode.jxinput.Axis;
import java.util.Iterator;
import de.hardcode.jxinput.Button;
import de.hardcode.jxinput.Directional;
/**
* Handles all events and listeners.
* <code>JXInputEventManager</code> is layed out a static singleton.
* @author Herkules
*/
public class JXInputEventManager
{
private final static ArrayList mAxisEventListeners = new ArrayList();
private final static ArrayList mButtonEventListeners = new ArrayList();
private final static ArrayList mDirectionalEventListeners = new ArrayList();
private static autotrigger mAutoTrigger = null;
/**
* Inner class combining a listener with its scheduling parameters.
*/
private static class axislistener
{
final JXInputAxisEventListener mListener;
final double mTreshold;
final JXInputAxisEvent mEvent;
double mLastValueFired = 0.0;
axislistener( JXInputAxisEventListener l, Axis axis, double treshold )
{
mListener = l;
mTreshold = treshold;
mEvent = new JXInputAxisEvent( axis );
}
final void checkTrigger()
{
double curval = mEvent.getAxis().getValue();
double delta = curval - mLastValueFired;
if ( Math.abs( delta ) >= mTreshold )
{
mLastValueFired = curval;
mEvent.mDelta = delta;
mListener.changed( mEvent );
}
}
}
/**
* Inner class combining a listener with its scheduling parameters.
*/
private static class buttonlistener
{
final JXInputButtonEventListener mListener;
final JXInputButtonEvent mEvent;
boolean mLastValueFired = false;
buttonlistener( JXInputButtonEventListener l, Button button )
{
mListener = l;
mEvent = new JXInputButtonEvent( button );
}
final void checkTrigger()
{
boolean curstate = mEvent.getButton().getState();
if ( curstate != mLastValueFired )
{
mLastValueFired = curstate;
mListener.changed( mEvent );
}
}
}
private static class directionallistener
{
final JXInputDirectionalEventListener mListener;
final double mValueTreshold;
final JXInputDirectionalEvent mEvent;
double mLastValueFired = 0.0;
boolean mLastCenteredFired = true;
int mLastDirectionFired = 0;
directionallistener( JXInputDirectionalEventListener l, Directional directional, double valuetreshold )
{
mListener = l;
mValueTreshold = valuetreshold;
mEvent = new JXInputDirectionalEvent( directional );
}
final void checkTrigger()
{
double curval = mEvent.getDirectional().getValue();
int curdir = mEvent.getDirectional().getDirection();
boolean curctr = mEvent.getDirectional().isCentered();
double delta = curval - mLastValueFired;
int dirdelta = curdir - mLastDirectionFired;
boolean centeredchanged = mLastCenteredFired != curctr;
if ( Math.abs( delta ) >= mValueTreshold
|| Math.abs( dirdelta ) > 0
|| centeredchanged )
{
mLastValueFired = curval;
mLastDirectionFired = curdir;
mLastCenteredFired = curctr;
mEvent.mValueDelta = delta;
mEvent.mDirectionDelta = dirdelta;
mListener.changed( mEvent );
}
}
}
/**
* Creates a new instance of JXInputEventManager.
*/
private JXInputEventManager()
{
}
/**
* Remove all listeners at once.
*/
public static void reset()
{
mAxisEventListeners.clear();
mButtonEventListeners.clear();
mDirectionalEventListeners.clear();
}
/**
* Query devices and fire all occuring events.
* <code>trigger()</code> is thought to be called by <code>JXInputManager#updateFeatures()</code>.
*/
public static void trigger()
{
int n = mAxisEventListeners.size();
for ( int i = 0; i < n; i++ )
{
axislistener l = (axislistener)mAxisEventListeners.get( i );
l.checkTrigger();
}
n = mButtonEventListeners.size();
for ( int i = 0; i < n; i++ )
{
buttonlistener l = (buttonlistener)mButtonEventListeners.get( i );
l.checkTrigger();
}
n = mDirectionalEventListeners.size();
for ( int i = 0; i < n; i++ )
{
directionallistener l = (directionallistener)mDirectionalEventListeners.get( i );
l.checkTrigger();
}
}
private final static class autotrigger extends Thread
{
boolean mFinish = false;
final int mDelay;
autotrigger( int delay )
{
mDelay = delay;
}
public void run()
{
while ( ! mFinish )
{
try
{
Thread.sleep( mDelay );
JXInputManager.updateFeatures();
}
catch ( InterruptedException ex )
{
}
}
}
}
/**
* Set the intervall in ms that is used to check for new values of the features.
* Set it to <= 0 to prohibit automatic triggering. Events will then only be fired
* when somebody invokes <code>JXInputManager#updateFeatures()</code>.
*/
public static void setTriggerIntervall( int ms )
{
//
// Kill current thread, if any
//
if ( null != mAutoTrigger )
{
mAutoTrigger.mFinish = true;
try
{
mAutoTrigger.join();
}
catch ( InterruptedException ex )
{
}
}
mAutoTrigger = null;
if ( ms > 0 )
{
mAutoTrigger = new autotrigger( ms );
mAutoTrigger.start();
}
}
public static void addListener( JXInputAxisEventListener l, Axis axis, double treshold )
{
mAxisEventListeners.add( new JXInputEventManager.axislistener( l, axis, treshold ) );
}
public static void addListener( JXInputAxisEventListener l, Axis axis )
{
mAxisEventListeners.add( new JXInputEventManager.axislistener( l, axis, axis.getResolution() ) );
}
public static void removeListener( JXInputAxisEventListener l )
{
mAxisEventListeners.remove( l );
}
public static void addListener( JXInputButtonEventListener l, Button button )
{
mButtonEventListeners.add( new JXInputEventManager.buttonlistener( l, button ) );
}
public static void removeListener( JXInputButtonEventListener l )
{
mButtonEventListeners.remove( l );
}
public static void addListener( JXInputDirectionalEventListener l, Directional directional, double valuetreshold )
{
mDirectionalEventListeners.add( new JXInputEventManager.directionallistener( l, directional, valuetreshold ) );
}
public static void addListener( JXInputDirectionalEventListener l, Directional directional )
{
mDirectionalEventListeners.add( new JXInputEventManager.directionallistener( l, directional, directional.getResolution() ) );
}
public static void removeListener( JXInputDirectionalEventListener l )
{
mDirectionalEventListeners.remove( l );
}
}

View File

@@ -1,95 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 23. Februar 2002, 14:05
//**********************************************************************************************
package de.hardcode.jxinput.j3d;
import de.hardcode.jxinput.Axis;
/**
* Connects JXInput with J3DInputDevice.
*
* @author Herkules
*/
public class DeviceConfiguration
{
public final static int AXIS_X = 0;
public final static int AXIS_Y = 1;
public final static int AXIS_Z = 2;
private final static class axisvalue
{
private final Axis mAxis;
private final IsActiveCondition mIsActive;
private final IsActiveCondition mIsIncremental;
private final double mScale;
private final double mOffset;
private double mValue;
axisvalue( Axis axis, IsActiveCondition active, IsActiveCondition incremental, double offset, double scale )
{
mAxis = axis;
mIsActive = active;
mIsIncremental = incremental;
mValue = mOffset = offset;
mScale = scale;
}
double value()
{
if ( mIsActive.isActive() )
{
double newval = mAxis.getValue() * mScale;
if ( mIsIncremental.isActive() )
mValue += newval;
else
mValue = newval + mOffset;
}
return mValue;
}
}
DeviceConfiguration.axisvalue [] mAxisTrans = new DeviceConfiguration.axisvalue[ 3 ];
DeviceConfiguration.axisvalue [] mAxisRot = new DeviceConfiguration.axisvalue[ 3 ];
/**
* Creates a new instance of DeviceConfiguration.
*/
public DeviceConfiguration()
{
}
double getTranslational( int axisid )
{
DeviceConfiguration.axisvalue val = mAxisTrans[ axisid ];
return null == val ? 0.0 : val.value();
}
double getRotational( int axisid )
{
DeviceConfiguration.axisvalue val = mAxisRot[ axisid ];
return null == val ? 0.0 : val.value();
}
public void setTranslational( int axisid, Axis axis, IsActiveCondition active, IsActiveCondition incremental, double offset, double scale )
{
if ( axisid < 0 || axisid > AXIS_Z )
throw new IllegalArgumentException();
mAxisTrans[ axisid ] = new DeviceConfiguration.axisvalue( axis, active, incremental, offset, scale );
}
public void setRotational( int axisid, Axis axis, IsActiveCondition active, IsActiveCondition incremental, double offset, double scale )
{
if ( axisid < 0 || axisid > AXIS_Z )
throw new IllegalArgumentException();
mAxisRot[ axisid ] = new DeviceConfiguration.axisvalue( axis, active, incremental, offset, scale );
}
}

View File

@@ -1,25 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 25. Februar 2002, 22:41
//**********************************************************************************************
package de.hardcode.jxinput.j3d;
/**
*
* @author Herkules
*/
public interface IsActiveCondition
{
public final static IsActiveCondition ALWAYS = IsAlwaysActiveCondition.ALWAYS;
public final static IsActiveCondition NEVER = IsAlwaysActiveCondition.NEVER;
/**
* Tell wether a certain thing is active.
*/
boolean isActive();
}

View File

@@ -1,39 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 25. Februar 2002, 22:43
//**********************************************************************************************
package de.hardcode.jxinput.j3d;
import de.hardcode.jxinput.Button;
/**
*
* @author Herkules
*/
public class IsActiveOnButtonCondition implements IsActiveCondition
{
private final boolean mActiveState;
private final Button mButton;
/**
* Creates a new instance of IsAlwayActiveCondition.
*/
public IsActiveOnButtonCondition( Button button, boolean activestate )
{
mActiveState = activestate;
mButton = button;
}
/**
* Tell wether a certain thing is active.
*/
public boolean isActive()
{
return mButton.getState() == mActiveState;
}
}

View File

@@ -1,38 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 25. Februar 2002, 22:43
//**********************************************************************************************
package de.hardcode.jxinput.j3d;
/**
*
* @author Herkules
*/
final class IsAlwaysActiveCondition implements IsActiveCondition
{
private final boolean mIsActive;
public final static IsActiveCondition ALWAYS = new IsAlwaysActiveCondition( true );
public final static IsActiveCondition NEVER = new IsAlwaysActiveCondition( false );
/**
* Creates a new instance of IsAlwayActiveCondition.
*/
private IsAlwaysActiveCondition(boolean isactive)
{
mIsActive = isactive;
}
/**
* Tell wether a certain thing is active.
*/
public boolean isActive()
{
return mIsActive;
}
}

View File

@@ -1,171 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 22. Februar 2002, 13:21
//**********************************************************************************************
package de.hardcode.jxinput.j3d;
import javax.media.j3d.InputDevice;
import javax.media.j3d.Sensor;
import javax.media.j3d.SensorRead;
import javax.vecmath.Vector3d;
import javax.media.j3d.Transform3D;
import de.hardcode.jxinput.JXInputManager;
/**
* Implementation of Java3D's InputDevice
*
* @author Herkules
*/
public class J3DInputDevice
implements InputDevice
{
private Vector3d mPosition = new Vector3d();
private Transform3D mNewTransform = new Transform3D();
private Transform3D mRotTransX = new Transform3D();
private Transform3D mRotTransY = new Transform3D();
private Transform3D mRotTransZ = new Transform3D();
private Vector3d mInitPos = new Vector3d( 0.0, 0.0, 0.0 );
private Sensor mSensor = new Sensor( this );
private SensorRead mSensorRead = new SensorRead();
private DeviceConfiguration mConfig;
/**
* Creates a new instance of J3DInputDevice.
*/
public J3DInputDevice( DeviceConfiguration config )
{
mConfig = config;
setNominalPositionAndOrientation();
}
public void close()
{
// Intentionally empty
}
/**
* Retrieve processing mode.
* For this device, it always is NON_BLOCKING.
*/
public int getProcessingMode()
{
return InputDevice.NON_BLOCKING;
}
/**
* Don't care for the index, I only support one sensor.
* And I deliver that.
*/
public Sensor getSensor( int param )
{
return mSensor;
}
/**
* Tell the world about the only one sensor I support.
*/
public int getSensorCount()
{
return 1;
}
/**
* Well - initialize!
* Nothing to do here.
*/
public boolean initialize()
{
return true;
}
/**
* The main update method.
*/
public void pollAndProcessInput()
{
JXInputManager.updateFeatures();
mSensorRead.setTime( JXInputManager.getLastUpdateTime() );
mRotTransX.rotX( mConfig.getRotational( DeviceConfiguration.AXIS_X ) );
mRotTransY.rotY( mConfig.getRotational( DeviceConfiguration.AXIS_Y ) );
mRotTransZ.rotZ( mConfig.getRotational( DeviceConfiguration.AXIS_Z ) );
mPosition.set(
mConfig.getTranslational( DeviceConfiguration.AXIS_X ),
mConfig.getTranslational( DeviceConfiguration.AXIS_Y ),
mConfig.getTranslational( DeviceConfiguration.AXIS_Z )
);
mNewTransform.set( mPosition );
mNewTransform.mul( mRotTransX );
mNewTransform.mul( mRotTransY );
mNewTransform.mul( mRotTransZ );
mSensorRead.set( mNewTransform );
mSensor.setNextSensorRead( mSensorRead );
}
/**
* Not called by current j3d implementation.
*/
public void processStreamInput()
{
// Intentionally empty
}
/**
* Reset state.
*/
public void setNominalPositionAndOrientation()
{
mSensorRead.setTime( JXInputManager.getLastUpdateTime() );
mRotTransX.rotX( 0.0 );
mRotTransY.rotY( 0.0 );
mRotTransZ.rotZ( 0.0 );
mPosition.set( mInitPos );
mNewTransform.set( mPosition );
mNewTransform.mul( mRotTransX );
mNewTransform.mul( mRotTransY );
mNewTransform.mul( mRotTransZ );
mSensorRead.set( mNewTransform );
mSensor.setNextSensorRead( mSensorRead );
}
/**
* Set the processing mode.
* Only NON_BLOCKING is allowed!
*/
public void setProcessingMode(int param)
{
if ( param != InputDevice.NON_BLOCKING )
throw new IllegalArgumentException("Processing mode must be NON_BLOCKING");
}
}

View File

@@ -1,11 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
Connecting JXInput to Java3D by implementing the interface
javax.media.j3d.InputDevice.
</BODY>
</HTML>

View File

@@ -1,205 +0,0 @@
/*
* @(#)HelloUniverse.java 1.15 02/02/07 14:48:36
*
* Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
* OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
* LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed,licensed or intended
* for use in the design, construction, operation or maintenance of
* any nuclear facility.
*/
package de.hardcode.jxinput.j3d.test;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.ColorCube;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import de.hardcode.jxinput.j3d.DeviceConfiguration;
import de.hardcode.jxinput.Axis;
import de.hardcode.jxinput.JXInputManager;
import de.hardcode.jxinput.j3d.IsActiveCondition;
import de.hardcode.jxinput.j3d.J3DInputDevice;
import de.hardcode.jxinput.j3d.IsActiveOnButtonCondition;
public class HelloUniverse extends Applet
{
private SimpleUniverse u = null;
TransformGroup objTrans;
public BranchGroup createSceneGraph()
{
BranchGroup objRoot = new BranchGroup();
objTrans = new TransformGroup();
objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
objRoot.addChild(objTrans);
objTrans.addChild(new ColorCube(0.4));
// Transform3D yAxis = new Transform3D();
// Alpha rotationAlpha = new Alpha(-1, Alpha.INCREASING_ENABLE,
// 0, 0,
// 4000, 0, 0,
// 0, 0, 0);
// RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, objTrans, yAxis,
// 0.0f, (float) Math.PI*2.0f);
// BoundingSphere bounds = new BoundingSphere(new Point3d(0.0,0.0,0.0), 100.0);
// rotator.setSchedulingBounds(bounds);
// objTrans.addChild(rotator);
return objRoot;
}
public HelloUniverse()
{
}
public void init()
{
// These are the string arguments given to the VirtualInputDevice
// constructor. These are settable parameters. Look in the
// VirtualInputDevice constructor for a complete list.
String[] args = new String[10];
args[0] = "printvalues";
args[1] = "true";
args[2] = "yscreeninitloc";
args[3] = "50";
args[4] = null;
// now create the HelloUniverse Canvas
setLayout(new BorderLayout());
GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
Canvas3D c = new Canvas3D(config);
add("Center", c);
// Create a simple scene and attach it to the virtual universe
BranchGroup scene = createSceneGraph();
u = new SimpleUniverse(c);
//
// Use the inputdevice
//
InputDevice device = createInputDevice();
// Register the VirtualInputDevice with Java 3D
u.getViewer().getPhysicalEnvironment().addInputDevice( device );
// TransformGroup viewTrans = u.getViewingPlatform().getViewPlatformTransform();
// Put the behavoir to teh object
SensorBehavior s = new SensorBehavior( objTrans, device.getSensor(0) );
s.setSchedulingBounds( new BoundingSphere( new Point3d(0.0,0.0,0.0), Float.MAX_VALUE ) );
objTrans.addChild( s );
u.getViewingPlatform().setNominalViewingTransform();
u.addBranchGraph(scene);
}
public void destroy()
{
u.removeAllLocales();
}
/**
* Setup an input device.
*/
private InputDevice createInputDevice()
{
IsActiveCondition button1down = new IsActiveOnButtonCondition(JXInputManager.getJXInputDevice( 0 ).getButton( 0 ), true );
IsActiveCondition button1up = new IsActiveOnButtonCondition(JXInputManager.getJXInputDevice( 0 ).getButton( 0 ), false );
Axis xaxis = JXInputManager.getJXInputDevice( 0 ).getAxis( Axis.ID_X );
Axis yaxis = JXInputManager.getJXInputDevice( 0 ).getAxis( Axis.ID_Y );
DeviceConfiguration cnf = new DeviceConfiguration();
//
// Setup the configuration to use joysticks x/y for rotation is not button is pressed
// and for translation if button1 is pressed.
//
cnf.setRotational(
DeviceConfiguration.AXIS_Y,
xaxis,
button1up,
IsActiveCondition.NEVER,
0.0, Math.PI
);
cnf.setRotational(
DeviceConfiguration.AXIS_X,
yaxis,
button1up,
IsActiveCondition.NEVER,
0.0, Math.PI
);
cnf.setTranslational(
DeviceConfiguration.AXIS_Z,
yaxis,
button1down,
IsActiveCondition.NEVER,
-5.0, 4.0
);
cnf.setTranslational(
DeviceConfiguration.AXIS_X,
xaxis,
button1down,
IsActiveCondition.NEVER,
0.0, 4.0
);
// We have the config, create the device...
J3DInputDevice d = new J3DInputDevice( cnf );
// The InputDevice must be initialized before registering it
// with the PhysicalEnvironment object.
d.initialize();
return d;
}
public static void main(String[] args)
{
new MainFrame(new HelloUniverse(), 350, 350);
}
}

View File

@@ -1,70 +0,0 @@
package de.hardcode.jxinput.j3d.test;
/*
* @(#)SensorBehavior.java 1.8 02/02/07 14:48:34
*
* Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
* OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
* LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed,licensed or intended
* for use in the design, construction, operation or maintenance of
* any nuclear facility.
*/
import javax.media.j3d.*;
import java.util.*;
public class SensorBehavior extends Behavior
{
private WakeupOnElapsedFrames conditions = new WakeupOnElapsedFrames(0);
private TransformGroup transformGroup;
private Sensor sensor;
private Transform3D transform = new Transform3D();
public SensorBehavior( TransformGroup tg, Sensor sensor )
{
transformGroup = tg;
this.sensor = sensor;
}
public void initialize()
{
wakeupOn( conditions );
}
public void processStimulus( Enumeration criteria )
{
sensor.getRead( transform );
transformGroup.setTransform( transform );
wakeupOn( conditions );
}
}

View File

@@ -1,35 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 16. April 2002, 23:31
//**********************************************************************************************
package de.hardcode.jxinput.keyboard;
/**
* Exeception to be thrown if keycode is not in then range [0,255].
*
* @author Herkules
*/
public class InvalidKeyCodeException
extends IllegalArgumentException
{
/**
* Creates a new instance of InvalidKeyCodeException.
*/
public InvalidKeyCodeException()
{
}
/**
* Creates a new instance of InvalidKeyCodeException.
*/
public InvalidKeyCodeException( String s )
{
super( s );
}
}

View File

@@ -1,175 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 9. April 2002, 22:40
//**********************************************************************************************
package de.hardcode.jxinput.keyboard;
import de.hardcode.jxinput.*;
import java.awt.Component;
/**
* Virtual input device treating a AWT keyboard as a source for Buttons.
*
* @author Herkules
*/
public class JXKeyboardInputDevice
implements JXInputDevice
{
private static final String DEVICENAME = "Swing Keyboard";
/** The driver doing all the real work. */
private final KeyboardDriver mDriver = new KeyboardDriver();
/** The Component I am listening to. */
private Component mComponent = null;
/** Hold the biggest keycode for which a button has been created. */
private int mMaxIdxCreated = 0;
/**
* Creates a new instance of JXKeyboardInputDevice.
*/
public JXKeyboardInputDevice()
{
}
/**
* Creates a new instance of JXKeyboardInputDevice
* immediately listening to a JComponent.
*/
public JXKeyboardInputDevice( Component comp )
{
listenTo( comp );
}
/**
* Makes this device listen to a certain JComponent.
*/
public final void listenTo( Component comp )
{
shutdown();
mComponent = comp;
mComponent.addKeyListener( mDriver );
}
/**
* Shut down. No longer listen to my JComponent.
*/
public final void shutdown()
{
if ( null != mComponent )
mComponent.removeKeyListener( mDriver );
}
/**
* Create a button object for a certain keycode.
*/
public Button createButton( int keycode )
{
if ( 0 > keycode || 0x100 < keycode )
throw new InvalidKeyCodeException();
KeyButton b;
if ( null == (b = mDriver.getButton( keycode ) ) )
{
b = new KeyButton( keycode );
mDriver.registerKeyButton( b );
if ( keycode > mMaxIdxCreated )
mMaxIdxCreated = keycode;
}
return b;
}
public void removeButton( Button b )
{
mDriver.unregisterKeyButton( (KeyButton) b );
}
//*********************************************************************************************
//
// Implement JXInputDevice
//
//*********************************************************************************************
public Axis getAxis(int idx)
{
// No axes on keyboard.
return null;
}
public Button getButton(int idx)
{
// idx is interpreted as the keycode
return mDriver.getButton( idx );
}
public Directional getDirectional(int idx)
{
// No directionals on keyboard.
return null;
}
/** Maximum number of axes as an upper bound for index values. */
public int getMaxNumberOfAxes()
{
// No axes on keyboard.
return 0;
}
/** Maximum number of buttons as an upper bound for index values. */
public int getMaxNumberOfButtons()
{
// Return biggest keycode (inclusive).
return mMaxIdxCreated + 1;
}
/** Maximum number of directional features as an upper bound for index values. */
public int getMaxNumberOfDirectionals()
{
// No directionals on keyboard.
return 0;
}
/**
* Devices may have a name.
* This name might be provided by a system dependant driver.
*/
public String getName()
{
return DEVICENAME;
}
/** Actual number of available axes. */
public int getNumberOfAxes()
{
// No axes on keyboard.
return 0;
}
/** Actual number of available buttons. */
public int getNumberOfButtons()
{
return mDriver.getNumberOfButtons();
}
/** Actual number of available directional features. */
public int getNumberOfDirectionals()
{
// No directionals on keyboard.
return 0;
}
}

View File

@@ -1,94 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 9. April 2002, 22:51
//**********************************************************************************************
package de.hardcode.jxinput.keyboard;
import de.hardcode.jxinput.Button;
import java.awt.event.KeyEvent;
/**
* Associates a keycode with a Button and handles the current state of that button.
*
* @author Herkules
*/
class KeyButton
implements Button
{
private final int mKeyCode;
private boolean mIsPressed;
private boolean mHasChanged;
/**
* Creates a new instance of KeyButton.
*/
public KeyButton( int keycode )
{
mKeyCode = keycode;
}
/**
* Return the keycode assigned with this button.
*/
public final int getKeyCode()
{
return mKeyCode;
}
final void setIsPressed( boolean flag )
{
mIsPressed = flag;
}
//*********************************************************************************************
//
// Implement Button
//
//*********************************************************************************************
/**
* Features may have a name provided e.g. by the driver.
*/
public String getName()
{
return KeyEvent.getKeyText( mKeyCode );
}
/**
* Tells the state of the button at last update.
*/
public boolean getState()
{
return mIsPressed;
}
/**
* Retrieve the type of the button.
* Pushbutton will deliver <code>true==getState()</code> as long as they are pressed down.
* Togglebuttons will change their state once they are pressed and keep that state
* until they are pressed again.
* @return [ PUSHBUTTON | TOGGLEBUTTON ]
*/
public int getType()
{
return Button.PUSHBUTTON;
}
/**
* Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
}

View File

@@ -1,141 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 9. April 2002, 22:43
//**********************************************************************************************
package de.hardcode.jxinput.keyboard;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.security.InvalidParameterException;
/**
* Listen to a JComponent handle handle all associated button objects.
* This is the main worker class for JXKeyboardInputDevice.
*
* @author Herkules
*/
class KeyboardDriver implements KeyListener
{
// HashMap mKeysToObserveMap = new HashMap();
int mNumberOfKeysObserved = 0;
KeyButton [] mKeysObserved = new KeyButton [ 0x100 ];
/**
* Creates a new instance of KeyboardDriver.
*/
public KeyboardDriver()
{
}
/**
* How many buttons are registered?
*/
final int getNumberOfButtons()
{
return mNumberOfKeysObserved;
// return mKeysToObserveMap.size();
}
/**
* Place a new button under my observation.
*/
final boolean registerKeyButton( KeyButton b )
{
final int keycode = b.getKeyCode();
if ( 0 > keycode || 0x100 < keycode )
throw new InvalidKeyCodeException();
if ( null == mKeysObserved[ keycode ] )
{
mKeysObserved[ keycode ] = b;
mNumberOfKeysObserved++;
return true;
}
else
{
return false;
}
// Integer code = new Integer( b.getKeyCode() );
// if ( ! mKeysToObserveMap.containsKey( code ) )
// {
// mKeysToObserveMap.put( code, b );
// return true;
// }
// else
// {
// return false;
// }
}
final void unregisterKeyButton( KeyButton b )
{
final int keycode = b.getKeyCode();
if ( 0 > keycode || 0x100 < keycode )
throw new InvalidKeyCodeException();
if ( null != mKeysObserved[ b.getKeyCode() ] )
{
mKeysObserved[ keycode ] = null;
mNumberOfKeysObserved--;
}
// Integer code = new Integer( b.getKeyCode() );
// mKeysToObserveMap.remove( code );
}
/**
* Retrieve the button from its keycode.
*/
final KeyButton getButton( int keycode )
{
if ( 0 > keycode || 0x100 < keycode )
throw new InvalidKeyCodeException();
return mKeysObserved[ keycode ];
// Integer code = new Integer( keycode );
// return (KeyButton)mKeysToObserveMap.get( code );
}
//*********************************************************************************************
//
// Implement KeyListener
//
//*********************************************************************************************
public void keyPressed( KeyEvent keyEvent )
{
KeyButton b = getButton( keyEvent.getKeyCode() );
if ( null != b )
b.setIsPressed( true );
}
public void keyReleased( KeyEvent keyEvent )
{
KeyButton b = getButton( keyEvent.getKeyCode() );
if ( null != b )
b.setIsPressed( false );
}
public void keyTyped( KeyEvent keyEvent )
{
// Intentionally empty.
}
}

View File

@@ -1,10 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>de.hardcode.jxinput.keyboard</TITLE>
</HEAD>
<BODY>
Connects Swing keyboard handling to the JXInput infrastructure.
</BODY>
</HTML>

View File

@@ -1,39 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 20. Februar 2002, 22:19
//**********************************************************************************************
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.event.JXInputEventManager;
import de.hardcode.jxinput.event.JXInputAxisEventListener;
import de.hardcode.jxinput.event.JXInputAxisEvent;
import de.hardcode.jxinput.Axis;
/**
* Example listener to an axis.
*
* @author Herkules
*/
public class AxisListener
implements JXInputAxisEventListener
{
/**
* Creates a new instance of AxisListener.
*/
public AxisListener( Axis axis )
{
JXInputEventManager.addListener( this, axis, 0.1 );
}
public void changed( JXInputAxisEvent ev )
{
System.out.println( "Axis " + ev.getAxis().getName() + " changed : value=" + ev.getAxis().getValue() + ", event causing delta=" + ev.getDelta() );
}
}

View File

@@ -1,38 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 20. Februar 2002, 22:19
//**********************************************************************************************
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.event.JXInputEventManager;
import de.hardcode.jxinput.event.JXInputButtonEventListener;
import de.hardcode.jxinput.event.JXInputButtonEvent;
import de.hardcode.jxinput.Button;
/**
* Sample button listener.
*
* @author Herkules
*/
public class ButtonListener implements JXInputButtonEventListener
{
/**
* Creates a new instance of AxisListener.
*/
public ButtonListener( Button button )
{
JXInputEventManager.addListener( this, button );
}
public void changed( JXInputButtonEvent ev )
{
System.out.println( "Button " + ev.getButton().getName() + " changed : state=" + ev.getButton().getState() );
}
}

View File

@@ -1,37 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 20. Februar 2002, 22:19
//**********************************************************************************************
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.event.JXInputEventManager;
import de.hardcode.jxinput.event.JXInputDirectionalEventListener;
import de.hardcode.jxinput.event.JXInputDirectionalEvent;
import de.hardcode.jxinput.Directional;
/**
* Sample directional listener.
*
* @author Herkules
*/
public class DirectionalListener implements JXInputDirectionalEventListener
{
/**
* Creates a new instance of AxisListener.
*/
public DirectionalListener( Directional directional )
{
JXInputEventManager.addListener( this, directional, 1.0 );
}
public void changed( JXInputDirectionalEvent ev )
{
System.out.println( "Directional " + ev.getDirectional().getName() + " changed : direction=" + ev.getDirectional().getDirection() + ", value=" + ev.getDirectional().getValue() + ", event causing delta=" + ev.getDirectionDelta() );
}
}

View File

@@ -1,97 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.0" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
<Events>
<EventHandler event="componentShown" listener="java.awt.event.ComponentListener" parameters="java.awt.event.ComponentEvent" handler="OnShow"/>
</Events>
<AuxValues>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout">
<Property name="horizontalGap" type="int" value="2"/>
<Property name="verticalGap" type="int" value="2"/>
</Layout>
<SubComponents>
<Container class="javax.swing.JPanel" name="mAxesPanelContainer">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.BevelBorderInfo">
<BevelBorder/>
</Border>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="mAxesPanel">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="North"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridLayout">
<Property name="columns" type="int" value="1"/>
<Property name="rows" type="int" value="1"/>
<Property name="verticalGap" type="int" value="20"/>
</Layout>
</Container>
</SubComponents>
</Container>
<Container class="javax.swing.JPanel" name="mDirectionalPanel">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.BevelBorderInfo">
<BevelBorder/>
</Border>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="South"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridLayout">
<Property name="columns" type="int" value="1"/>
<Property name="rows" type="int" value="1"/>
</Layout>
</Container>
<Container class="javax.swing.JScrollPane" name="mButtonScrollPane">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="East"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="mButtonsPanel">
<Properties>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.BevelBorderInfo">
<BevelBorder/>
</Border>
</Property>
</Properties>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridLayout">
<Property name="columns" type="int" value="1"/>
<Property name="rows" type="int" value="1"/>
</Layout>
</Container>
</SubComponents>
</Container>
</SubComponents>
</Form>

View File

@@ -1,296 +0,0 @@
/*
* JXInputDevicePanel.java
*
* Created on 23. Januar 2002, 22:19
*/
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.JXInputManager;
import de.hardcode.jxinput.JXInputDevice;
import de.hardcode.jxinput.Axis;
import de.hardcode.jxinput.Directional;
import de.hardcode.jxinput.Button;
import javax.swing.*;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Dictionary;
import java.util.Enumeration;
/**
*
* @author Herkules
*/
public class JXInputDevicePanel extends javax.swing.JPanel
{
private static final Font AXIS_SLIDER_FONT = new Font( "Verdana", Font.PLAIN, 9 );
private final JXInputDevice mDev;
private final ArrayList mAxisSliders = new ArrayList();
private final ArrayList mButtonCheckboxes = new ArrayList();
private final ArrayList mDirectionalLabels = new ArrayList();
/** Creates new form JXInputDevicePanel */
public JXInputDevicePanel( JXInputDevice dev )
{
mDev = dev;
initComponents();
initFromDevice();
}
/**
* Helper class connecting a JSlider with an Axis.
*/
private class AxisSlider extends JSlider
{
Axis mAxis;
AxisSlider( Axis axis )
{
super( ( Axis.SLIDER == axis.getType() ? 0 : -100 ), 100 );
this.setMajorTickSpacing( Axis.SLIDER == axis.getType() ? 25 : 50 );
this.setMinorTickSpacing( 5 );
this.setPaintTicks( true );
this.setPaintLabels( true );
this.setEnabled( false );
Dictionary labeldict = this.getLabelTable();
Enumeration labels = labeldict.elements();
while ( labels.hasMoreElements() )
{
JLabel label = (JLabel)labels.nextElement();
label.setFont( AXIS_SLIDER_FONT );
label.setSize( 32, 12 );
label.setHorizontalAlignment( SwingConstants.LEFT );
}
mAxis = axis;
}
void update()
{
int ax = (int)(mAxis.getValue() * 100.0);
//
// Only if value really changes
//
if ( ax != this.getValue() )
{
this.setValue( ax );
this.setToolTipText( mAxis.getName() + ": " + Double.toString( mAxis.getValue() ) );
}
}
}
private class ButtonCheckbox extends JCheckBox
{
Button mButton;
ButtonCheckbox( Button button )
{
super( button.getName() );
this.setEnabled( false );
mButton = button;
}
void update()
{
boolean state = mButton.getState();
//
// Only if value really changes
//
if ( state != this.isSelected() )
{
this.setSelected( state );
}
}
}
private class DirectionalLabel extends JLabel
{
Directional mDirectional;
int mCurrent = 0;
DirectionalLabel( Directional directional )
{
super( directional.getName() );
mDirectional = directional;
}
void update()
{
int dir = mDirectional.getDirection();
//
// Only if value really changes
//
if ( dir != mCurrent )
{
this.setText( mDirectional.getName() + ": " + ( mDirectional.isCentered() ? "-" : Integer.toString( dir ) ) );
mCurrent = dir;
}
}
}
/**
* Setup the dialogs content from the JXInputDevice.
*/
void initFromDevice()
{
if ( null != mDev )
{
((GridLayout)mAxesPanel.getLayout()).setRows( mDev.getNumberOfAxes() );
for ( int i = 0; i < mDev.getMaxNumberOfAxes(); ++i )
{
if ( null != mDev.getAxis( i ) )
{
AxisSlider slider = new AxisSlider( mDev.getAxis( i ) );
JLabel name = new JLabel( mDev.getAxis( i ).getName() );
name.setVerticalAlignment( SwingConstants.TOP );
name.setHorizontalAlignment( SwingConstants.CENTER );
name.setPreferredSize( new java.awt.Dimension( 90, 0 ) );
JPanel p = new JPanel();
p.setLayout( new BorderLayout() );
p.add( name, BorderLayout.WEST );
p.add( slider, BorderLayout.CENTER );
mAxesPanel.add( p );
// Add to list of all AxisSlider controls
mAxisSliders.add( slider );
// Add an event listener:
new AxisListener( mDev.getAxis( i ) );
}
}
((GridLayout)mButtonsPanel.getLayout()).setRows( mDev.getNumberOfButtons() );
for ( int i = 0; i < mDev.getMaxNumberOfButtons(); ++i )
{
if ( null != mDev.getButton( i ) )
{
ButtonCheckbox chk = new ButtonCheckbox( mDev.getButton( i ) );
mButtonCheckboxes.add( chk );
mButtonsPanel.add( chk );
// Add an event listener:
new ButtonListener( mDev.getButton( i ) );
}
}
((GridLayout)mDirectionalPanel.getLayout()).setRows( mDev.getNumberOfDirectionals() / 2 );
for ( int i = 0; i < mDev.getMaxNumberOfDirectionals(); ++i )
{
if ( null != mDev.getDirectional( i ) )
{
DirectionalLabel lbl = new DirectionalLabel( mDev.getDirectional( i ) );
mDirectionalLabels.add( lbl );
mDirectionalPanel.add( lbl );
// Add an event listener:
new DirectionalListener( mDev.getDirectional( i ) );
}
}
}
}
public void update()
{
Iterator it = mAxisSliders.iterator();
while ( it.hasNext() )
{
((AxisSlider)it.next()).update();
}
it = mButtonCheckboxes.iterator();
while ( it.hasNext() )
{
((ButtonCheckbox)it.next()).update();
}
it = mDirectionalLabels.iterator();
while ( it.hasNext() )
{
((DirectionalLabel)it.next()).update();
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents()
{
mAxesPanelContainer = new javax.swing.JPanel();
mAxesPanel = new javax.swing.JPanel();
mDirectionalPanel = new javax.swing.JPanel();
mButtonScrollPane = new javax.swing.JScrollPane();
mButtonsPanel = new javax.swing.JPanel();
setLayout(new java.awt.BorderLayout(2, 2));
addComponentListener(new java.awt.event.ComponentAdapter()
{
public void componentShown(java.awt.event.ComponentEvent evt)
{
OnShow(evt);
}
});
mAxesPanelContainer.setLayout(new java.awt.BorderLayout());
mAxesPanelContainer.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
mAxesPanel.setLayout(new java.awt.GridLayout(1, 1, 0, 20));
mAxesPanelContainer.add(mAxesPanel, java.awt.BorderLayout.NORTH);
add(mAxesPanelContainer, java.awt.BorderLayout.CENTER);
mDirectionalPanel.setLayout(new java.awt.GridLayout(1, 1));
mDirectionalPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
add(mDirectionalPanel, java.awt.BorderLayout.SOUTH);
mButtonsPanel.setLayout(new java.awt.GridLayout(1, 1));
mButtonsPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
mButtonScrollPane.setViewportView(mButtonsPanel);
add(mButtonScrollPane, java.awt.BorderLayout.EAST);
}// </editor-fold>//GEN-END:initComponents
private void OnShow(java.awt.event.ComponentEvent evt)//GEN-FIRST:event_OnShow
{//GEN-HEADEREND:event_OnShow
// Commented: the focus is held by a parent component
// System.out.println("OnShow");
// this.requestFocus();
}//GEN-LAST:event_OnShow
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel mAxesPanel;
private javax.swing.JPanel mAxesPanelContainer;
private javax.swing.JScrollPane mButtonScrollPane;
private javax.swing.JPanel mButtonsPanel;
private javax.swing.JPanel mDirectionalPanel;
// End of variables declaration//GEN-END:variables
}

View File

@@ -1,79 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Form version="1.0" type="org.netbeans.modules.form.forminfo.JDialogFormInfo">
<Properties>
<Property name="title" type="java.lang.String" value="JXInput (C) 2001-2006 HARDCODE Dev."/>
</Properties>
<SyntheticProperties>
<SyntheticProperty name="formSizePolicy" type="int" value="1"/>
</SyntheticProperties>
<Events>
<EventHandler event="windowClosing" listener="java.awt.event.WindowListener" parameters="java.awt.event.WindowEvent" handler="closeDialog"/>
</Events>
<AuxValues>
<AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
<AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
<AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
<AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,44,0,0,1,-112"/>
</AuxValues>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout"/>
<SubComponents>
<Container class="javax.swing.JPanel" name="mMainPanel">
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout">
<Property name="horizontalGap" type="int" value="10"/>
</Layout>
<SubComponents>
<Component class="javax.swing.JLabel" name="mLabelNoDevice">
<Properties>
<Property name="horizontalAlignment" type="int" value="0"/>
<Property name="text" type="java.lang.String" value="No JXInputDevice available!"/>
<Property name="border" type="javax.swing.border.Border" editor="org.netbeans.modules.form.editors2.BorderEditor">
<Border info="org.netbeans.modules.form.compat2.border.SoftBevelBorderInfo">
<BevelBorder/>
</Border>
</Property>
</Properties>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="North"/>
</Constraint>
</Constraints>
</Component>
<Container class="javax.swing.JTabbedPane" name="mDevicesTabbedPane">
<Events>
<EventHandler event="focusGained" listener="java.awt.event.FocusListener" parameters="java.awt.event.FocusEvent" handler="mDevicesTabbedPaneFocusGained"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="Center"/>
</Constraint>
</Constraints>
<Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
</Container>
<Component class="javax.swing.JButton" name="mButtonReset">
<Properties>
<Property name="text" type="java.lang.String" value="Reset "/>
</Properties>
<Events>
<EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="mButtonResetActionPerformed"/>
</Events>
<Constraints>
<Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout" value="org.netbeans.modules.form.compat2.layouts.DesignBorderLayout$BorderConstraintsDescription">
<BorderConstraints direction="South"/>
</Constraint>
</Constraints>
</Component>
</SubComponents>
</Container>
</SubComponents>
</Form>

View File

@@ -1,286 +0,0 @@
//**********************************************************************************************
// Dipl. Phys. Joerg Plewe, HARDCODE Development
// Created on 27. Dezember 2001, 01:15
//**********************************************************************************************
package de.hardcode.jxinput.test;
import de.hardcode.jxinput.*;
import de.hardcode.jxinput.event.*;
import de.hardcode.jxinput.keyboard.JXKeyboardInputDevice;
import de.hardcode.jxinput.virtual.JXVirtualInputDevice;
import de.hardcode.jxinput.virtual.VirtualAxis;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/**
* Test dialog showing some features of JXInput.
* @author Herkules
*/
public class JXInputTestDialog extends javax.swing.JDialog
implements ActionListener
{
private JXKeyboardInputDevice mKeyboardDevice = null;
private JXVirtualInputDevice mVirtualDevice = null;
Button mButtonUp;
Button mButtonDown;
Button mButtonLeft;
Button mButtonRight;
Button mButtonFire;
Button mButtonSpace;
/** Creates new form JXInputTestDialog */
public JXInputTestDialog(java.awt.Frame parent, boolean modal)
{
super(parent, modal);
initComponents();
configureKeyboardInputDevice();
configureVirtualInputDevice();
initDevicePanels();
pack();
// Request the focus so that the keyboarddevice can work
mMainPanel.requestFocus();
new Timer( 50, this ).start();
// Uncomment this line as an alternative to the Timer above.
// Don't use both!!
//JXInputEventManager.setTriggerIntervall( 50 );
}
/**
* Implement ActionListener#actionPerformed().
* This is called by the Timer.
*/
public void actionPerformed( ActionEvent e )
{
JXInputManager.updateFeatures();
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
for ( int i = 0; i < mDevicesTabbedPane.getComponentCount(); ++i )
{
((JXInputDevicePanel)mDevicesTabbedPane.getComponent( i )).update();
}
}
}
);
}
/**
* Configure a test JXKeyboardInputdevice.
*/
void configureKeyboardInputDevice()
{
mKeyboardDevice = JXInputManager.createKeyboardDevice();
mKeyboardDevice.createButton( KeyEvent.VK_ESCAPE );
mKeyboardDevice.createButton( KeyEvent.VK_F1 );
mKeyboardDevice.createButton( KeyEvent.VK_F2 );
mKeyboardDevice.createButton( KeyEvent.VK_F3 );
mKeyboardDevice.createButton( KeyEvent.VK_F4 );
mKeyboardDevice.createButton( KeyEvent.VK_LEFT );
mKeyboardDevice.createButton( KeyEvent.VK_RIGHT );
mKeyboardDevice.createButton( KeyEvent.VK_UP );
mKeyboardDevice.createButton( KeyEvent.VK_DOWN );
mKeyboardDevice.createButton( KeyEvent.VK_PAGE_UP );
mKeyboardDevice.createButton( KeyEvent.VK_PAGE_DOWN );
mButtonSpace = mKeyboardDevice.createButton( KeyEvent.VK_SPACE );
mButtonLeft = mKeyboardDevice.createButton( KeyEvent.VK_A );
mButtonRight = mKeyboardDevice.createButton( KeyEvent.VK_D );
mButtonDown = mKeyboardDevice.createButton( KeyEvent.VK_S );
mButtonUp = mKeyboardDevice.createButton( KeyEvent.VK_W );
// Configure it to make it listen to the main panel.
// I try to keep the kbd focus on it.
mKeyboardDevice.listenTo( mMainPanel );
}
/**
* Configure a test JXVirtualInputdevice.
*/
void configureVirtualInputDevice()
{
mVirtualDevice = JXInputManager.createVirtualDevice();
Button firebutton;
//
// Remember 'fire' button of first device for use
// in the virtual device.
// For we ran configureKeyboardInputDevice() before,
// getJXInputDevice( 0 ) should not return null
//
firebutton = JXInputManager.getJXInputDevice( 0 ).getButton( 0 );
VirtualAxis x = mVirtualDevice.createAxis( Axis.ID_X );
x.setButtons( mButtonRight, mButtonLeft );
x.setName( "x: A-D" );
VirtualAxis y = mVirtualDevice.createAxis( Axis.ID_Y );
y.setButtons( mButtonUp, mButtonDown );
y.setSpringSpeed( 0.0 );
y.setName( "y: S|W" );
VirtualAxis slider = mVirtualDevice.createAxis( Axis.ID_SLIDER0 );
slider.setIncreaseButton( mButtonSpace );
slider.setTimeFor0To1( 2000 );
slider.setName( "<space>" );
slider.setType( Axis.SLIDER );
if ( null != firebutton )
{
slider = mVirtualDevice.createAxis( Axis.ID_SLIDER1 );
slider.setIncreaseButton( firebutton );
slider.setTimeFor0To1( 2000 );
slider.setName( "JoyButton 0" );
}
}
/**
* Initialize one panel for each device available.
*/
void initDevicePanels()
{
int cnt = JXInputManager.getNumberOfDevices();
mLabelNoDevice.setVisible( cnt == 0 );
mDevicesTabbedPane.setVisible( cnt != 0 );
for ( int i = 0; i < cnt; ++i )
{
JXInputDevice dev = JXInputManager.getJXInputDevice( i );
if ( null != dev )
{
//
// Setup an own panel for each device.
//
JPanel panel = new JXInputDevicePanel( dev );
mDevicesTabbedPane.addTab( dev.getName(), panel );
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents()
{
mMainPanel = new javax.swing.JPanel();
mLabelNoDevice = new javax.swing.JLabel();
mDevicesTabbedPane = new javax.swing.JTabbedPane();
mButtonReset = new javax.swing.JButton();
setTitle("JXInput (C) 2001-2006 HARDCODE Dev.");
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt)
{
closeDialog(evt);
}
});
mMainPanel.setLayout(new java.awt.BorderLayout(10, 0));
mLabelNoDevice.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
mLabelNoDevice.setText("No JXInputDevice available!");
mLabelNoDevice.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
mMainPanel.add(mLabelNoDevice, java.awt.BorderLayout.NORTH);
mDevicesTabbedPane.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusGained(java.awt.event.FocusEvent evt)
{
mDevicesTabbedPaneFocusGained(evt);
}
});
mMainPanel.add(mDevicesTabbedPane, java.awt.BorderLayout.CENTER);
mButtonReset.setText("Reset ");
mButtonReset.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
mButtonResetActionPerformed(evt);
}
});
mMainPanel.add(mButtonReset, java.awt.BorderLayout.SOUTH);
getContentPane().add(mMainPanel, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void mButtonResetActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_mButtonResetActionPerformed
{//GEN-HEADEREND:event_mButtonResetActionPerformed
while ( this.mDevicesTabbedPane.getTabCount() > 0 )
this.mDevicesTabbedPane.removeTabAt( 0 );
JXInputManager.reset();
configureKeyboardInputDevice();
configureVirtualInputDevice();
initDevicePanels();
pack();
// Request the focus so that the keyboarddevice can work
mMainPanel.requestFocus();
}//GEN-LAST:event_mButtonResetActionPerformed
private void mDevicesTabbedPaneFocusGained(java.awt.event.FocusEvent evt)//GEN-FIRST:event_mDevicesTabbedPaneFocusGained
{//GEN-HEADEREND:event_mDevicesTabbedPaneFocusGained
// Switch focus back to main panel!
this.mMainPanel.requestFocus();
}//GEN-LAST:event_mDevicesTabbedPaneFocusGained
/** Closes the dialog */
private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
setVisible(false);
dispose();
System.exit( 0 );
}//GEN-LAST:event_closeDialog
/**
* Allow the dialog to run standalone.
* @param args the command line arguments
*/
public static void main(String args[])
{
new JXInputTestDialog(new javax.swing.JFrame(), true).setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton mButtonReset;
private javax.swing.JTabbedPane mDevicesTabbedPane;
private javax.swing.JLabel mLabelNoDevice;
private javax.swing.JPanel mMainPanel;
// End of variables declaration//GEN-END:variables
}

View File

@@ -1,98 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 17. April 2002, 23:24
//**********************************************************************************************
package de.hardcode.jxinput.util;
import de.hardcode.jxinput.Axis;
/**
*
* @author Herkules
*/
public class LatestChangedValueAxis implements Axis
{
private final Axis mAxis1;
private final Axis mAxis2;
private Axis mAxisInUse;
private double mSaved1;
private double mSaved2;
/**
* Creates a new instance of MeanValueAxis.
*/
public LatestChangedValueAxis(Axis a1, Axis a2)
{
mAxis1 = a1;
mAxis2 = a2;
mAxisInUse = a1;
mSaved1 = a1.getValue();
mSaved2 = a2.getValue();
}
/**
* Features may have a name provided e.g. by the driver.
*/
public String getName()
{
return mAxis1.getName();
}
/** Inform about the resolution of the axis.
*
* @return resolution, e.g. 2^-16
*/
public double getResolution()
{
return mAxis1.getResolution();
}
/**
* Retrieve the type of the axis.
*
* @return [ TRANSLATION | ROTATION | SLIDER ]
*/
public int getType()
{
return mAxis1.getType();
}
/** Returns the current value of the axis.
* The range of the result depends on the axis type.
*s
* @return value [-1.0,1.0] or [0.0,1.0]
*/
public double getValue()
{
double v1 = mAxis1.getValue();
double v2 = mAxis2.getValue();
if ( Math.abs( v2 - mSaved2 ) > 0.2 )
{
mAxisInUse = mAxis2;
mSaved2 = v2;
}
if ( Math.abs( v1 - mSaved1 ) > 0.2 )
{
mAxisInUse = mAxis1;
mSaved1 = v1;
}
return mAxisInUse.getValue();
}
/** Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
}

View File

@@ -1,52 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 23. Dezember 2002, 19:21
//**********************************************************************************************
package de.hardcode.jxinput.util;
import de.hardcode.jxinput.Button;
/**
*
* @author Herkules
*/
public class OrButton implements Button
{
private final Button mButton1;
private final Button mButton2;
/**
* Creates a new instance of OrButton.
*/
public OrButton( Button b1, Button b2 )
{
mButton1 = b1;
mButton2 = b2;
}
public String getName()
{
return mButton1.getName();
}
public boolean getState()
{
return mButton1.getState() || mButton2.getState();
}
public int getType()
{
return mButton1.getType();
}
public boolean hasChanged()
{
return mButton1.hasChanged() || mButton2.hasChanged();
}
}

View File

@@ -1,140 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 9. April 2002, 22:40
//**********************************************************************************************
package de.hardcode.jxinput.virtual;
import de.hardcode.jxinput.*;
/**
* Virtual input device.
*
* @author Herkules
*/
public class JXVirtualInputDevice implements JXInputDevice
{
private static final String DEVICENAME = "Virtual Device";
/** The driver doing all the real work. */
private final VirtualDriver mDriver = new VirtualDriver();
/**
* Creates a new instance of JXKeyboardInputDevice.
*/
public JXVirtualInputDevice()
{
}
/**
* The virtual input device needs to be updated regularly.
*/
public final void update( long deltaT )
{
//
// Delegate the update call to the driver.
//
mDriver.update( deltaT );
}
/**
* Create a virtual axis object with a certain ID, e.g. Axis.ID_X.
*/
public VirtualAxis createAxis( int id )
{
VirtualAxis a;
a = new VirtualAxis( id );
mDriver.registerVirtualAxis( id, a );
return a;
}
public void removeAxis( VirtualAxis a )
{
mDriver.unregisterVirtualAxis( a );
}
//*********************************************************************************************
//
// Implement JXInputDevice
//
//*********************************************************************************************
public Axis getAxis(int idx)
{
return mDriver.getAxis( idx );
}
public Button getButton(int idx)
{
// No virtual buttons.
return null;
}
public Directional getDirectional(int idx)
{
// No virtual directionals.
return null;
}
/** Maximum number of axes as an upper bound for index values. */
public int getMaxNumberOfAxes()
{
return Axis.NUMBER_OF_ID;
}
/** Maximum number of buttons as an upper bound for index values. */
public int getMaxNumberOfButtons()
{
// No virtual buttons.
return 0;
}
/** Maximum number of directional features as an upper bound for index values. */
public int getMaxNumberOfDirectionals()
{
// No virtual directionals.
return 0;
}
/**
* Devices may have a name.
* This name might be provided by a system dependant driver.
*/
public String getName()
{
return DEVICENAME;
}
/** Actual number of available axes. */
public int getNumberOfAxes()
{
// No axes on keyboard.
return mDriver.getNumberOfAxes();
}
/** Actual number of available buttons. */
public int getNumberOfButtons()
{
return 0;
}
/** Actual number of available directional features. */
public int getNumberOfDirectionals()
{
// No directionals on keyboard.
return 0;
}
}

View File

@@ -1,207 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 11. April 2002, 23:40
//**********************************************************************************************
package de.hardcode.jxinput.virtual;
import de.hardcode.jxinput.Axis;
import de.hardcode.jxinput.Button;
import java.security.InvalidParameterException;
/**
*
* @author J<>rg Plewe
*/
public class VirtualAxis
implements Axis
{
private int mType = Axis.TRANSLATION;
private final int mID;
private String mName = "VirtualAxis";
private double mCurrentValue = 0;
private Button mButtonIncrease = null;
private Button mButtonDecrease = null;
private double mSpeed = 1.0 / 500.0;
private double mSpringSpeed = 1.0 / 500.0;
/**
* Creates a new instance of VirtualAxis.
*/
public VirtualAxis( int id )
{
mID = id;
}
/**
* Set the type of this axis to be either <code>Axis.ROTATION</code>,
* <code>Axis.TRANSLATION</code> or <code>Axis.SLIDER</code>.
*/
public void setType( int type )
{
if ( Axis.ROTATION != type
&& Axis.TRANSLATION != type
&& Axis.SLIDER != type
)
throw new InvalidParameterException( "Invalid type for axis!" );
mType = type;
}
/**
* Update features under my control.
*/
final void update( long deltaT )
{
double change = mSpeed * deltaT;
double springchange = mSpringSpeed * deltaT;
boolean doincrease = ( null != mButtonIncrease && mButtonIncrease.getState() );
boolean dodecrease = ( null != mButtonDecrease && mButtonDecrease.getState() );
boolean iscontrolled = doincrease || dodecrease;
double controlledchange = 0.0;
if ( doincrease )
controlledchange += change;
if ( dodecrease )
controlledchange -= change;
mCurrentValue += controlledchange;
if ( mCurrentValue > 0.0 && ! doincrease )
{
springchange = Math.min( mCurrentValue, springchange );
mCurrentValue -= springchange;
}
if ( mCurrentValue < 0.0 && ! dodecrease )
{
springchange = Math.min( -mCurrentValue, springchange );
mCurrentValue += springchange;
}
//
// Hold value within range
//
if ( mCurrentValue > 1.0 )
mCurrentValue = 1.0;
double lowerlimit = Axis.SLIDER == mType ? 0.0 : -1.0;
if ( mCurrentValue < lowerlimit )
mCurrentValue = lowerlimit;
}
/**
* Set the button to increase the axis for a single button axis.
*/
public final void setIncreaseButton( Button b )
{
if ( null == b )
throw new InvalidParameterException( "Button may not be null!" );
mButtonIncrease = b;
}
/**
* Set the buttons to increase and descrease the axis.
*/
public final void setButtons( Button increase, Button decrease )
{
if ( null == increase || null == decrease )
throw new InvalidParameterException( "Buttons may not be null!" );
mButtonIncrease = increase;
mButtonDecrease = decrease;
}
public final void setSpeed( double speed )
{
mSpeed = speed;
}
public final void setSpringSpeed( double springspeed )
{
mSpringSpeed = springspeed;
}
public final void setTimeFor0To1( int ms )
{
if ( 0 >= ms )
mSpeed = 0.0;
else
mSpeed = 1.0/ ms;
}
public final void setTimeFor1To0( int ms )
{
if ( 0 >= ms )
mSpringSpeed = 0.0;
else
mSpringSpeed = 1.0/ ms;
}
public final void setName( String name )
{
mName = name;
}
//*********************************************************************************************
//
// Implement Axis
//
//*********************************************************************************************
/**
* Features may have a name provided e.g. by the driver.
*/
public String getName()
{
return mName;
}
/**
* Inform about the resolution of the axis.
*
* @return resolution, e.g. 2^-16
*/
public double getResolution()
{
return 1.0/65536.0;
}
/**
* Retrieve the type of the axis.
* @return [ TRANSLATION | ROTATION | SLIDER ]
*/
public int getType()
{
return mType;
}
/** Returns the current value of the axis.
* The range of the result depends on the axis type.
*
* @return value [-1.0,1.0] or [0.0,1.0]
*/
public double getValue()
{
return mCurrentValue;
}
/** Denote wether this feature has changed beyond it's resolution since it got last
* updated.
*/
public boolean hasChanged()
{
return true;
}
}

View File

@@ -1,95 +0,0 @@
//**********************************************************************************************
// (C) Copyright 2002 by Dipl. Phys. Joerg Plewe, HARDCODE Development
// All rights reserved. Copying, modification,
// distribution or publication without the prior written
// consent of the author is prohibited.
//
// Created on 9. April 2002, 22:43
//**********************************************************************************************
package de.hardcode.jxinput.virtual;
import java.util.ArrayList;
import de.hardcode.jxinput.Axis;
/**
* This is the main worker class for JXVirtualInputDevice.
*
* @author Herkules
*/
class VirtualDriver
{
private final VirtualAxis[] mVAxes = new VirtualAxis[ Axis.NUMBER_OF_ID ];
/**
* Creates a new instance of KeyboardDriver.
*/
VirtualDriver()
{
}
/**
* Update features under my control.
*/
final void update( long deltaT )
{
//
// Delegate the update call to the axes in use.
//
for ( int i = 0; i < mVAxes.length; i++ )
{
if ( null != mVAxes[ i ] )
mVAxes[ i ].update( deltaT );
}
}
/**
* How many axes are registered?
*/
final int getNumberOfAxes()
{
int ctr = 0;
for ( int i = 0; i < mVAxes.length; i++ )
{
if ( null != mVAxes[ i ] )
ctr++;
}
return ctr;
}
Axis getAxis(int idx)
{
return mVAxes[ idx ];
}
/**
* Place a new axis under my observation.
*/
final void registerVirtualAxis( int id, VirtualAxis a )
{
mVAxes[ id ] = a;
}
/**
* Remove an axis from my control.
*/
final void unregisterVirtualAxis( VirtualAxis a )
{
for ( int i = 0; i < mVAxes.length; ++i )
{
if ( mVAxes[ i ] == a )
{
mVAxes[ i ] = null;
break;
}
}
}
}

View File

@@ -1,11 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>de.hardcode.jxinput.virtual</TITLE>
</HEAD>
<BODY>
Allows to define virtual axes that are not derived from any device
but from other JXInput feature objects.
</BODY>
</HTML>

Binary file not shown.

Binary file not shown.

View File

@@ -1,34 +0,0 @@
# Project: wpcom
# Makefile created by Dev-C++ 4.9.9.2
CPP = g++.exe
CC = gcc.exe
WINDRES = windres.exe
RES =
OBJ = WinampController.o $(RES)
LINKOBJ = WinampController.o $(RES)
LIBS = -L"E:/java/Dev-Cpp/lib" --no-export-all-symbols --add-stdcall-alias
INCS = -I"E:/java/Dev-Cpp/include" -I"E:/Program Files/Java/jdk1.6.0_11/include" -I"E:/Program Files/Java/jdk1.6.0_11/include/win32"
CXXINCS = -I"E:/java/Dev-Cpp/lib/gcc/mingw32/3.4.2/include" -I"E:/java/Dev-Cpp/include/c++/3.4.2/backward" -I"E:/java/Dev-Cpp/include/c++/3.4.2/mingw32" -I"E:/java/Dev-Cpp/include/c++/3.4.2" -I"E:/java/Dev-Cpp/include" -I"E:/Program Files/Java/jdk1.6.0_11/include" -I"E:/Program Files/Java/jdk1.6.0_11/include/win32"
BIN = ../../wpcom.dll
CXXFLAGS = $(CXXINCS) -DBUILDING_DLL=1
CFLAGS = $(INCS) -DBUILDING_DLL=1
RM = rm -f
.PHONY: all all-before all-after clean clean-custom
all: all-before ../../wpcom.dll all-after
clean: clean-custom
${RM} $(OBJ) $(BIN)
DLLWRAP=dllwrap.exe
DEFFILE=../../libwpcom.def
STATICLIB=../../libwpcom.a
$(BIN): $(LINKOBJ)
$(DLLWRAP) --output-def $(DEFFILE) --implib $(STATICLIB) $(LINKOBJ) $(LIBS) -o $(BIN)
WinampController.o: WinampController.c
$(CC) -c WinampController.c -o WinampController.o $(CFLAGS)

View File

@@ -1,62 +0,0 @@
#define WINAMP_FILE_QUIT 40001
#define WINAMP_OPTIONS_PREFS 40012
#define WINAMP_OPTIONS_AOT 40019
#define WINAMP_FILE_REPEAT 40022
#define WINAMP_FILE_SHUFFLE 40023
#define WINAMP_HIGH_PRIORITY 40025
#define WINAMP_FILE_PLAY 40029
#define WINAMP_OPTIONS_EQ 40036
#define WINAMP_OPTIONS_ELAPSED 40037
#define WINAMP_OPTIONS_REMAINING 40038
#define WINAMP_OPTIONS_PLEDIT 40040
#define WINAMP_HELP_ABOUT 40041
#define WINAMP_MAINMENU 40043
#define WINAMP_BUTTON1 40044
#define WINAMP_BUTTON2 40045
#define WINAMP_BUTTON3 40046
#define WINAMP_BUTTON4 40047
#define WINAMP_BUTTON5 40048
#define WINAMP_VOLUMEUP 40058
#define WINAMP_VOLUMEDOWN 40059
#define WINAMP_FFWD5S 40060
#define WINAMP_REW5S 40061
#define WINAMP_NEXT_WINDOW 40063
#define WINAMP_OPTIONS_WINDOWSHADE 40064
#define WINAMP_BUTTON1_SHIFT 40144
#define WINAMP_BUTTON2_SHIFT 40145
#define WINAMP_BUTTON3_SHIFT 40146
#define WINAMP_BUTTON4_SHIFT 40147
#define WINAMP_BUTTON5_SHIFT 40148
#define WINAMP_BUTTON1_CTRL 40154
#define WINAMP_BUTTON2_CTRL 40155
#define WINAMP_BUTTON3_CTRL 40156
#define WINAMP_BUTTON4_CTRL 40157
#define WINAMP_BUTTON5_CTRL 40158
#define WINAMP_OPTIONS_DSIZE 40165
#define IDC_SORT_FILENAME 40166
#define IDC_SORT_FILETITLE 40167
#define IDC_SORT_ENTIREFILENAME 40168
#define IDC_SELECTALL 40169
#define IDC_SELECTNONE 40170
#define IDC_SELECTINV 40171
#define IDM_EQ_LOADPRE 40172
#define IDM_EQ_LOADMP3 40173
#define IDM_EQ_LOADDEFAULT 40174
#define IDM_EQ_SAVEPRE 40175
#define IDM_EQ_SAVEMP3 40176
#define IDM_EQ_SAVEDEFAULT 40177
#define IDM_EQ_DELPRE 40178
#define IDM_EQ_DELMP3 40180
#define IDC_PLAYLIST_PLAY 40184
#define WINAMP_FILE_LOC 40185
#define WINAMP_OPTIONS_EASYMOVE 40186
#define WINAMP_FILE_DIR 40187
#define WINAMP_EDIT_ID3 40188
#define WINAMP_TOGGLE_AUTOSCROLL 40189
#define WINAMP_VISSETUP 40190
#define WINAMP_PLGSETUP 40191
#define WINAMP_VISPLUGIN 40192
#define WINAMP_JUMP 40193
#define WINAMP_JUMPFILE 40194
#define WINAMP_JUMP10FWD 40195
#define WINAMP_JUMP10BACK 40197

View File

@@ -1,587 +0,0 @@
/* meu .h */
#include "WinampController.h"
/* mingw */
#include <windows.h>
#include <w32api.h>
#include <winuser.h>
/* winamp sdk */
#include "wa_ipc.h"
#include "WINAMPCMD.H"
const int WA_CLOSE = 40001 ;
const int WA_PLAY = WINAMP_BUTTON2;
const int WA_STOP = WINAMP_BUTTON4;
const int WA_PAUSE = WINAMP_BUTTON3;
const int WA_PREVTRACK = WINAMP_BUTTON1;
const int WA_NEXTTRACK = WINAMP_BUTTON5;
const int WA_FWD5SECS = WINAMP_FFWD5S;
const int WA_REW5SECS = WINAMP_REW5S;
const int WA_PLAYLISTLEN = IPC_GETLISTLENGTH;
const int WA_SETVOLUME = IPC_SETVOLUME;
const int WA_SETPLAYLISTPOS = IPC_SETPLAYLISTPOS;
const int WA_WRITEPLAYLIST = IPC_WRITEPLAYLIST;
const int WA_ENQUEUEFILE = IPC_ENQUEUEFILE;
const int WA_VOLUMEUP = WINAMP_VOLUMEUP;
const int WA_VOLUMEDOWN = WINAMP_VOLUMEDOWN;
const int WA_CLEARPLAYLIST = IPC_DELETE;
const int WA_NOTHING = 0;
const int WA_TRACK_LENGTH = 1;
const int WA_RESTART = IPC_RESTARTWINAMP;
const int WA_REFRESHPLCACHE = IPC_REFRESHPLCACHE;
const int WA_GETSHUFFLESTATUS = IPC_GET_SHUFFLE;
const int WA_GETREPEATSTATUS = IPC_GET_REPEAT;
const int WA_SETSHUFFLESTATUS = IPC_SET_SHUFFLE;
const int WA_SETREPEATSTATUS = IPC_SET_REPEAT;
const int WA_GETSTATUS = IPC_ISPLAYING;
const int WA_GETLISTPOS = IPC_GETLISTPOS;
const int WA_GETTITLE = IPC_GETPLAYLISTTITLE;
const int WA_VERSION = IPC_GETVERSION;
const int WA_FILENAMEINLIST = IPC_GETPLAYLISTFILE;
const int WA_GETFILEINFO = IPC_GET_EXTENDED_FILE_INFO;
HWND hwnd_winamp = NULL;
INT position = 0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
char messageReturn[255];
wchar_t* wMessageReturn;
LPDWORD temp;
void initWinampHandle() {
hwnd_winamp = NULL;
if (hwnd_winamp == NULL) {
hwnd_winamp = FindWindow("Winamp v1.x", NULL);
}
if (hwnd_winamp == NULL) {
hwnd_winamp = FindWindow("Winamp v2.x", NULL);
}
if (hwnd_winamp == NULL) {
hwnd_winamp = FindWindow("Winamp v3.x", NULL);
}
}
jboolean runWinamp(unsigned char* pathWinamp) {
/* STARTUPINFO si;
PROCESS_INFORMATION pi;*/
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
// Start the child process.
if(!CreateProcess(pathWinamp,
NULL,
0,
0,
FALSE,
CREATE_NEW_CONSOLE,
0,
0,
&si,
&pi))
{
return FALSE;
}
DWORD dwResult = WaitForInputIdle(pi.hProcess,INFINITE);
if (dwResult != 0) return FALSE;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return TRUE;
}
int getListPos() {
initWinampHandle();
if (hwnd_winamp != NULL) {
return SendMessage(hwnd_winamp,WM_USER,WA_NOTHING,WA_GETLISTPOS);
}
return -1;
}
void getPluginMessage(int param, int sendMessage)
{
LPCVOID message = (LPCVOID)SendMessageW(hwnd_winamp, WM_USER, param, sendMessage);
ZeroMemory( &pi, sizeof(pi));
GetWindowThreadProcessId(hwnd_winamp, &pi.dwThreadId);
pi.hProcess = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pi.dwThreadId);
ReadProcessMemory(pi.hProcess, message, messageReturn,2056,temp);
free(temp);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_run
(JNIEnv *env, jobject obj) {
initWinampHandle();
if ( hwnd_winamp == NULL ) {
unsigned char path[MAX_PATH]="";
DWORD size = MAX_PATH;
HKEY key;
DWORD tipo;
if (!RegOpenKey(HKEY_LOCAL_MACHINE,"Software\\Clients\\Media\\Winamp\\shell\\open\\command",&key)==ERROR_SUCCESS)
{
printf("0");
return FALSE;
}
if (!(RegQueryValueEx(key,"",NULL,&tipo,path,&size))==ERROR_SUCCESS)
{
RegCloseKey(key);
return FALSE;
}
if (!runWinamp(path))
{
RegCloseKey(key);
return FALSE;
}
return TRUE;
}
int version = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION);
return TRUE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_exit
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_CLOSE, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_play
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_PLAY, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_stop
(JNIEnv *env, jobject obj)
{
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_STOP, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_resume
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_PAUSE, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_pause
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_PAUSE, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_previousTrack
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_PREVTRACK, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_nextTrack
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_NEXTTRACK, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_fwd5Secs
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_FWD5SECS, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_rew5Secs
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_REW5SECS, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_increaseVolume
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_VOLUMEUP, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_decreaseVolume
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_VOLUMEDOWN, WA_NOTHING);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_increaseVolumePercent
(JNIEnv *env, jobject obj, jint percent) {
initWinampHandle();
int i = 0;
if (hwnd_winamp != NULL) {
for(i=0;i<percent;i++) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_VOLUMEUP, WA_NOTHING);
}
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_decreaseVolumePercent
(JNIEnv *env, jobject obj, jint percent) {
initWinampHandle();
int i = 0;
if (hwnd_winamp != NULL) {
for(i=0;i<percent;i++) {
SendMessageA(hwnd_winamp, WM_COMMAND, WA_VOLUMEDOWN, WA_NOTHING);
}
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setVolume
(JNIEnv *env, jobject obj, jint pos) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, pos, WA_SETVOLUME);
return TRUE;
}
return FALSE;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getVolume
(JNIEnv *env, jobject obj, jint pos) {
jint curVolume = -1;
initWinampHandle();
if (hwnd_winamp != NULL) {
curVolume = (jint)SendMessageA(hwnd_winamp, WM_USER, -666, WA_SETVOLUME);
}
return curVolume;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_restart
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_RESTART);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setPlaylistPosition
(JNIEnv *env, jobject obj, jint pos) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, pos, WA_SETPLAYLISTPOS);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_clearPlayList
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_CLEARPLAYLIST);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_refreshPlayListCache
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_REFRESHPLCACHE);
return TRUE;
}
return FALSE;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getPlayListLength
(JNIEnv *env, jobject obj) {
jint length = -1;
initWinampHandle();
if (hwnd_winamp != NULL) {
length = (jint)SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_PLAYLISTLEN);
}
return length;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_writePlayListToFile
(JNIEnv *env, jobject obj) {
jint length = -1;
initWinampHandle();
if (hwnd_winamp != NULL) {
length = SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_WRITEPLAYLIST);
}
return length;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_isShuffleStatusOn
(JNIEnv *env, jobject obj) {
jint status = 0;
initWinampHandle();
if (hwnd_winamp != NULL) {
status = (jint)SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_GETSHUFFLESTATUS);
} else
return -1;
return status>0?1:0;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_isRepeatStatusOn
(JNIEnv *env, jobject obj) {
jint status = 0;
initWinampHandle();
if (hwnd_winamp != NULL) {
status = (jint)SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_GETREPEATSTATUS);
} else
return -1;
return status>0?1:0;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setRepeatStatusOn
(JNIEnv *env, jobject obj, jboolean status) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, status, WA_SETREPEATSTATUS);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setShuffleStatusOn
(JNIEnv *env, jobject obj, jboolean status) {
initWinampHandle();
if (hwnd_winamp != NULL) {
SendMessageA(hwnd_winamp, WM_USER, status, WA_SETSHUFFLESTATUS);
return TRUE;
}
return FALSE;
}
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_appendToPlayList
(JNIEnv *env, jobject obj, jstring mp3filename) {
initWinampHandle();
jboolean iscopy;
if (hwnd_winamp != NULL) {
wMessageReturn = (wchar_t*)(*env)->GetStringChars(env, mp3filename, &iscopy);
int length = wcslen(wMessageReturn);
COPYDATASTRUCT cds;
cds.dwData = IPC_PLAYFILEW;
cds.lpData = (void*)wMessageReturn;
cds.cbData = length * 2 + 2 ; // it sums white space
SendMessageW(hwnd_winamp, WM_COPYDATA, WA_NOTHING, (LPARAM)&cds);
return TRUE;
}
return FALSE;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getStatus
(JNIEnv *env, jobject obj) {
jint status = -1;
initWinampHandle();
if (hwnd_winamp != NULL) {
status = SendMessageA(hwnd_winamp, WM_USER, WA_NOTHING, WA_GETSTATUS);
}
return status;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getListPos
(JNIEnv *env, jobject obj) {
return getListPos();
}
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getTitle
(JNIEnv *env, jobject obj) {
initWinampHandle();
if (hwnd_winamp != NULL) {
char title[500] = "";
GetWindowText(hwnd_winamp,title,500);
return (*env)->NewStringUTF(env,title);
}
return NULL;
}
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getTime
(JNIEnv *env, jobject obj, jint mode) {
initWinampHandle();
if (hwnd_winamp != NULL) {
return SendMessage(hwnd_winamp,WM_USER,mode,IPC_GETOUTPUTTIME);
}
return -2;
}
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getFileNameInList
(JNIEnv *env, jobject obj, jint index)
{
initWinampHandle();
if (hwnd_winamp != NULL) {
getPluginMessage(index, WA_FILENAMEINLIST);
char* filePath = messageReturn;
jstring strReturn = (*env)->NewStringUTF(env,filePath);
return strReturn;
}
return NULL;
}
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getFileNamePlaying
(JNIEnv *env, jobject obj)
{
initWinampHandle();
if (hwnd_winamp != NULL) {
getPluginMessage(WA_NOTHING, IPC_GET_PLAYING_FILENAME);
wchar_t* fileName = (wchar_t*)messageReturn;
int length = wcslen(fileName);
jstring strReturn = (*env)->NewString(env,fileName,length);
return strReturn;
}
return NULL;
}

View File

@@ -1,285 +0,0 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class WinampController */
#ifndef _Included_WinampController
#define _Included_WinampController
#ifdef __cplusplus
extern "C" {
#endif
void initWinampHandle();
jboolean runWinamp(unsigned char* pathWinamp);
int getListPos();
void getPluginMessage(int param, int sendMessage);
/*
* Class: WinampController
* Method: run
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_run
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: exit
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_exit
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: play
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_play
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: stop
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_stop
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: resume
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_resume
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: pause
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_pause
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: previousTrack
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_previousTrack
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: nextTrack
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_nextTrack
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: fwd5Secs
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_fwd5Secs
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: fwd5Secs
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_rew5Secs
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: increaseVolume
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_increaseVolume
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: decreaseVolume
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_decreaseVolume
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: increaseVolumePercent
* Signature: (I)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_increaseVolumePercent
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: decreaseVolumePercent
* Signature: (I)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_decreaseVolumePercent
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: setVolume
* Signature: (I)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setVolume
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: setVolume
* Signature: (I)V
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getVolume
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: restart
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_restart
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: setPlaylistPosition
* Signature: (I)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setPlaylistPosition
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: clearPlayList
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_clearPlayList
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: refreshPlayListCache
* Signature: ()V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_refreshPlayListCache
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: getPlayListLength
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getPlayListLength
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: writePlayListToFile
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_writePlayListToFile
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: isShuffleStatusOn
* Signature: ()Z
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_isShuffleStatusOn
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: isRepeatStatusOn
* Signature: ()Z
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_isRepeatStatusOn
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: setRepeatStatusOn
* Signature: (Z)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setRepeatStatusOn
(JNIEnv *, jclass, jboolean);
/*
* Class: WinampController
* Method: setShuffleStatusOn
* Signature: (Z)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_setShuffleStatusOn
(JNIEnv *, jclass, jboolean);
/*
* Class: WinampController
* Method: appendToPlayList
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jboolean JNICALL Java_com_qotsa_jni_controller_JNIWinamp_appendToPlayList
(JNIEnv *, jclass, jstring);
/*
* Class: WinampController
* Method: getStatus
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getStatus
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: getListPos
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getListPos
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: getTitle
* Signature: ()I
*/
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getTitle
(JNIEnv *, jclass);
/*
* Class: WinampController
* Method: getTime
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getTime
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: getFileNameInList
* Signature: ()I
*/
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getFileNameInList
(JNIEnv *, jclass, jint);
/*
* Class: WinampController
* Method: getFileNamePlaying
* Signature: ()I
*/
JNIEXPORT jstring JNICALL Java_com_qotsa_jni_controller_JNIWinamp_getFileNamePlaying
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1 +0,0 @@
copy /y wpcom.dll c:\winnt\system32\

View File

@@ -1,58 +0,0 @@
; dlltool --base-file C:\DOCUME~1\FRANCI~1\CONFIG~1\Temp/cca03628.base --output-exp wpcom.exp --dllname wpcom.dll --output-def libwpcom.def --no-export-all-symbols --add-stdcall-alias --exclude-symbol=DllMainCRTStartup@12 --def C:\DOCUME~1\FRANCI~1\CONFIG~1\Temp/cca03628.def --output-lib libwpcom.a
EXPORTS
Java_controller_JNIWinampController_appendToPlayList = Java_controller_JNIWinampController_appendToPlayList@12 @ 1
Java_controller_JNIWinampController_appendToPlayList@12 @ 2
Java_controller_JNIWinampController_clearPlayList = Java_controller_JNIWinampController_clearPlayList@8 @ 3
Java_controller_JNIWinampController_clearPlayList@8 @ 4
Java_controller_JNIWinampController_clearPlayListCache = Java_controller_JNIWinampController_clearPlayListCache@8 @ 5
Java_controller_JNIWinampController_clearPlayListCache@8 @ 6
Java_controller_JNIWinampController_decreaseVolume = Java_controller_JNIWinampController_decreaseVolume@8 @ 7
Java_controller_JNIWinampController_decreaseVolume@8 @ 8
Java_controller_JNIWinampController_decreaseVolumePercent = Java_controller_JNIWinampController_decreaseVolumePercent@12 @ 9
Java_controller_JNIWinampController_decreaseVolumePercent@12 @ 10
Java_controller_JNIWinampController_exit = Java_controller_JNIWinampController_exit@8 @ 11
Java_controller_JNIWinampController_exit@8 @ 12
Java_controller_JNIWinampController_getListPos = Java_controller_JNIWinampController_getListPos@8 @ 13
Java_controller_JNIWinampController_getListPos@8 @ 14
Java_controller_JNIWinampController_getPlayListLength = Java_controller_JNIWinampController_getPlayListLength@8 @ 15
Java_controller_JNIWinampController_getPlayListLength@8 @ 16
Java_controller_JNIWinampController_getSeconds = Java_controller_JNIWinampController_getSeconds@8 @ 17
Java_controller_JNIWinampController_getSeconds@8 @ 18
Java_controller_JNIWinampController_getStatus = Java_controller_JNIWinampController_getStatus@8 @ 19
Java_controller_JNIWinampController_getStatus@8 @ 20
Java_controller_JNIWinampController_getTitle = Java_controller_JNIWinampController_getTitle@8 @ 21
Java_controller_JNIWinampController_getTitle@8 @ 22
Java_controller_JNIWinampController_increaseVolume = Java_controller_JNIWinampController_increaseVolume@8 @ 23
Java_controller_JNIWinampController_increaseVolume@8 @ 24
Java_controller_JNIWinampController_increaseVolumePercent = Java_controller_JNIWinampController_increaseVolumePercent@12 @ 25
Java_controller_JNIWinampController_increaseVolumePercent@12 @ 26
Java_controller_JNIWinampController_isRepeatStatusOn = Java_controller_JNIWinampController_isRepeatStatusOn@8 @ 27
Java_controller_JNIWinampController_isRepeatStatusOn@8 @ 28
Java_controller_JNIWinampController_isShuffleStatusOn = Java_controller_JNIWinampController_isShuffleStatusOn@8 @ 29
Java_controller_JNIWinampController_isShuffleStatusOn@8 @ 30
Java_controller_JNIWinampController_nextTrack = Java_controller_JNIWinampController_nextTrack@8 @ 31
Java_controller_JNIWinampController_nextTrack@8 @ 32
Java_controller_JNIWinampController_pause = Java_controller_JNIWinampController_pause@8 @ 33
Java_controller_JNIWinampController_pause@8 @ 34
Java_controller_JNIWinampController_play = Java_controller_JNIWinampController_play@8 @ 35
Java_controller_JNIWinampController_play@8 @ 36
Java_controller_JNIWinampController_previousTrack = Java_controller_JNIWinampController_previousTrack@8 @ 37
Java_controller_JNIWinampController_previousTrack@8 @ 38
Java_controller_JNIWinampController_restart = Java_controller_JNIWinampController_restart@8 @ 39
Java_controller_JNIWinampController_restart@8 @ 40
Java_controller_JNIWinampController_resume = Java_controller_JNIWinampController_resume@8 @ 41
Java_controller_JNIWinampController_resume@8 @ 42
Java_controller_JNIWinampController_run = Java_controller_JNIWinampController_run@8 @ 43
Java_controller_JNIWinampController_run@8 @ 44
Java_controller_JNIWinampController_setPlaylistPosition = Java_controller_JNIWinampController_setPlaylistPosition@12 @ 45
Java_controller_JNIWinampController_setPlaylistPosition@12 @ 46
Java_controller_JNIWinampController_setRepeatStatusOn = Java_controller_JNIWinampController_setRepeatStatusOn@12 @ 47
Java_controller_JNIWinampController_setRepeatStatusOn@12 @ 48
Java_controller_JNIWinampController_setShuffleStatusOn = Java_controller_JNIWinampController_setShuffleStatusOn@12 @ 49
Java_controller_JNIWinampController_setShuffleStatusOn@12 @ 50
Java_controller_JNIWinampController_setVolume = Java_controller_JNIWinampController_setVolume@12 @ 51
Java_controller_JNIWinampController_setVolume@12 @ 52
Java_controller_JNIWinampController_stop = Java_controller_JNIWinampController_stop@8 @ 53
Java_controller_JNIWinampController_stop@8 @ 54
Java_controller_JNIWinampController_writePlayListToFile = Java_controller_JNIWinampController_writePlayListToFile@8 @ 55
Java_controller_JNIWinampController_writePlayListToFile@8 @ 56

File diff suppressed because it is too large Load Diff

View File

@@ -1,69 +0,0 @@
[Project]
FileName=wpcom.dev
Name=wpcom
UnitCount=2
Type=3
Ver=1
ObjFiles=
Includes="E:\Program Files\Java\jdk1.6.0_11\include";"E:\Program Files\Java\jdk1.6.0_11\include\win32"
Libs=
PrivateResource=
ResourceIncludes=
MakeIncludes=
Compiler=-DBUILDING_DLL=1_@@_
CppCompiler=-DBUILDING_DLL=1_@@_
Linker=--no-export-all-symbols --add-stdcall-alias_@@_
IsCpp=0
Icon=
ExeOutput=..\..\..\JavaWinampAPI
ObjectOutput=
OverrideOutput=1
OverrideOutputName=wpcom.dll
HostApplication=
Folders=
CommandLine=
UseCustomMakefile=0
CustomMakefile=
IncludeVersionInfo=0
SupportXPThemes=0
CompilerSet=0
CompilerSettings=0000000000000000000000
[Unit1]
FileName=WinampController.c
CompileCpp=0
Folder=wacon
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=$(CC) -c WinampController.c -o WinampController.o $(CFLAGS)
[VersionInfo]
Major=0
Minor=1
Release=1
Build=1
LanguageID=1033
CharsetID=1252
CompanyName=
FileVersion=
FileDescription=Developed using the Dev-C++ IDE
InternalName=
LegalCopyright=
LegalTrademarks=
OriginalFilename=
ProductName=
ProductVersion=
AutoIncBuildNr=0
[Unit2]
FileName=WinampController.h
CompileCpp=0
Folder=wacon
Compile=1
Link=1
Priority=1000
OverrideBuildCmd=0
BuildCmd=

View File

@@ -1,17 +0,0 @@
[Editor_0]
CursorCol=32
CursorRow=359
TopLine=338
LeftChar=1
Open=1
Top=1
[Editors]
Focused=0
Order=1,0
[Editor_1]
Open=1
Top=0
CursorCol=73
CursorRow=143
TopLine=127
LeftChar=1

View File

@@ -1,40 +0,0 @@
/*
* InvalidHandle.java
*
* Created on 9 de Outubro de 2007, 14:18
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.qotsa.exception;
/**
* Exception to throw when Winamp Handle Fails.
*
* @author Francisco
*/
public class InvalidHandle extends Exception{
private static final String defaultMessage = "Invalid Handle. Please Verify if Winamp is running.";
/**
* Creates a new instance of InvalidHandle
* @param message Message to print in the stack.
*/
public InvalidHandle(String message) {
super(message);
}
/**
* Creates a new instance of InvalidHandle with the default message
*/
public InvalidHandle() {
super(defaultMessage);
}
}

View File

@@ -1,40 +0,0 @@
/*
* InvalidParameter.java
*
* Created on 11 de Outubro de 2007, 10:53
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.qotsa.exception;
/**
* Exception to throw when any parameter is invalid.
*
* @author Francisco
*/
public class InvalidParameter extends Exception {
private static final String defaultMessage = "Invalid Parameter";
/**
* Creates a new instance of NegativeValueException
* @param message Message to print in the stack.
*/
public InvalidParameter(String message) {
super(message);
}
/**
* Creates a new instance of NegativeValueException with the default message
*/
public InvalidParameter() {
super(defaultMessage);
}
}

View File

@@ -1,20 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
@(#)package.html 1.60 98/01/27
-->
</head>
<body bgcolor="white">
Package containing the Exception Class used in the WinampController Class.
<h2>Package Specification</h2>
<!-- Put @see and @since tags down here. -->
</body>
</html>

View File

@@ -1,227 +0,0 @@
/*
* JNIWinamp.java
*
* Created on 23 de Abril de 2007, 20:41
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.qotsa.jni.controller;
import java.io.IOException;
/**
*
* @author Francisco Guimar<61>es
*/
final class JNIWinamp {
static {
System.loadLibrary("wpcom");
}
/**
* Verify if Winamp is started
* and if not started, starts it
* @return True - if successful run Winamp
* False - if not successful run Winamp
*/
protected static native boolean run() throws UnsatisfiedLinkError;
/*
* Exit Winamp
* @return True - if successful exit
* False - if not successful exit
*/
protected static native boolean exit() throws UnsatisfiedLinkError;
/**
* Play Winamp.
*
*/
protected static native boolean play() throws UnsatisfiedLinkError;
/**
* Stop Winamp.
*
*/
protected static native boolean stop() throws UnsatisfiedLinkError;
/**
* Resume Winamp.
*
*/
protected static native boolean resume() throws UnsatisfiedLinkError;
/**
* Pause Winamp.
*
*/
protected static native boolean pause() throws UnsatisfiedLinkError;
/**
* Go to Previous Track.
*
*/
protected static native boolean previousTrack() throws UnsatisfiedLinkError;
/**
* Go to Next Track.
*
*/
protected static native boolean nextTrack() throws UnsatisfiedLinkError;
/**
* Fowards 5 seconds on the current song.
*
*/
protected static native boolean fwd5Secs() throws UnsatisfiedLinkError;
/**
* Rewinds 5 seconds on the current song.
*
*/
protected static native boolean rew5Secs() throws UnsatisfiedLinkError;
/**
* Increase Volume.
*
*/
protected static native boolean increaseVolume() throws UnsatisfiedLinkError;
/**
* Decrease Volume.
*
*/
protected static native boolean decreaseVolume() throws UnsatisfiedLinkError;
/**
* Increase Volume.
* @param percent Percent to Increase.
*/
protected static native boolean increaseVolumePercent(int percent) throws UnsatisfiedLinkError;
/**
* Decrease Volume.
* @param percent Percent to Decrease.
*/
protected static native boolean decreaseVolumePercent(int percent) throws UnsatisfiedLinkError;
/**
* Adjust Volume
* @param pos Position to Set Volume between 0 and 99.
*/
protected static native boolean setVolume(int pos) throws UnsatisfiedLinkError;
/**
* Get Volume.
* @return volume.
*/
protected static native int getVolume() throws UnsatisfiedLinkError;
/**
* Go to a Specified Position in the List.
* @param pos Position.
*/
protected static native boolean setPlaylistPosition(int pos) throws UnsatisfiedLinkError;
/**
* Clear List.
*
*/
protected static native boolean clearPlayList() throws UnsatisfiedLinkError;
/**
* Refresh List<73>s Cache.
*
*/
protected static native boolean refreshPlayListCache() throws UnsatisfiedLinkError;
/**
* Return the PlayListLength.
* @return List Length.
*/
protected static native int getPlayListLength() throws UnsatisfiedLinkError;
/**
* Write a Playlist in <winampdir>\\Winamp.m3u.
* @return List Position.
*/
protected static native int writePlayListToFile() throws UnsatisfiedLinkError;
/**
* Verify if Shuffle is On.
* @return True - On throws UnsatisfiedLinkError; False - Off.
*/
protected static native int isShuffleStatusOn() throws UnsatisfiedLinkError;
/**
* Verify if Repeat is On.
* @return True - On throws UnsatisfiedLinkError; False - Off.
*/
protected static native int isRepeatStatusOn() throws UnsatisfiedLinkError;
/**
* Turn on Repeat.
* @param True - Turn on Repeat throws UnsatisfiedLinkError; False - Turn off Repeat.
*/
protected static native boolean setRepeatStatusOn(boolean mode) throws UnsatisfiedLinkError;
/**
* Turn on Shuffle.
* @param True - Turn on Shuffle throws UnsatisfiedLinkError; False - Turn off Shuffle.
*/
protected static native boolean setShuffleStatusOn(boolean mode) throws UnsatisfiedLinkError;
/**
* Append a File in the List
* @param filename FileName to Append.
*/
protected static native boolean appendToPlayList(String filename) throws UnsatisfiedLinkError;
/**
* Get Winamp Status.
* @return STOPPED - Stop
* PLAYING - play
* PAUSED - Paused
*/
protected static native int getStatus() throws UnsatisfiedLinkError;
/**
* Get Current List Pos.
* @return Current List Position.
*/
protected static native int getListPos() throws UnsatisfiedLinkError;
/**
* Get Current Track Title
* @return Current Track Title
*/
protected static native String getTitle() throws UnsatisfiedLinkError;
/**
* Get Track FileName in List<73>s index.
* @param index Track Index in the Current PlayList
* @return Current Track FileName
*/
protected static native String getFileNameInList(int index) throws UnsatisfiedLinkError;
/**
* Get Song Time
* @param mode CURRENTTIME - Currently Time in Milliseconds
* TIMELENGHT - Song Time Length in seconds
* @return Song Time in Seconds
*/
protected static native int getTime(int mode) throws UnsatisfiedLinkError;
/**
* Get File Name Playing In Winamp.
*
* @return Current File Name.
*/
protected static native String getFileNamePlaying() throws UnsatisfiedLinkError;
}

View File

@@ -1,592 +0,0 @@
/*
* WinampController.java
*
* Created on 9 de Outubro de 2007, 14:06
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
/**
* Package containing the Controller Class to communicate with Winamp.
*
* @author Francisco Guimar<61>es
*/
package com.qotsa.jni.controller;
import com.qotsa.exception.InvalidHandle;
import com.qotsa.exception.InvalidParameter;
import java.io.File;
/**
* This class is a wrapper to call JNI functions
* to send Message to Winamp Window.
*
* @author Francisco Guimar<61>es
*
*
*/
public class WinampController {
/**
* Constant used as return in getTime()
* Value = -1
*/
public static final int ISNOTPLAYING = -1;
/**
* Constant used as parameter in getTime() method
* Value = 0
*/
public static final int CURRENTTIME = 0;
/**
* Constant used as parameter in getTime() method
* Value = 1
*/
public static final int TIMELENGTH = 1;
/**
* Constant used as return in getStatus() method
* Value = 0
*/
public static final int STOPPED = 0;
/**
* Constant used as return in getStatus() method
* Value = 1
*/
public static final int PLAYING = 1;
/**
* Constant used as return in getStatus() method
* Value = 3
*/
public static final int PAUSED = 3;
/**
* Verify if Winamp is started
* and if not started, starts it.
*
* @throws java.lang.Exception When the key HKEY_LOCAL_MACHINE\Software\Clients\Media\Winamp\shell\open\command
* is not found in the register. This key is used to find Winamp Directory installation to execute it.
*/
public static void run() throws Exception{
if (!JNIWinamp.run())
throw new Exception("Unable to run Winamp. Verify if it is properly installed");
}
/**
* Exit Winamp.
*
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void exit() throws InvalidHandle {
if (!JNIWinamp.exit())
throw new InvalidHandle();
}
/**
* Play current file in Winamp.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void play() throws InvalidHandle {
if (!JNIWinamp.play())
throw new InvalidHandle();
}
/**
* Stop current file in Winamp.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void stop() throws InvalidHandle {
if (!JNIWinamp.stop())
throw new InvalidHandle();
}
/**
* Resume current file in Winamp.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void resume() throws InvalidHandle {
if (!JNIWinamp.resume())
throw new InvalidHandle();
}
/**
* Pause Winamp.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void pause() throws InvalidHandle {
if (!JNIWinamp.pause())
throw new InvalidHandle();
}
/**
*
* Go to Previous Track in the play list.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void previousTrack() throws InvalidHandle {
if (!JNIWinamp.previousTrack())
throw new InvalidHandle();
}
/**
* Go to Next Track in the play list.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void nextTrack() throws InvalidHandle {
if (!JNIWinamp.nextTrack())
throw new InvalidHandle();
}
/**
* Fowards 5 seconds on the current song.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void fwd5Secs() throws InvalidHandle {
if (!JNIWinamp.fwd5Secs())
throw new InvalidHandle();
}
/**
* Rewinds 5 seconds on the current song.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void rew5Secs() throws InvalidHandle {
if (!JNIWinamp.rew5Secs())
throw new InvalidHandle();
}
/**
* Increase Volume a little bit.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void increaseVolume() throws InvalidHandle {
if (!JNIWinamp.increaseVolume())
throw new InvalidHandle();
}
/**
* Decrease Volume a little bit.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void decreaseVolume() throws InvalidHandle {
if (!JNIWinamp.decreaseVolume())
throw new InvalidHandle();
}
/**
* Increase Volume.
*
* @param percent Percent to Increase Volume.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If percent not between 0 and 100
*/
public static void increaseVolumePercent (int percent) throws InvalidHandle, InvalidParameter {
if ( (percent < 0) || (percent > 100) )
throw new InvalidParameter("percent<EFBFBD>s value must be between 0 and 100");
if (!JNIWinamp.increaseVolumePercent(percent))
throw new InvalidHandle();
}
/**
* Decrease Volume.
*
* @param percent Percent to Decrease Volume.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If percent not between 0 and 100
*/
public static void decreaseVolumePercent(int percent) throws InvalidHandle, InvalidParameter {
if ( (percent < 0) || (percent > 100) )
throw new InvalidParameter("percent<EFBFBD>s value must be between 0 and 100");
if (!JNIWinamp.decreaseVolumePercent(percent))
throw new InvalidHandle();
}
/**
* Adjust Volume.
* Note that the pos must be between 0(0%) and 255 (100%).
*
* @param pos Position to Set Volume.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If pos not between 0 and 255
*/
public static void setVolume(int pos) throws InvalidHandle, InvalidParameter {
if ( (pos < 0) || (pos > 255) )
throw new InvalidParameter("pos value must be between 0 and 255");
if (!JNIWinamp.setVolume(pos))
throw new InvalidHandle();
}
/**
* Get Volume.
* @return The volume which is a number between 0 (0%) and 255(100%)
* @throws com.qotsa.exception.InvalidHandle
*/
public static int getVolume() throws InvalidHandle {
int volume = JNIWinamp.getVolume();
if (volume == -1)
throw new InvalidHandle();
return volume;
}
/**
* Get Volume Percent.
* @return Volume percent.
* @throws com.qotsa.exception.InvalidHandle
*/
public static int getVolumePercent() throws InvalidHandle {
int volume = getVolume();
int percent = (volume * 100) / 255;
return percent;
}
/**
* Restarts Winamp.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws java.lang.Exception When failed to restart Winamp.
*/
public static void restart() throws InvalidHandle, Exception {
exit();
run();
}
/**
* Go to a Specified Position in the List. This method doesn<73>t play.
* Just set list position. If you wanna play call play() after set position.
* Parameter pos is Zero-based index.
* @param pos Position.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If pos is negative or greater than List Length.
*/
public static void setPlaylistPosition(int pos) throws InvalidHandle, InvalidParameter {
int listLength = getPlayListLength();
if ( (pos < 0) || ( (pos + 1) > listLength) )
throw new InvalidParameter("Position is invalid in the list.");
if (!JNIWinamp.setPlaylistPosition(pos))
throw new InvalidHandle();
}
/**
* Clear Winamp's internal playlist.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void clearPlayList() throws InvalidHandle {
if (!JNIWinamp.clearPlayList())
throw new InvalidHandle();
}
/**
* Flush the playlist cache buffer.
* Call this if you want it to go refetch titles for tracks in the list.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void refreshPlayListCache() throws InvalidHandle{
if (!JNIWinamp.refreshPlayListCache())
throw new InvalidHandle();
}
/**
* Return the PlayListLength.
*
* @return List Length.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static int getPlayListLength() throws InvalidHandle {
int length = JNIWinamp.getPlayListLength();
if (length == -1)
throw new InvalidHandle();
return length;
}
/**
* Write a Playlist in winampDirInstallation\\Winamp.m3u.
* This is default Winamp IPC Default. If you wanna change this,
* just rename the file you<6F>ve created.
*
* @return Current List Position.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static int writePlayListToFile() throws InvalidHandle {
int playListPos = JNIWinamp.writePlayListToFile();
if (playListPos == -1)
throw new InvalidHandle();
return playListPos;
}
/**
* Verify if Shuffle is On.
*
* @return True - On ; False - Off.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static boolean isShuffleStatusOn() throws InvalidHandle {
int status = JNIWinamp.isShuffleStatusOn();
if (status == -1)
throw new InvalidHandle();
return (status == 1 ? true : false);
}
/**
* Verify if Repeat is On.
*
* @return True - On ; False - Off.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static boolean isRepeatStatusOn() throws InvalidHandle {
int status = JNIWinamp.isRepeatStatusOn();
if (status == -1)
throw new InvalidHandle();
return (status == 1 ? true : false);
}
/**
* Turn on Repeat.
*
* @param mode True - Turn on Repeat ; False - Turn off Repeat.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void setRepeatStatusOn(boolean mode) throws InvalidHandle {
if (!JNIWinamp.setRepeatStatusOn(mode))
throw new InvalidHandle();
}
/**
* Turn on Shuffle.
*
* @param mode True - Turn on Shuffle ; False - Turn off Shuffle.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static void setShuffleStatusOn(boolean mode) throws InvalidHandle {
if (!JNIWinamp.setShuffleStatusOn(mode))
throw new InvalidHandle();
}
/**
* Append a File into the List.
*
* @param filename FileName to Append in the list.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If the filename is an invalid path.
*/
public static void appendToPlayList(String filename) throws InvalidHandle, InvalidParameter {
File file = new File(filename);
if (!file.exists())
throw new InvalidParameter("File doesn<73>t exists.");
if (!JNIWinamp.appendToPlayList(filename))
throw new InvalidHandle();
}
/**
* Get Winamp Status.
*
* @return STOPPED - Stop
* PLAYING - play
* PAUSED - Paused
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static int getStatus() throws InvalidHandle {
int status = JNIWinamp.getStatus();
if (status == -1)
throw new InvalidHandle();
return status;
}
/**
* Get Current List Pos.
*
* @return Current List Position.
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static int getListPos() throws InvalidHandle {
int pos = JNIWinamp.getListPos();
if (pos == -1)
throw new InvalidHandle();
return pos;
}
/**
* Get Current Track Title.
*
* @return Current Track Title
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
*/
public static String getTitle() throws InvalidHandle {
String title = JNIWinamp.getTitle();
if (title == null)
throw new InvalidHandle();
return title;
}
/**
* Get Current Track FileName.
* Parameter pos is Zero-based index.
*
* @return Current Track FileName
* @param pos Track Position in the Current PlayList
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter If pos is negative or greater than List Length
*/
public static String getFileNameInList(int pos) throws InvalidHandle, InvalidParameter {
int listLength = getPlayListLength();
if ( (pos < 0) || (pos > listLength) )
throw new InvalidParameter("Position is invalid in the list.");
String filename = JNIWinamp.getFileNameInList(pos);
if (filename == null)
throw new InvalidHandle();
return filename;
}
/**
* Get Song Time.
*
* @return Time Song (depends on Param mode) or
* ISNOTPLAYING if there is no info about time because it not starts to play.
* @param mode CURRENTTIME - Currently Time in Milliseconds
* TIMELENGHT - Song Time Length in seconds
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter if parameter is not CURRENTTIME or TIMELENGTH.
*/
public static int getTime(int mode) throws InvalidHandle, InvalidParameter {
if (mode != CURRENTTIME && mode != TIMELENGTH)
throw new InvalidParameter();
int time = JNIWinamp.getTime(mode);
if (time == -2)
throw new InvalidHandle();
return time;
}
/**
* Fowards n Tracks in Play List.
*
* @param n Number of Tracks to Foward
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter if n is negative or Zero.
*/
public static void fwdTracks(int n) throws InvalidParameter, InvalidHandle {
if (n <= 0)
throw new InvalidParameter("Value must be Positive");
int pos = getListPos();
int lengthList = getPlayListLength();
int newPos = pos + n;
if (newPos > lengthList ) {
setPlaylistPosition(lengthList);
play();
}
else {
setPlaylistPosition(newPos);
play();
}
}
/**
* Rewinds n Tracks in Play List.
*
* @param n Number of Tracks to Rewind
* @throws com.qotsa.exception.InvalidHandle When the Winamp Windows is not handle(in most case, it means that winamp is not running)
* @throws com.qotsa.exception.InvalidParameter if n is negative or Zero.
*/
public static void rewTracks(int n) throws InvalidParameter, InvalidHandle {
if (n <= 0)
throw new InvalidParameter("Value must be Positive");
int pos = getListPos();
int lengthList = getPlayListLength();
int newPos = pos - n;
if (newPos < 0 ) {
setPlaylistPosition(0);
play();
}
else {
setPlaylistPosition(newPos);
play();
}
}
/**
* Get File Name Playing In Winamp.
*
* @return Current File Name.
*/
public static String getFileNamePlaying() throws InvalidHandle {
String fileName = JNIWinamp.getFileNamePlaying();
if (fileName == null)
throw new InvalidHandle();
return fileName;
}
}

View File

@@ -1,20 +0,0 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
@(#)package.html 1.60 98/01/27
-->
</head>
<body bgcolor="white">
Package containing the Controller Class to communicate with Winamp.
<h2>Package Specification</h2>
<!-- Put @see and @since tags down here. -->
</body>
</html>

View File

@@ -1,479 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.activeX;
import com.jacob.com.Dispatch;
import com.jacob.com.JacobObject;
import com.jacob.com.Variant;
/**
* This class provides a higher level, more object like, wrapper for top of the
* Dispatch object. The Dispatch class's method essentially directly map to
* Microsoft C API including the first parameter that is almost always the
* target of the message. ActiveXComponent assumes the target of every message
* is the MS COM object behind the ActiveXComponent. This removes the need to
* pass the Dispatch object into every method.
* <p>
* It is really up to the developer as to whether they want to use the Dispatch
* interface or the ActiveXComponent interface.
* <p>
* This class simulates com.ms.activeX.ActiveXComponent only in the sense that
* it is used for creating Dispatch objects
*/
public class ActiveXComponent extends Dispatch {
/**
* Normally used to create a new connection to a microsoft application. The
* passed in parameter is the name of the program as registered in the
* registry. It can also be the object name.
* <p>
* This constructor causes a new Windows object of the requested type to be
* created. The windows CoCreate() function gets called to create the
* underlying windows object.
*
* <pre>
* new ActiveXComponent(&quot;ScriptControl&quot;);
* </pre>
*
* @param programId
*/
public ActiveXComponent(String programId) {
super(programId);
}
/**
* Creates an active X component that is built on top of the COM pointers
* held in the passed in dispatch. This widens the Dispatch object to pick
* up the ActiveXComponent API
*
* @param dispatchToBeWrapped
*/
public ActiveXComponent(Dispatch dispatchToBeWrapped) {
super(dispatchToBeWrapped);
}
/**
* only used by the factories
*
*/
private ActiveXComponent() {
super();
}
/**
* Probably was a cover for something else in the past. Should be
* deprecated.
*
* @return Now it actually returns this exact same object.
*/
public Dispatch getObject() {
return this;
}
/**
* Most code should use the standard ActiveXComponent(String) contructor and
* not this factory method. This method exists for applications that need
* special behavior. <B>Experimental in release 1.9.2.</B>
* <p>
* Factory that returns a Dispatch object wrapped around the result of a
* CoCreate() call. This differs from the standard constructor in that it
* throws no exceptions and returns null on failure.
* <p>
* This will fail for any prog id with a ":" in it.
*
* @param pRequestedProgramId
* @return Dispatch pointer to the COM object or null if couldn't create
*/
public static ActiveXComponent createNewInstance(String pRequestedProgramId) {
ActiveXComponent mCreatedDispatch = null;
try {
mCreatedDispatch = new ActiveXComponent();
mCreatedDispatch.coCreateInstance(pRequestedProgramId);
} catch (Exception e) {
mCreatedDispatch = null;
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("Unable to co-create instance of "
+ pRequestedProgramId);
}
}
return mCreatedDispatch;
}
/**
* Most code should use the standard ActiveXComponent(String) constructor
* and not this factory method. This method exists for applications that
* need special behavior. <B>Experimental in release 1.9.2.</B>
* <p>
* Factory that returns a Dispatch wrapped around the result of a
* getActiveObject() call. This differs from the standard constructor in
* that it throws no exceptions and returns null on failure.
* <p>
* This will fail for any prog id with a ":" in it
*
* @param pRequestedProgramId
* @return Dispatch pointer to a COM object or null if wasn't already
* running
*/
public static ActiveXComponent connectToActiveInstance(
String pRequestedProgramId) {
ActiveXComponent mCreatedDispatch = null;
try {
mCreatedDispatch = new ActiveXComponent();
mCreatedDispatch.getActiveInstance(pRequestedProgramId);
} catch (Exception e) {
mCreatedDispatch = null;
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("Unable to attach to running instance of "
+ pRequestedProgramId);
}
}
return mCreatedDispatch;
}
/**
* @see com.jacob.com.Dispatch#finalize()
*/
@Override
protected void finalize() {
super.finalize();
}
/*
* ============================================================
*
* start of instance based calls to the COM layer
* ===========================================================
*/
/**
* retrieves a property and returns it as a Variant
*
* @param propertyName
* @return variant value of property
*/
public Variant getProperty(String propertyName) {
return Dispatch.get(this, propertyName);
}
/**
* retrieves a property and returns it as an ActiveX component
*
* @param propertyName
* @return Dispatch representing the object under the property name
*/
public ActiveXComponent getPropertyAsComponent(String propertyName) {
return new ActiveXComponent(Dispatch.get(this, propertyName)
.toDispatch());
}
/**
* retrieves a property and returns it as a Boolean
*
* @param propertyName
* property we are looking up
* @return boolean value of property
*/
public boolean getPropertyAsBoolean(String propertyName) {
return Dispatch.get(this, propertyName).getBoolean();
}
/**
* retrieves a property and returns it as a byte
*
* @param propertyName
* property we are looking up
* @return byte value of property
*/
public byte getPropertyAsByte(String propertyName) {
return Dispatch.get(this, propertyName).getByte();
}
/**
* retrieves a property and returns it as a String
*
* @param propertyName
* @return String value of property
*/
public String getPropertyAsString(String propertyName) {
return Dispatch.get(this, propertyName).getString();
}
/**
* retrieves a property and returns it as a int
*
* @param propertyName
* @return the property value as an int
*/
public int getPropertyAsInt(String propertyName) {
return Dispatch.get(this, propertyName).getInt();
}
/**
* sets a property on this object
*
* @param propertyName
* property name
* @param arg
* variant value to be set
*/
public void setProperty(String propertyName, Variant arg) {
Dispatch.put(this, propertyName, arg);
}
/**
* sets a property on this object
*
* @param propertyName
* property name
* @param arg
* variant value to be set
*/
public void setProperty(String propertyName, Dispatch arg) {
Dispatch.put(this, propertyName, arg);
}
/**
* sets a property to be the value of the string
*
* @param propertyName
* @param propertyValue
*/
public void setProperty(String propertyName, String propertyValue) {
this.setProperty(propertyName, new Variant(propertyValue));
}
/**
* sets a property as a boolean value
*
* @param propertyName
* @param propValue
* the boolean value we want the prop set to
*/
public void setProperty(String propertyName, boolean propValue) {
this.setProperty(propertyName, new Variant(propValue));
}
/**
* sets a property as a boolean value
*
* @param propertyName
* @param propValue
* the boolean value we want the prop set to
*/
public void setProperty(String propertyName, byte propValue) {
this.setProperty(propertyName, new Variant(propValue));
}
/**
* sets the property as an int value
*
* @param propertyName
* @param propValue
* the int value we want the prop to be set to.
*/
public void setProperty(String propertyName, int propValue) {
this.setProperty(propertyName, new Variant(propValue));
}
/*-------------------------------------------------------
* Listener logging helpers
*-------------------------------------------------------
*/
/**
* This boolean determines if callback events should be logged
*/
public static boolean shouldLogEvents = false;
/**
* used by the doc and application listeners to get intelligent logging
*
* @param description
* event description
* @param args
* args passed in (variants)
*
*/
public void logCallbackEvent(String description, Variant[] args) {
String argString = "";
if (args != null && ActiveXComponent.shouldLogEvents) {
if (args.length > 0) {
argString += " args: ";
}
for (int i = 0; i < args.length; i++) {
short argType = args[i].getvt();
argString += ",[" + i + "]";
// break out the byref bits if they are on this
if ((argType & Variant.VariantByref) == Variant.VariantByref) {
// show the type and the fact that its byref
argString += "("
+ (args[i].getvt() & ~Variant.VariantByref) + "/"
+ Variant.VariantByref + ")";
} else {
// show the type
argString += "(" + argType + ")";
}
argString += "=";
if (argType == Variant.VariantDispatch) {
Dispatch foo = (args[i].getDispatch());
argString += foo;
} else if ((argType & Variant.VariantBoolean) == Variant.VariantBoolean) {
// do the boolean thing
if ((argType & Variant.VariantByref) == Variant.VariantByref) {
// boolean by ref
argString += args[i].getBooleanRef();
} else {
// boolean by value
argString += args[i].getBoolean();
}
} else if ((argType & Variant.VariantString) == Variant.VariantString) {
// do the string thing
if ((argType & Variant.VariantByref) == Variant.VariantByref) {
// string by ref
argString += args[i].getStringRef();
} else {
// string by value
argString += args[i].getString();
}
} else {
argString += args[i].toString();
}
}
System.out.println(description + argString);
}
}
/*
* ==============================================================
*
* covers for dispatch call methods
* =============================================================
*/
/**
* makes a dispatch call for the passed in action and no parameter
*
* @param callAction
* @return ActiveXComponent representing the results of the call
*/
public ActiveXComponent invokeGetComponent(String callAction) {
return new ActiveXComponent(invoke(callAction).toDispatch());
}
/**
* makes a dispatch call for the passed in action and single parameter
*
* @param callAction
* @param parameters
* @return ActiveXComponent representing the results of the call
*/
public ActiveXComponent invokeGetComponent(String callAction,
Variant... parameters) {
return new ActiveXComponent(invoke(callAction, parameters).toDispatch());
}
/**
* invokes a single parameter call on this dispatch that returns no value
*
* @param actionCommand
* @param parameter
* @return a Variant but that may be null for some calls
*/
public Variant invoke(String actionCommand, String parameter) {
return Dispatch.call(this, actionCommand, parameter);
}
/**
* makes a dispatch call to the passed in action with a single boolean
* parameter
*
* @param actionCommand
* @param parameter
* @return Variant result
*/
public Variant invoke(String actionCommand, boolean parameter) {
return Dispatch.call(this, actionCommand, new Variant(parameter));
}
/**
* makes a dispatch call to the passed in action with a single int parameter
*
* @param actionCommand
* @param parameter
* @return Variant result of the invoke (Dispatch.call)
*/
public Variant invoke(String actionCommand, int parameter) {
return Dispatch.call(this, actionCommand, new Variant(parameter));
}
/**
* makes a dispatch call to the passed in action with a string and integer
* parameter (this was put in for some application)
*
* @param actionCommand
* @param parameter1
* @param parameter2
* @return Variant result
*/
public Variant invoke(String actionCommand, String parameter1,
int parameter2) {
return Dispatch.call(this, actionCommand, parameter1, new Variant(
parameter2));
}
/**
* makes a dispatch call to the passed in action with two integer parameters
* (this was put in for some application)
*
* @param actionCommand
* @param parameter1
* @param parameter2
* @return a Variant but that may be null for some calls
*/
public Variant invoke(String actionCommand, int parameter1, int parameter2) {
return Dispatch.call(this, actionCommand, new Variant(parameter1),
new Variant(parameter2));
}
/**
* makes a dispatch call for the passed in action and no parameter
*
* @param callAction
* @return a Variant but that may be null for some calls
*/
public Variant invoke(String callAction) {
return Dispatch.call(this, callAction);
}
/**
* This is really a cover for call(String,Variant[]) that should be
* eliminated call with a variable number of args mainly used for quit.
*
* @param name
* @param args
* @return Variant returned by the invoke (Dispatch.callN)
*/
public Variant invoke(String name, Variant... args) {
return Dispatch.callN(this, name, args);
}
}

View File

@@ -1,106 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.activeX;
import com.jacob.com.Dispatch;
import com.jacob.com.DispatchEvents;
import com.jacob.com.InvocationProxy;
/**
* RELEASE 1.12 EXPERIMENTAL.
* <p>
* Use this exactly like the DispatchEvents class. This class plugs in an
* ActiveXInvocationProxy instead of an InvocationProxy. It is the
* ActiveXInvocationProxy that implements the reflection calls and invoke the
* found java event callbacks. See ActiveXInvocationProxy for details.
*
*
*/
public class ActiveXDispatchEvents extends DispatchEvents {
/**
* This is the most commonly used constructor.
* <p>
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
*
* @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks
* @param eventSink
* Java object that wants to receive the events
*/
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink) {
super(sourceOfEvent, eventSink, null);
}
/**
* None of the samples use this constructor.
* <p>
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
*
* @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks
* @param eventSink
* Java object that wants to receive the events
* @param progId
* ???
*/
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId) {
super(sourceOfEvent, eventSink, progId, null);
}
/**
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
*
* <pre>
* &gt;ActiveXDispatchEvents de =
* new ActiveXDispatchEvents(someDispatch,someEventHAndler,
* &quot;Excel.Application&quot;,
* &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;);
*
* @param sourceOfEvent Dispatch object who's MS app will generate callbacks
* @param eventSink Java object that wants to receive the events
* @param progId , mandatory if the typelib is specified
* @param typeLib The location of the typelib to use
*
*/
public ActiveXDispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId, String typeLib) {
super(sourceOfEvent, eventSink, progId, typeLib);
}
/*
* (non-Javadoc)
*
* @see com.jacob.com.DispatchEvents#getInvocationProxy(java.lang.Object)
*/
protected InvocationProxy getInvocationProxy(Object pTargetObject) {
InvocationProxy newProxy = new ActiveXInvocationProxy();
newProxy.setTarget(pTargetObject);
return newProxy;
}
}

View File

@@ -1,183 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.activeX;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.jacob.com.InvocationProxy;
import com.jacob.com.NotImplementedException;
import com.jacob.com.Variant;
/**
* RELEASE 1.12 EXPERIMENTAL.
* <p>
* This class that lets event handlers receive events with all java objects as
* parameters. The standard Jacob event methods all accept an array of Variant
* objects. When using this class, you can set up your event methods as regular
* java methods with the correct number of parameters of the correct java type.
* This does NOT work for any event that wishes to accept a call back and modify
* the calling parameters to tell windows what to do. An example is when an
* event lets the receiver cancel the action by setting a boolean flag to false.
* The java objects cannot be modified and their values will not be passed back
* into the originating Variants even if they could be modified.
* <p>
* This class acts as a proxy between the windows event callback mechanism and
* the Java classes that are looking for events. It assumes that all of the Java
* classes that are looking for events implement methods with the same names as
* the windows events and that the implemented methods native java objects of
* the type and order that match the windows documentation. The methods can
* return void or a Variant that will be returned to the calling layer. All
* Event methods that will be recognized by InvocationProxyAllEvents have the
* signature
*
* <code> void eventMethodName(Object,Object...)</code> or
* <code> Object eventMethodName(Object,Object...)</code>
*/
public class ActiveXInvocationProxy extends InvocationProxy {
/*
* (non-Javadoc)
*
* @see com.jacob.com.InvocationProxy#invoke(java.lang.String,
* com.jacob.com.Variant[])
*/
@SuppressWarnings("unchecked")
public Variant invoke(String methodName, Variant targetParameters[]) {
Variant mVariantToBeReturned = null;
if (mTargetObject == null) {
// structured programming guidlines say this return should not be up
// here
return null;
}
Class targetClass = mTargetObject.getClass();
if (methodName == null) {
throw new IllegalArgumentException(
"InvocationProxy: missing method name");
}
if (targetParameters == null) {
throw new IllegalArgumentException(
"InvocationProxy: missing Variant parameters");
}
try {
Method targetMethod;
Object parametersAsJavaObjects[] = getParametersAsJavaObjects(targetParameters);
Class parametersAsJavaClasses[] = getParametersAsJavaClasses(parametersAsJavaObjects);
targetMethod = targetClass.getMethod(methodName,
parametersAsJavaClasses);
if (targetMethod != null) {
// protected classes can't be invoked against even if they
// let you grab the method. you could do
// targetMethod.setAccessible(true);
// but that should be stopped by the security manager
Object mReturnedByInvocation = null;
mReturnedByInvocation = targetMethod.invoke(mTargetObject,
parametersAsJavaObjects);
if (mReturnedByInvocation == null) {
mVariantToBeReturned = null;
} else if (!(mReturnedByInvocation instanceof Variant)) {
mVariantToBeReturned = new Variant(mReturnedByInvocation);
} else {
mVariantToBeReturned = (Variant) mReturnedByInvocation;
}
}
} catch (SecurityException e) {
// what causes this exception?
e.printStackTrace();
} catch (NoSuchMethodException e) {
// this happens whenever the listener doesn't implement all the
// methods
} catch (IllegalArgumentException e) {
// we can throw these inside the catch block so need to re-throw it
Exception oneWeShouldToss = new IllegalArgumentException(
"Unable to map parameters for method " + methodName + ": "
+ e.toString());
oneWeShouldToss.printStackTrace();
} catch (IllegalAccessException e) {
// can't access the method on the target instance for some reason
e.printStackTrace();
} catch (InvocationTargetException e) {
// invocation of target method failed
e.printStackTrace();
}
return mVariantToBeReturned;
}
/**
* creates a method signature compatible array of classes from an array of
* parameters
*
* @param parametersAsJavaObjects
* @return
*/
@SuppressWarnings("unchecked")
private Class[] getParametersAsJavaClasses(Object[] parametersAsJavaObjects) {
if (parametersAsJavaObjects == null) {
throw new IllegalArgumentException(
"This only works with an array of parameters");
}
int numParameters = parametersAsJavaObjects.length;
Class parametersAsJavaClasses[] = new Class[numParameters];
for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) {
Object oneParameterObject = parametersAsJavaObjects[parameterIndex];
if (oneParameterObject == null) {
parametersAsJavaClasses[parameterIndex] = null;
} else {
Class oneParameterClass = oneParameterObject.getClass();
parametersAsJavaClasses[parameterIndex] = oneParameterClass;
}
}
return parametersAsJavaClasses;
}
/**
* converts an array of Variants to their associated Java types
*
* @param targetParameters
* @return
*/
private Object[] getParametersAsJavaObjects(Variant[] targetParameters) {
if (targetParameters == null) {
throw new IllegalArgumentException(
"This only works with an array of parameters");
}
int numParameters = targetParameters.length;
Object parametersAsJavaObjects[] = new Object[numParameters];
for (int parameterIndex = 0; parameterIndex < numParameters; parameterIndex++) {
Variant oneParameterObject = targetParameters[parameterIndex];
if (oneParameterObject == null) {
parametersAsJavaObjects[parameterIndex] = null;
} else {
try {
parametersAsJavaObjects[parameterIndex] = oneParameterObject
.toJavaObject();
} catch (NotImplementedException nie) {
throw new IllegalArgumentException(
"Can't convert parameter " + parameterIndex
+ " type " + oneParameterObject.getvt()
+ " to java object: " + nie.getMessage());
}
}
}
return parametersAsJavaObjects;
}
}

View File

@@ -1,141 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* Standard exception thrown by com jni code when there is a problem
*/
public abstract class ComException extends JacobException {
/**
* COM code initializes this filed with an appropriate return code that was
* returned by the underlying com code
*/
protected int hr;
/**
* No documentation is available at this time. Someone should document this
* field
*/
protected int m_helpContext;
/**
* No documentation is available at this time. Someone should document this
* field
*/
protected String m_helpFile;
/**
* No documentation is available at this time. Someone should document this
* field
*/
protected String m_source;
/**
* constructor
*
*/
public ComException() {
super();
}
/**
* constructor with error code?
*
* @param newHr ??
*/
public ComException(int newHr) {
super();
this.hr = newHr;
}
/**
* @param newHr
* @param description
*/
public ComException(int newHr, String description) {
super(description);
this.hr = newHr;
}
/**
* @param newHr
* @param source
* @param helpFile
* @param helpContext
*/
public ComException(int newHr, String source, String helpFile,
int helpContext) {
super();
this.hr = newHr;
m_source = source;
m_helpFile = helpFile;
m_helpContext = helpContext;
}
/**
* @param newHr
* @param description
* @param source
* @param helpFile
* @param helpContext
*/
public ComException(int newHr, String description, String source,
String helpFile, int helpContext) {
super(description);
this.hr = newHr;
m_source = source;
m_helpFile = helpFile;
m_helpContext = helpContext;
}
/**
* @param description
*/
public ComException(String description) {
super(description);
}
/**
* @return int representation of the help context
*/
// Methods
public int getHelpContext() {
return m_helpContext;
}
/**
* @return String ??? help file
*/
public String getHelpFile() {
return m_helpFile;
}
/**
* @return int hr result ??
*/
public int getHResult() {
return hr;
}
/**
* @return String source ??
*/
public String getSource() {
return m_source;
}
}

View File

@@ -1,88 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* COM Fail Exception class raised when there is a problem
*/
public class ComFailException extends ComException {
/**
* eclipse generated to get rid of a wanring
*/
private static final long serialVersionUID = -266047261992987700L;
/**
* Constructor
*
* @param hrNew
*/
public ComFailException(int hrNew) {
super(hrNew);
}
/**
* Constructor
*
* @param hrNew
* @param message
*/
public ComFailException(int hrNew, String message) {
super(hrNew, message);
}
/**
* @param hrNew
* @param source
* @param helpFile
* @param helpContext
*/
public ComFailException(int hrNew, String source, String helpFile,
int helpContext) {
super(hrNew, source, helpFile, helpContext);
}
/**
* Constructor
*
* @param hrNew
* @param description
* @param source
* @param helpFile
* @param helpContext
*/
public ComFailException(int hrNew, String description, String source,
String helpFile, int helpContext) {
super(hrNew, description, source, helpFile, helpContext);
}
/**
* No argument Constructor
*/
public ComFailException() {
super();
}
/**
* @param message
*/
public ComFailException(String message) {
super(message);
}
}

View File

@@ -1,169 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* Represents a COM level thread This is an abstract class because all the
* methods are static and no instances are ever created.
*/
public abstract class ComThread {
private static final int MTA = 0x0;
private static final int STA = 0x2;
/**
* Comment for <code>haveSTA</code>
*/
public static boolean haveSTA = false;
/**
* Comment for <code>mainSTA</code>
*/
public static MainSTA mainSTA = null;
/**
* Initialize the current java thread to be part of the Multi-threaded COM
* Apartment
*/
public static synchronized void InitMTA() {
InitMTA(false);
}
/**
* Initialize the current java thread to be an STA
*/
public static synchronized void InitSTA() {
InitSTA(false);
}
/**
* Initialize the current java thread to be part of the Multi-threaded COM
* Apartment, if createMainSTA is true, create a separate MainSTA thread
* that will house all Apartment Threaded components
*
* @param createMainSTA
*/
public static synchronized void InitMTA(boolean createMainSTA) {
Init(createMainSTA, MTA);
}
/**
* Initialize the current java thread to be an STA COM Apartment, if
* createMainSTA is true, create a separate MainSTA thread that will house
* all Apartment Threaded components
*
* @param createMainSTA
*/
public static synchronized void InitSTA(boolean createMainSTA) {
Init(createMainSTA, STA);
}
/**
*
*/
public static synchronized void startMainSTA() {
mainSTA = new MainSTA();
haveSTA = true;
}
/**
*
*/
public static synchronized void quitMainSTA() {
if (mainSTA != null)
mainSTA.quit();
}
/**
* Initialize the current java thread to be part of the MTA/STA COM
* Apartment
*
* @param createMainSTA
* @param mode
*/
public static synchronized void Init(boolean createMainSTA, int mode) {
if (createMainSTA && !haveSTA) {
// if the current thread is going to be in the MTA and there
// is no STA thread yet, then create a main STA thread
// to avoid COM creating its own
startMainSTA();
}
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before Init: " + mode);
}
doCoInitialize(mode);
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after Init: " + mode);
}
ROT.addThread();
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after ROT.addThread: " + mode);
}
}
/**
* Call CoUninitialize to release this java thread from COM
*/
public static synchronized void Release() {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before clearObjects");
}
ROT.clearObjects();
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: before UnInit");
}
doCoUninitialize();
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ComThread: after UnInit");
}
}
/**
* @deprecated the java model leave the responsibility of clearing up
* objects to the Garbage Collector. Our programming model
* should not require that the user specifically remove object
* from the thread.
*
* This will remove an object from the ROT
* @param o
*/
@Deprecated
public static synchronized void RemoveObject(JacobObject o) {
ROT.removeObject(o);
}
/**
* @param threadModel
*/
public static native void doCoInitialize(int threadModel);
/**
*
*/
public static native void doCoUninitialize();
/**
* load the Jacob DLL. We do this in case COMThread is called before any
* other reference to one of the JacboObject subclasses is made.
*/
static {
LibraryLoader.loadJacobLibrary();
}
}

View File

@@ -1,91 +0,0 @@
package com.jacob.com;
/**
* Most COM bridges use java.lang.Long as their Java data type for COM Currency
* data. This is because COM currency is a 64 bit number where the last 4 digits
* represent the milli-cents. We wanted to support 64 bit Long values for x64
* platforms so that meant we wanted to map Java.LONG to COM.LONG even though it
* only works for 64 bit platforms. The end result was we needed a new
* representation for Money so we have this.
* <p>
* In the future, this should convert to and from BigDecimal or Double
*/
public class Currency {
Long embeddedValue = null;
/**
* constructor that takes a long already in COM representation
*
* @param newValue
*/
public Currency(long newValue) {
embeddedValue = new Long(newValue);
}
/**
* constructor that takes a String already in COM representation
*
* @param newValue
*/
public Currency(String newValue) {
embeddedValue = new Long(newValue);
}
/**
*
* @return the currency as a primitive long
*/
public long longValue() {
return embeddedValue.longValue();
}
/**
* getter to the inner storage so that cmpareTo can work
*
* @return the embedded long value
*/
protected Long getLongValue() {
return embeddedValue;
}
/**
* compares the values of two currencies
*
* @param anotherCurrency
* @return the usual compareTo results
*/
public int compareTo(Currency anotherCurrency) {
return embeddedValue.compareTo(anotherCurrency.getLongValue());
}
/**
* standard comparison
*
* @param o
* must be Currency or Long
* @return the usual compareTo results
*/
public int compareTo(Object o) {
if (o instanceof Currency) {
return compareTo((Currency) o);
} else if (o instanceof Long) {
return embeddedValue.compareTo((Long) o);
} else
throw new IllegalArgumentException(
"Can only compare to Long and Currency not "
+ o.getClass().getName());
}
/**
* {@inheritDoc}
*/
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (compareTo(o) == 0) {
return true;
} else {
return false;
}
}
}

View File

@@ -1,105 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
import java.util.Calendar;
import java.util.Date;
/**
* java / windows date conversion utilities
*
* @author joe
*
*/
public class DateUtilities {
/**
* converts a windows time to a Java Date Object
*
* @param comTime
* @return Date object representing the windows time as specified in comTime
*/
static public Date convertWindowsTimeToDate(double comTime) {
return new Date(convertWindowsTimeToMilliseconds(comTime));
}
/**
* Convert a COM time from functions Date(), Time(), Now() to a Java time
* (milliseconds). Visual Basic time values are based to 30.12.1899, Java
* time values are based to 1.1.1970 (= 0 milliseconds). The difference is
* added to the Visual Basic value to get the corresponding Java value. The
* Visual Basic double value reads: <day count delta since 30.12.1899>.<1
* day percentage fraction>, e.g. "38100.6453" means: 38100 days since
* 30.12.1899 plus (24 hours * 0.6453). Example usage:
* <code>Date javaDate = new Date(toMilliseconds (vbDate));</code>.
*
* @param comTime
* COM time.
* @return Java time.
*/
static public long convertWindowsTimeToMilliseconds(double comTime) {
long result = 0;
// code from jacobgen:
comTime = comTime - 25569D;
Calendar cal = Calendar.getInstance();
result = Math.round(86400000L * comTime)
- cal.get(Calendar.ZONE_OFFSET);
cal.setTime(new Date(result));
result -= cal.get(Calendar.DST_OFFSET);
return result;
}// convertWindowsTimeToMilliseconds()
/**
* converts a java date to a windows time object (is this timezone safe?)
*
* @param javaDate
* the java date to be converted to windows time
* @return the double representing the date in a form windows understands
*/
static public double convertDateToWindowsTime(Date javaDate) {
if (javaDate == null) {
throw new IllegalArgumentException(
"cannot convert null to windows time");
}
return convertMillisecondsToWindowsTime(javaDate.getTime());
}
/**
* Convert a Java time to a COM time.
*
* @param milliseconds
* Java time.
* @return COM time.
*/
static public double convertMillisecondsToWindowsTime(long milliseconds) {
double result = 0.0;
// code from jacobgen:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milliseconds);
milliseconds += (cal.get(Calendar.ZONE_OFFSET) + cal
.get(Calendar.DST_OFFSET)); // add GMT offset
result = (milliseconds / 86400000D) + 25569D;
return result;
}// convertMillisecondsToWindowsTime()
}

View File

@@ -1,872 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project. All rights reserved. Originator: Dan Adler
* (http://danadler.com). Get more information about JACOB at
* http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
package com.jacob.com;
/**
* Object represents MS level dispatch object. Each instance of this points at
* some data structure on the MS windows side.
*
*
* <p>
* You're going to live here a lot
*/
public class Dispatch extends JacobObject {
/**
* Used to set the locale in a call. The user locale is another option
*/
public static final int LOCALE_SYSTEM_DEFAULT = 2048;
/** used by callN() and callSubN() */
public static final int Method = 1;
/** used by callN() and callSubN() */
public static final int Get = 2;
/** used by put() */
public static final int Put = 4;
/** not used, probably intended for putRef() */
public static final int PutRef = 8;
/**
* One of legal values for GetDispId. Not used in this layer and probably
* not needed.
*/
public static final int fdexNameCaseSensitive = 1;
/**
* This is public because Dispatch.cpp knows its name and accesses it
* directly to get the dispatch id. You really can't rename it or make it
* private
*/
public int m_pDispatch;
/** program Id passed in by ActiveX components in their constructor */
private String programId = null;
private static int NOT_ATTACHED = 0;
/**
* Dummy empty array used one doesn't have to be created on every invocation
*/
private final static Object[] NO_OBJECT_ARGS = new Object[0];
/**
* Dummy empty array used one doesn't have to be created on every invocation
*/
private final static Variant[] NO_VARIANT_ARGS = new Variant[0];
/**
* Dummy empty array used one doesn't have to be created on every invocation
*/
private final static int[] NO_INT_ARGS = new int[0];
/**
* zero argument constructor that sets the dispatch pointer to 0 This is the
* only way to create a Dispatch without a value in the pointer field.
*/
public Dispatch() {
m_pDispatch = NOT_ATTACHED;
}
/**
* This constructor calls createInstance with progid. This is the
* constructor used by the ActiveXComponent or by programs that don't like
* the activeX interface but wish to create new connections to windows
* programs.
* <p>
* This constructor always creates a new windows/program object because it
* is based on the CoCreate() windows function.
* <p>
*
* @param requestedProgramId
* @throws IllegalArgumentException
* if null is passed in as the program id
* <p>
*/
public Dispatch(String requestedProgramId) {
programId = requestedProgramId;
if (programId != null && !"".equals(programId)) {
createInstanceNative(requestedProgramId);
} else {
throw new IllegalArgumentException(
"Dispatch(String) does not accept null or an empty string as a parameter");
}
}
/**
* native call createInstance only used by the constructor with the same
* parm type. This probably should be private. It is the wrapper for the
* Windows CoCreate() call
* <P>
* This ends up calling CoCreate down in the JNI layer
* <p>
* The behavior is different if a ":" character exists in the progId. In
* that case CoGetObject and CreateInstance (someone needs to describe this
* better)
*
* @param progid
*/
private native void createInstanceNative(String progid);
/**
* native call getActiveInstance only used by the constructor with the same
* parm type. This probably should be private. It is the wrapper for the
* Windows GetActiveObject() call
* <P>
* This ends up calling GetActiveObject down in the JNI layer
* <p>
* This does not have the special behavior for program ids with ":" in them
* that createInstance has.
*
* @param progid
*/
private native void getActiveInstanceNative(String progid);
/**
* Wrapper around the native method
*
* @param pProgramIdentifier
* name of the program you wish to connect to
*/
protected void getActiveInstance(String pProgramIdentifier) {
if (pProgramIdentifier == null || "".equals(pProgramIdentifier)) {
throw new IllegalArgumentException("program id is required");
}
this.programId = pProgramIdentifier;
getActiveInstanceNative(pProgramIdentifier);
}
/**
* native call coCreateInstance only used by the constructor with the same
* parm type. This probably should be private. It is the wrapper for the
* Windows CoCreate() call
* <P>
* This ends up calling CoCreate down in the JNI layer
* <p>
* This does not have the special behavior for program ids with ":" in them
* that createInstance has.
*
* @param progid
*/
private native void coCreateInstanceNative(String progid);
/**
* Wrapper around the native method
*
* @param pProgramIdentifier
*/
protected void coCreateInstance(String pProgramIdentifier) {
if (pProgramIdentifier == null || "".equals(pProgramIdentifier)) {
throw new IllegalArgumentException("program id is required");
}
this.programId = pProgramIdentifier;
coCreateInstanceNative(pProgramIdentifier);
}
/**
* Return a different interface by IID string.
* <p>
* Once you have a Dispatch object, you can navigate to the other interfaces
* of a COM object by calling QueryInterafce. The argument is an IID string
* in the format: "{9BF24410-B2E0-11D4-A695-00104BFF3241}". You typically
* get this string from the idl file (it's called uuid in there). Any
* interface you try to use must be derived from IDispatch. T The atl
* example uses this.
* <p>
* The Dispatch instance resulting from this query is instanciated in the
* JNI code.
*
* @param iid
* @return Dispatch a disptach that matches ??
*/
public native Dispatch QueryInterface(String iid);
/**
* Constructor that only gets called from JNI QueryInterface calls JNI code
* that looks up the object for the key passed in. The JNI CODE then creates
* a new dispatch object using this constructor
*
* @param pDisp
*/
protected Dispatch(int pDisp) {
m_pDispatch = pDisp;
}
/**
* Constructor to be used by subclass that want to swap themselves in for
* the default Dispatch class. Usually you will have a class like
* WordDocument that is a subclass of Dispatch and it will have a
* constructor public WordDocument(Dispatch). That constructor should just
* call this constructor as super(Dispatch)
*
* @param dispatchToBeDisplaced
*/
public Dispatch(Dispatch dispatchToBeDisplaced) {
// TAKE OVER THE IDispatch POINTER
this.m_pDispatch = dispatchToBeDisplaced.m_pDispatch;
// NULL OUT THE INPUT POINTER
dispatchToBeDisplaced.m_pDispatch = NOT_ATTACHED;
}
/**
* returns the program id if an activeX component created this otherwise it
* returns null. This was added to aid in debugging
*
* @return the program id an activeX component was created against
*/
public String getProgramId() {
return programId;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
@Override
protected void finalize() {
safeRelease();
}
/*
* (non-Javadoc)
*
* @see com.jacob.com.JacobObject#safeRelease()
*/
@Override
public void safeRelease() {
super.safeRelease();
if (isAttached()) {
release();
m_pDispatch = NOT_ATTACHED;
} else {
// looks like a double release
if (isDebugEnabled()) {
debug(this.getClass().getName() + ":" + this.hashCode()
+ " double release");
}
}
}
/**
*
* @return true if there is an underlying windows dispatch object
*/
protected boolean isAttached() {
if (m_pDispatch == NOT_ATTACHED) {
return false;
} else {
return true;
}
}
/**
* @param theOneInQuestion
* dispatch being tested
* @throws IllegalStateException
* if this dispatch isn't hooked up
* @throws IllegalArgumentException
* if null the dispatch under test is null
*/
private static void throwIfUnattachedDispatch(Dispatch theOneInQuestion) {
if (theOneInQuestion == null) {
throw new IllegalArgumentException(
"Can't pass in null Dispatch object");
} else if (theOneInQuestion.isAttached()) {
return;
} else {
throw new IllegalStateException(
"Dispatch not hooked to windows memory");
}
}
/**
* now private so only this object can access was: call this to explicitly
* release the com object before gc
*
*/
private native void release();
/**
* not implemented yet
*
* @param dispatchTarget
* @param name
* @param val
* @throws com.jacob.com.NotImplementedException
*/
public static void put_Casesensitive(Dispatch dispatchTarget, String name,
Object val) {
throw new NotImplementedException("not implemented yet");
}
/*
* ============================================================ start of the
* invokev section
* ===========================================================
*/
// eliminate _Guid arg
/**
* @param dispatchTarget
* @param name
* @param dispID
* @param lcid
* @param wFlags
* @param vArg
* @param uArgErr
*/
public static void invokeSubv(Dispatch dispatchTarget, String name,
int dispID, int lcid, int wFlags, Variant[] vArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokev(dispatchTarget, name, dispID, lcid, wFlags, vArg, uArgErr);
}
/**
* @param dispatchTarget
* @param name
* @param wFlags
* @param vArg
* @param uArgErr
*/
public static void invokeSubv(Dispatch dispatchTarget, String name,
int wFlags, Variant[] vArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokev(dispatchTarget, name, 0, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, vArg, uArgErr);
}
/**
* @param dispatchTarget
* @param dispID
* @param wFlags
* @param vArg
* @param uArgErr
*/
public static void invokeSubv(Dispatch dispatchTarget, int dispID,
int wFlags, Variant[] vArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokev(dispatchTarget, null, dispID, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, vArg, uArgErr);
}
/**
* not implemented yet
*
* @param dispatchTarget
* @param name
* @param values
* @return never returns anything because
* @throws com.jacob.com.NotImplementedException
*/
public static Variant callN_CaseSensitive(Dispatch dispatchTarget,
String name, Object[] values) {
throw new NotImplementedException("not implemented yet");
}
/**
* @param dispatchTarget
* @param name
* @param args
* an array of argument objects
*/
public static void callSubN(Dispatch dispatchTarget, String name,
Object... args) {
throwIfUnattachedDispatch(dispatchTarget);
invokeSubv(dispatchTarget, name, Dispatch.Method | Dispatch.Get,
VariantUtilities.objectsToVariants(args), new int[args.length]);
}
/**
* @param dispatchTarget
* @param dispID
* @param args
* an array of argument objects
*/
public static void callSubN(Dispatch dispatchTarget, int dispID,
Object... args) {
throwIfUnattachedDispatch(dispatchTarget);
invokeSubv(dispatchTarget, dispID, Dispatch.Method | Dispatch.Get,
VariantUtilities.objectsToVariants(args), new int[args.length]);
}
/*
* ============================================================ start of the
* getIdsOfNames section
* ===========================================================
*/
/**
* @param dispatchTarget
* @param name
* @return int id for the passed in name
*/
public static int getIDOfName(Dispatch dispatchTarget, String name) {
int ids[] = getIDsOfNames(dispatchTarget,
Dispatch.LOCALE_SYSTEM_DEFAULT, new String[] { name });
return ids[0];
}
/**
* @param dispatchTarget
* @param lcid
* @param names
* @return int[] in id array for passed in names
*/
// eliminated _Guid argument
public static native int[] getIDsOfNames(Dispatch dispatchTarget, int lcid,
String[] names);
/**
* @param dispatchTarget
* @param names
* @return int[] int id array for passed in names
*/
// eliminated _Guid argument
public static int[] getIDsOfNames(Dispatch dispatchTarget, String[] names) {
return getIDsOfNames(dispatchTarget, Dispatch.LOCALE_SYSTEM_DEFAULT,
names);
}
/*
* ============================================================ start of the
* invokev section
* ===========================================================
*/
/**
* @param dispatchTarget
* @param name
* @param args
* @return Variant returned by call
*/
public static Variant callN(Dispatch dispatchTarget, String name,
Object... args) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, name, Dispatch.Method | Dispatch.Get,
VariantUtilities.objectsToVariants(args), new int[args.length]);
}
/**
* @param dispatchTarget
* @param dispID
* @param args
* @return Variant returned by call
*/
public static Variant callN(Dispatch dispatchTarget, int dispID,
Object... args) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, dispID, Dispatch.Method | Dispatch.Get,
VariantUtilities.objectsToVariants(args), new int[args.length]);
}
/**
* @param dispatchTarget
* @param name
* @param dispID
* @param lcid
* @param wFlags
* @param oArg
* @param uArgErr
* @return Variant returned by invoke
*/
public static Variant invoke(Dispatch dispatchTarget, String name,
int dispID, int lcid, int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, name, dispID, lcid, wFlags,
VariantUtilities.objectsToVariants(oArg), uArgErr);
}
/**
* @param dispatchTarget
* @param name
* @param wFlags
* @param oArg
* @param uArgErr
* @return Variant returned by invoke
*/
public static Variant invoke(Dispatch dispatchTarget, String name,
int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, name, wFlags, VariantUtilities
.objectsToVariants(oArg), uArgErr);
}
/**
* @param dispatchTarget
* @param dispID
* @param wFlags
* @param oArg
* @param uArgErr
* @return Variant returned by invoke
*/
public static Variant invoke(Dispatch dispatchTarget, int dispID,
int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, dispID, wFlags, VariantUtilities
.objectsToVariants(oArg), uArgErr);
}
/*
* ============================================================ start of the
* callN section ===========================================================
*/
/**
* @param dispatchTarget
* @param name
* @return Variant returned by underlying callN
*/
public static Variant call(Dispatch dispatchTarget, String name) {
throwIfUnattachedDispatch(dispatchTarget);
return callN(dispatchTarget, name, NO_VARIANT_ARGS);
}
/**
* @param dispatchTarget
* @param name
* @param attributes
* @return Variant returned by underlying callN
*/
public static Variant call(Dispatch dispatchTarget, String name,
Object... attributes) {
throwIfUnattachedDispatch(dispatchTarget);
return callN(dispatchTarget, name, attributes);
}
/**
* @param dispatchTarget
* @param dispid
* @return Variant returned by underlying callN
*/
public static Variant call(Dispatch dispatchTarget, int dispid) {
throwIfUnattachedDispatch(dispatchTarget);
return callN(dispatchTarget, dispid, NO_VARIANT_ARGS);
}
/**
* @param dispatchTarget
* @param dispid
* @param attributes
* var arg list of attributes that will be passed to the
* underlying function
* @return Variant returned by underlying callN
*/
public static Variant call(Dispatch dispatchTarget, int dispid,
Object... attributes) {
throwIfUnattachedDispatch(dispatchTarget);
return callN(dispatchTarget, dispid, attributes);
}
/*
* ============================================================ start of the
* invoke section
* ===========================================================
*/
/**
* @param dispatchTarget
* @param name
* @param val
*/
public static void put(Dispatch dispatchTarget, String name, Object val) {
throwIfUnattachedDispatch(dispatchTarget);
invoke(dispatchTarget, name, Dispatch.Put, new Object[] { val },
new int[1]);
}
/**
* @param dispatchTarget
* @param dispid
* @param val
*/
public static void put(Dispatch dispatchTarget, int dispid, Object val) {
throwIfUnattachedDispatch(dispatchTarget);
invoke(dispatchTarget, dispid, Dispatch.Put, new Object[] { val },
new int[1]);
}
/*
* ============================================================ start of the
* invokev section
* ===========================================================
*/
// removed _Guid argument
/**
* @param dispatchTarget
* @param name
* @param dispID
* @param lcid
* @param wFlags
* @param vArg
* @param uArgErr
* @return Variant returned by underlying invokev
*/
public static native Variant invokev(Dispatch dispatchTarget, String name,
int dispID, int lcid, int wFlags, Variant[] vArg, int[] uArgErr);
/**
* @param dispatchTarget
* @param name
* @param wFlags
* @param vArg
* @param uArgErr
* @return Variant returned by underlying invokev
*/
public static Variant invokev(Dispatch dispatchTarget, String name,
int wFlags, Variant[] vArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, name, 0, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, vArg, uArgErr);
}
/**
* @param dispatchTarget
* @param name
* @param wFlags
* @param vArg
* @param uArgErr
* @param wFlagsEx
* @return Variant returned by underlying invokev
*/
public static Variant invokev(Dispatch dispatchTarget, String name,
int wFlags, Variant[] vArg, int[] uArgErr, int wFlagsEx) {
throwIfUnattachedDispatch(dispatchTarget);
// do not implement IDispatchEx for now
return invokev(dispatchTarget, name, 0, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, vArg, uArgErr);
}
/**
* @param dispatchTarget
* @param dispID
* @param wFlags
* @param vArg
* @param uArgErr
* @return Variant returned by underlying invokev
*/
public static Variant invokev(Dispatch dispatchTarget, int dispID,
int wFlags, Variant[] vArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, null, dispID,
Dispatch.LOCALE_SYSTEM_DEFAULT, wFlags, vArg, uArgErr);
}
/*
* ============================================================ start of the
* invokeSubv section
* ===========================================================
*/
// removed _Guid argument
/**
* @param dispatchTarget
* @param name
* @param dispid
* @param lcid
* @param wFlags
* @param oArg
* @param uArgErr
*/
public static void invokeSub(Dispatch dispatchTarget, String name,
int dispid, int lcid, int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokeSubv(dispatchTarget, name, dispid, lcid, wFlags, VariantUtilities
.objectsToVariants(oArg), uArgErr);
}
/*
* ============================================================ start of the
* invokeSub section
* ===========================================================
*/
/**
* @param dispatchTarget
* @param name
* @param wFlags
* @param oArg
* @param uArgErr
*/
public static void invokeSub(Dispatch dispatchTarget, String name,
int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokeSub(dispatchTarget, name, 0, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, oArg, uArgErr);
}
/**
* @param dispatchTarget
* @param dispid
* @param wFlags
* @param oArg
* @param uArgErr
*/
public static void invokeSub(Dispatch dispatchTarget, int dispid,
int wFlags, Object[] oArg, int[] uArgErr) {
throwIfUnattachedDispatch(dispatchTarget);
invokeSub(dispatchTarget, null, dispid, Dispatch.LOCALE_SYSTEM_DEFAULT,
wFlags, oArg, uArgErr);
}
/*
* ============================================================ start of the
* callSubN section
* ===========================================================
*/
/**
* makes call to native callSubN
*
* @param dispatchTarget
* @param name
*/
public static void callSub(Dispatch dispatchTarget, String name) {
throwIfUnattachedDispatch(dispatchTarget);
callSubN(dispatchTarget, name, NO_OBJECT_ARGS);
}
/**
* makes call to native callSubN
*
* @param dispatchTarget
* @param name
* @param attributes
* var args list of attributes to be passed to underlying
* functions
*/
public static void callSub(Dispatch dispatchTarget, String name,
Object... attributes) {
throwIfUnattachedDispatch(dispatchTarget);
callSubN(dispatchTarget, name, attributes);
}
/**
* makes call to native callSubN
*
* @param dispatchTarget
* @param dispid
*/
public static void callSub(Dispatch dispatchTarget, int dispid) {
throwIfUnattachedDispatch(dispatchTarget);
callSubN(dispatchTarget, dispid, NO_OBJECT_ARGS);
}
/**
* makes call to native callSubN
*
* @param dispatchTarget
* @param dispid
* @param attributes
* var args list of attributes to be passed to underlying
* function
*/
public static void callSub(Dispatch dispatchTarget, int dispid,
Object... attributes) {
throwIfUnattachedDispatch(dispatchTarget);
callSubN(dispatchTarget, dispid, attributes);
}
/*
* ============================================================ start of the
* invokev section
* ===========================================================
*/
/**
* Cover for call to underlying invokev()
*
* @param dispatchTarget
* @param name
* @return Variant returned by the request for retrieval of parameter
*/
public static Variant get(Dispatch dispatchTarget, String name) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, name, Dispatch.Get, NO_VARIANT_ARGS,
NO_INT_ARGS);
}
/**
* Cover for call to underlying invokev()
*
* @param dispatchTarget
* @param dispid
* @return Variant returned by the request for retrieval of parameter
*/
public static Variant get(Dispatch dispatchTarget, int dispid) {
throwIfUnattachedDispatch(dispatchTarget);
return invokev(dispatchTarget, dispid, Dispatch.Get, NO_VARIANT_ARGS,
NO_INT_ARGS);
}
/*
* ============================================================ start of the
* invoke section
* ===========================================================
*/
/**
* cover for underlying call to invoke
*
* @param dispatchTarget
* @param name
* @param val
*/
public static void putRef(Dispatch dispatchTarget, String name, Object val) {
throwIfUnattachedDispatch(dispatchTarget);
invoke(dispatchTarget, name, Dispatch.PutRef, new Object[] { val },
new int[1]);
}
/**
* cover for underlying call to invoke
*
* @param dispatchTarget
* @param dispid
* @param val
*/
public static void putRef(Dispatch dispatchTarget, int dispid, Object val) {
throwIfUnattachedDispatch(dispatchTarget);
invoke(dispatchTarget, dispid, Dispatch.PutRef, new Object[] { val },
new int[1]);
}
/**
* not implemented yet
*
* @param dispatchTarget
* @param name
* @return Variant never returned
* @throws com.jacob.com.NotImplementedException
*/
public static Variant get_CaseSensitive(Dispatch dispatchTarget, String name) {
throw new NotImplementedException("not implemented yet");
}
/**
* Cover for native method
*
* @param disp
* @param dispid
* @param lcid
* @return 0 if the dispatch is still active and 1 if it has exited
*/
public static native int hasExited(Dispatch disp, int dispid, int lcid);
/**
* The method is used to poll until it returns 1, indicating that the COM
* server in gone.
* <p>
* Sourceforge feature request 2927058
*
* @param dispatchTarget
* @return 0 if the dispatch is still active and 1 if it has exited
*/
public static int hasExited(Dispatch dispatchTarget) {
throwIfUnattachedDispatch(dispatchTarget);
return hasExited(dispatchTarget, 0, LOCALE_SYSTEM_DEFAULT);
}
}

View File

@@ -1,219 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* This class creates the scaffolding for event callbacks. Every instance of tis
* acts as a wrapper around some java object that wants callbacks from the
* microsoft side. It represents the connection between Java and COM for
* callbacks.
* <p>
* The callback mechanism will take any event that it receives and try and find
* a java method with the same name that accepts the Variant... as a parameter.
* It will then wrap the call back data in the Variant array and call the java
* method of the object that this DispatchEvents object was initialized with.
* <p>
* Instances of this class are created with "sink object" that will receive the
* event messages. The sink object is wrapped in an Invocation handler that
* actually receives the messages and then forwards them on to the "sink
* object". The constructors recognize when an instance of InvocationProxy is
* passed in and do not create a new InvocationProxy as a wrapper. They instead
* use the passed in InvocationProxy.
*
*/
public class DispatchEvents extends JacobObject {
/**
* pointer to an MS data struct. The COM layer knows the name of this
* variable and puts the windows memory pointer here.
*/
int m_pConnPtProxy = 0;
/**
* the wrapper for the event sink. This object is the one that will be sent
* a message when an event occurs in the MS layer. Normally, the
* InvocationProxy will forward the messages to a wrapped object that it
* contains.
*/
InvocationProxy mInvocationProxy = null;
/**
* This is the most commonly used constructor.
* <p>
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
* <p>
* Can be used on any object that implements IProvideClassInfo.
*
* @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks
* @param eventSink
* Java object that wants to receive the events
*/
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink) {
this(sourceOfEvent, eventSink, null);
}
/**
* None of the samples use this constructor.
* <p>
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
* <p>
* Used when the program doesn't implement IProvideClassInfo. It provides a
* way to find the TypeLib in the registry based on the programId. The
* TypeLib is looked up in the registry on the path
* HKEY_LOCAL_MACHINE/SOFTWARE/Classes/CLSID/(CLID drived from
* progid)/ProgID/Typelib
*
* @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks
* @param eventSink
* Java object that wants to receive the events
* @param progId
* program id in the registry that has a TypeLib subkey. The
* progrId is mapped to a CLSID that is they used to look up the
* key to the Typelib
*/
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId) {
this(sourceOfEvent, eventSink, progId, null);
}
/**
* Creates the event callback linkage between the the MS program represented
* by the Dispatch object and the Java object that will receive the
* callback.
* <p>
* This method was added because Excel doesn't implement IProvideClassInfo
* and the registry entry for Excel.Application doesn't include a typelib
* key.
*
* <pre>
* DispatchEvents de = new DispatchEvents(someDispatch, someEventHAndler,
* &quot;Excel.Application&quot;,
* &quot;C:\\Program Files\\Microsoft Office\\OFFICE11\\EXCEL.EXE&quot;);
* </pre>
*
* @param sourceOfEvent
* Dispatch object who's MS app will generate callbacks
* @param eventSink
* Java object that wants to receive the events
* @param progId ,
* mandatory if the typelib is specified
* @param typeLib
* The location of the typelib to use
*/
public DispatchEvents(Dispatch sourceOfEvent, Object eventSink,
String progId, String typeLib) {
if (JacobObject.isDebugEnabled()) {
System.out.println("DispatchEvents: Registering " + eventSink
+ "for events ");
}
if (eventSink instanceof InvocationProxy) {
mInvocationProxy = (InvocationProxy) eventSink;
} else {
mInvocationProxy = getInvocationProxy(eventSink);
}
if (mInvocationProxy != null) {
init3(sourceOfEvent, mInvocationProxy, progId, typeLib);
} else {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("Cannot register null event sink for events");
}
throw new IllegalArgumentException(
"Cannot register null event sink for events");
}
}
/**
* Returns an instance of the proxy configured with pTargetObject as its
* target
*
* @param pTargetObject
* @return InvocationProxy an instance of the proxy this DispatchEvents will
* send to the COM layer
*/
protected InvocationProxy getInvocationProxy(Object pTargetObject) {
InvocationProxy newProxy = new InvocationProxyAllVariants();
newProxy.setTarget(pTargetObject);
return newProxy;
}
/**
* hooks up a connection point proxy by progId event methods on the sink
* object will be called by name with a signature of <name>(Variant[] args)
*
* You must specify the location of the typeLib.
*
* @param src
* dispatch that is the source of the messages
* @param sink
* the object that will receive the messages
* @param progId
* optional program id. most folks don't need this either
* @param typeLib
* optional parameter for those programs that don't register
* their type libs (like Excel)
*/
private native void init3(Dispatch src, Object sink, String progId,
String typeLib);
/**
* now private so only this object can asccess was: call this to explicitly
* release the com object before gc
*
*/
private native void release();
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
protected void finalize() {
safeRelease();
}
/*
* (non-Javadoc)
*
* @see com.jacob.com.JacobObject#safeRelease()
*/
public void safeRelease() {
if (mInvocationProxy != null) {
mInvocationProxy.setTarget(null);
}
mInvocationProxy = null;
super.safeRelease();
if (m_pConnPtProxy != 0) {
release();
m_pConnPtProxy = 0;
} else {
// looks like a double release
if (isDebugEnabled()) {
debug("DispatchEvents:" + this.hashCode() + " double release");
}
}
}
}

View File

@@ -1,82 +0,0 @@
/**
*
*/
package com.jacob.com;
/**
* A bunch of DispatchIds that were pulled out of the Dispatch class for version
* 1.14.
*/
public class DispatchIdentifier {
private DispatchIdentifier() {
// This is utility class so there is no constructor.
}
public static final int DISPID_UNKNOWN = -1;
public static final int DISPID_VALUE = 0;
public static final int DISPID_PROPERTYPUT = -3;
public static final int DISPID_NEWENUM = -4;
public static final int DISPID_EVALUATE = -5;
public static final int DISPID_CONSTRUCTOR = -6;
public static final int DISPID_DESTRUCTOR = -7;
public static final int DISPID_COLLECT = -8;
public static final int DISPID_AUTOSIZE = -500;
public static final int DISPID_BACKCOLOR = -501;
public static final int DISPID_BACKSTYLE = -502;
public static final int DISPID_BORDERCOLOR = -503;
public static final int DISPID_BORDERSTYLE = -504;
public static final int DISPID_BORDERWIDTH = -505;
public static final int DISPID_DRAWMODE = -507;
public static final int DISPID_DRAWSTYLE = -508;
public static final int DISPID_DRAWWIDTH = -509;
public static final int DISPID_FILLCOLOR = -510;
public static final int DISPID_FILLSTYLE = -511;
public static final int DISPID_FONT = -512;
public static final int DISPID_FORECOLOR = -513;
public static final int DISPID_ENABLED = -514;
public static final int DISPID_HWND = -515;
public static final int DISPID_TABSTOP = -516;
public static final int DISPID_TEXT = -517;
public static final int DISPID_CAPTION = -518;
public static final int DISPID_BORDERVISIBLE = -519;
public static final int DISPID_APPEARANCE = -520;
public static final int DISPID_MOUSEPOINTER = -521;
public static final int DISPID_MOUSEICON = -522;
public static final int DISPID_PICTURE = -523;
public static final int DISPID_VALID = -524;
public static final int DISPID_READYSTATE = -525;
public static final int DISPID_REFRESH = -550;
public static final int DISPID_DOCLICK = -551;
public static final int DISPID_ABOUTBOX = -552;
public static final int DISPID_CLICK = -600;
public static final int DISPID_DBLCLICK = -601;
public static final int DISPID_KEYDOWN = -602;
public static final int DISPID_KEYPRESS = -603;
public static final int DISPID_KEYUP = -604;
public static final int DISPID_MOUSEDOWN = -605;
public static final int DISPID_MOUSEMOVE = -606;
public static final int DISPID_MOUSEUP = -607;
public static final int DISPID_ERROREVENT = -608;
public static final int DISPID_READYSTATECHANGE = -609;
public static final int DISPID_AMBIENT_BACKCOLOR = -701;
public static final int DISPID_AMBIENT_DISPLAYNAME = -702;
public static final int DISPID_AMBIENT_FONT = -703;
public static final int DISPID_AMBIENT_FORECOLOR = -704;
public static final int DISPID_AMBIENT_LOCALEID = -705;
public static final int DISPID_AMBIENT_MESSAGEREFLECT = -706;
public static final int DISPID_AMBIENT_SCALEUNITS = -707;
public static final int DISPID_AMBIENT_TEXTALIGN = -708;
public static final int DISPID_AMBIENT_USERMODE = -709;
public static final int DISPID_AMBIENT_UIDEAD = -710;
public static final int DISPID_AMBIENT_SHOWGRABHANDLES = -711;
public static final int DISPID_AMBIENT_SHOWHATCHING = -712;
public static final int DISPID_AMBIENT_DISPLAYASDEFAULT = -713;
public static final int DISPID_AMBIENT_SUPPORTSMNEMONICS = -714;
public static final int DISPID_AMBIENT_AUTOCLIP = -715;
public static final int DISPID_AMBIENT_APPEARANCE = -716;
public static final int DISPID_AMBIENT_CODEPAGE = -725;
public static final int DISPID_AMBIENT_PALETTE = -726;
public static final int DISPID_AMBIENT_CHARSET = -727;
public static final int DISPID_AMBIENT_TRANSFERPRIORITY = -728;
}

View File

@@ -1,92 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* If you need to pass a COM Dispatch object between STA threads, you have to
* marshall the interface. This class is used as follows: the STA that creates
* the Dispatch object must construct an instance of this class. Another thread
* can then call toDispatch() on that instance and get a Dispatch pointer which
* has been marshalled. WARNING: You can only call toDispatch() once! If you
* need to call it multiple times (or from multiple threads) you need to
* construct a separate DispatchProxy instance for each such case!
*/
public class DispatchProxy extends JacobObject {
/**
* Comment for <code>m_pStream</code>
*/
public int m_pStream;
/**
* Marshals the passed in dispatch into the stream
*
* @param localDispatch
*/
public DispatchProxy(Dispatch localDispatch) {
MarshalIntoStream(localDispatch);
}
/**
*
* @return Dispatch the dispatch retrieved from the stream
*/
public Dispatch toDispatch() {
return MarshalFromStream();
}
private native void MarshalIntoStream(Dispatch d);
private native Dispatch MarshalFromStream();
/**
* now private so only this object can access was: call this to explicitly
* release the com object before gc
*
*/
private native void release();
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
public void finalize() {
safeRelease();
}
/*
* (non-Javadoc)
*
* @see com.jacob.com.JacobObject#safeRelease()
*/
public void safeRelease() {
super.safeRelease();
if (m_pStream != 0) {
release();
m_pStream = 0;
} else {
// looks like a double release
if (isDebugEnabled()) {
debug(this.getClass().getName() + ":" + this.hashCode()
+ " double release");
}
}
}
}

View File

@@ -1,156 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* An implementation of IEnumVariant based on code submitted by Thomas Hallgren
* (mailto:Thomas.Hallgren@eoncompany.com)
*/
public class EnumVariant extends JacobObject implements
java.util.Enumeration<Variant> {
private int m_pIEnumVARIANT;
private final Variant[] m_recBuf = new Variant[1];
// this only gets called from JNI
//
protected EnumVariant(int pIEnumVARIANT) {
m_pIEnumVARIANT = pIEnumVARIANT;
}
/**
* @param disp
*/
public EnumVariant(Dispatch disp) {
int[] hres = new int[1];
Variant evv = Dispatch.invokev(disp, DispatchIdentifier.DISPID_NEWENUM,
Dispatch.Get, new Variant[0], hres);
if (evv.getvt() != Variant.VariantObject)
//
// The DISPID_NEWENUM did not result in a valid object
//
throw new ComFailException("Can't obtain EnumVARIANT");
EnumVariant tmp = evv.toEnumVariant();
m_pIEnumVARIANT = tmp.m_pIEnumVARIANT;
tmp.m_pIEnumVARIANT = 0;
}
/**
* Implements java.util.Enumeration
*
* @return boolean true if there are more elements in this enumeration
*/
public boolean hasMoreElements() {
{
if (m_recBuf[0] == null) {
if (this.Next(m_recBuf) <= 0)
return false;
}
return true;
}
}
/**
* Implements java.util.Enumeration
*
* @return next element in the enumeration
*/
public Variant nextElement() {
Variant last = m_recBuf[0];
if (last == null) {
if (this.Next(m_recBuf) <= 0)
throw new java.util.NoSuchElementException();
last = m_recBuf[0];
}
m_recBuf[0] = null;
return last;
}
/**
* Get next element in collection or null if at end
*
* @return Variant that is next in the collection
* @deprecated use nextElement() instead
*/
@Deprecated
public Variant Next() {
if (hasMoreElements())
return nextElement();
return null;
}
/**
* This should be private and wrapped to protect JNI layer.
*
* @param receiverArray
* @return Returns the next variant object pointer as an int from windows
* layer
*/
public native int Next(Variant[] receiverArray);
/**
* This should be private and wrapped to protect JNI layer.
*
* @param count
* number to skip
*/
public native void Skip(int count);
/**
* This should be private and wrapped to protect JNI layer
*/
public native void Reset();
/**
* now private so only this object can access was: call this to explicitly
* release the com object before gc
*
*/
private native void release();
/*
* (non-Javadoc)
*
* @see java.lang.Object#finalize()
*/
protected void finalize() {
safeRelease();
}
/*
* (non-Javadoc)
*
* @see com.jacob.com.JacobObject#safeRelease()
*/
public void safeRelease() {
super.safeRelease();
if (m_pIEnumVARIANT != 0) {
this.release();
m_pIEnumVARIANT = 0;
} else {
// looks like a double release
if (isDebugEnabled()) {
debug(this.getClass().getName() + ":" + this.hashCode()
+ " double release");
}
}
}
}

View File

@@ -1,108 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* @version $Id$
* @author joe
*
* DispatchEvents wraps this class around any event handlers before making the
* JNI call that sets up the link with EventProxy. This means that
* EventProxy.cpp just calls invoke(String,Variant[]) against the instance of
* this class. Then this class does reflection against the event listener to
* call the actual event methods. The event methods can return void or return a
* Variant. Any value returned will be passed back to the calling windows module
* by the Jacob JNI layer.
* <p>
*
* The void returning signature is the standard legacy signature. The Variant
* returning signature was added in 1.10 to support event handlers returning
* values.
*
*/
public abstract class InvocationProxy {
/**
* the object we will try and forward to.
*/
protected Object mTargetObject = null;
/**
* dummy constructor for subclasses that don't actually wrap anything and
* just want to override the invoke() method
*/
protected InvocationProxy() {
super();
}
/**
* The method actually invoked by EventProxy.cpp. The method name is
* calculated by the underlying JNI code from the MS windows Callback
* function name. The method is assumed to take an array of Variant objects.
* The method may return a Variant or be a void. Those are the only two
* options that will not blow up.
* <p>
* Subclasses that override this should make sure mTargetObject is not null
* before processing.
*
* @param methodName
* name of method in mTargetObject we will invoke
* @param targetParameters
* Variant[] that is the single parameter to the method
* @return an object that will be returned to the com event caller
*/
public abstract Variant invoke(String methodName,
Variant targetParameters[]);
/**
* used by EventProxy.cpp to create variant objects in the right thread
*
* @return Variant object that will be used by the COM layer
*/
public Variant getVariant() {
return new VariantViaEvent();
}
/**
* Sets the target for this InvocationProxy.
*
* @param pTargetObject
* @throws IllegalArgumentException
* if target is not publicly accessible
*/
public void setTarget(Object pTargetObject) {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: setting target "
+ pTargetObject);
}
if (pTargetObject != null) {
// JNI code apparently bypasses this check and could operate against
// protected classes. This seems like a security issue...
// maybe it was because JNI code isn't in a package?
if (!java.lang.reflect.Modifier.isPublic(pTargetObject.getClass()
.getModifiers())) {
throw new IllegalArgumentException(
"InvocationProxy only public classes can receive event notifications");
}
}
mTargetObject = pTargetObject;
}
}

View File

@@ -1,123 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* This class acts as a proxy between the windows event callback mechanism and
* the Java classes that are looking for events. It assumes that all of the Java
* classes that are looking for events implement methods with the same names as
* the windows events and that the implemented methods accept an array of
* variant objects. The methods can return void or a Variant that will be
* returned to the calling layer. All Event methods that will be recognized by
* InvocationProxyAllEvents have the signature
*
* <code> void eventMethodName(Variant[])</code> or
* <code> Variant eventMethodName(Variant[])</code>
*/
public class InvocationProxyAllVariants extends InvocationProxy {
/*
* (non-Javadoc)
*
* @see com.jacob.com.InvocationProxy#invoke(java.lang.String,
* com.jacob.com.Variant[])
*/
@SuppressWarnings("unchecked")
public Variant invoke(String methodName, Variant targetParameters[]) {
Variant mVariantToBeReturned = null;
if (mTargetObject == null) {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: received notification ("
+ methodName + ") with no target set");
}
// structured programming guidlines say this return should not be up
// here
return null;
}
Class targetClass = mTargetObject.getClass();
if (methodName == null) {
throw new IllegalArgumentException(
"InvocationProxy: missing method name");
}
if (targetParameters == null) {
throw new IllegalArgumentException(
"InvocationProxy: missing Variant parameters");
}
try {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: trying to invoke "
+ methodName + " on " + mTargetObject);
}
Method targetMethod;
targetMethod = targetClass.getMethod(methodName,
new Class[] { Variant[].class });
if (targetMethod != null) {
// protected classes can't be invoked against even if they
// let you grab the method. you could do
// targetMethod.setAccessible(true);
// but that should be stopped by the security manager
Object mReturnedByInvocation = null;
mReturnedByInvocation = targetMethod.invoke(mTargetObject,
new Object[] { targetParameters });
if (mReturnedByInvocation == null) {
mVariantToBeReturned = null;
} else if (!(mReturnedByInvocation instanceof Variant)) {
// could try and convert to Variant here.
throw new IllegalArgumentException(
"InvocationProxy: invokation of target method returned "
+ "non-null non-variant object: "
+ mReturnedByInvocation);
} else {
mVariantToBeReturned = (Variant) mReturnedByInvocation;
}
}
} catch (SecurityException e) {
// what causes this exception?
e.printStackTrace();
} catch (NoSuchMethodException e) {
// this happens whenever the listener doesn't implement all the
// methods
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("InvocationProxy: listener (" + mTargetObject
+ ") doesn't implement " + methodName);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
// we can throw these inside the catch block so need to re-throw it
throw e;
} catch (IllegalAccessException e) {
// can't access the method on the target instance for some reason
if (JacobObject.isDebugEnabled()) {
JacobObject
.debug("InvocationProxy: probably tried to access public method on non public class"
+ methodName);
}
e.printStackTrace();
} catch (InvocationTargetException e) {
// invocation of target method failed
e.printStackTrace();
}
return mVariantToBeReturned;
}
}

View File

@@ -1,49 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* The parent class of all Jacob exceptions. They all used to be based off of
* RuntimeException or ComException but it was decided to base them all off of
* one owned by this project.
*/
public class JacobException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -1637125318746002715L;
/**
* Default constructor. Calls super with a "No Message Provided" string
*/
public JacobException() {
super("No Message Provided");
}
/**
* standard constructor
*
* @param message
*/
public JacobException(String message) {
super(message);
}
}

View File

@@ -1,110 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* The superclass of all Jacob objects. It is used to create a standard API
* framework and to facilitate memory management for Java and COM memory
* elements.
* <p>
* All instances of this class and subclasses are automatically managed by the
* ROT. This means the ROT cannot be a subclass of JacobObject.
* <p>
* All COM object created by JACOB extend this class so that we can
* automatically release them when the thread is detached from COM - if we leave
* it to the finalizer it will call the release from another thread, which may
* result in a segmentation violation.
*/
public class JacobObject {
/**
* Standard constructor that adds this JacobObject to the memory management
* pool.
*/
public JacobObject() {
ROT.addObject(this);
}
/**
* Finalizers call this method. This method should release any COM data
* structures in a way that it can be called multiple times. This can happen
* if someone manually calls this and then a finalizer calls it.
*/
public void safeRelease() {
// currently does nothing - subclasses may do something
if (isDebugEnabled()) {
// this used to do a toString() but that is bad for SafeArray
debug("SafeRelease: " + this.getClass().getName());
}
}
/**
* When things go wrong, it is useful to be able to debug the ROT.
*/
private static final boolean DEBUG =
// true;
"true".equalsIgnoreCase(System.getProperty("com.jacob.debug"));
protected static boolean isDebugEnabled() {
return DEBUG;
}
/**
* Loads JacobVersion.Properties and returns the value of version in it
*
* @deprecated use JacobReleaseInfo.getBuildDate() instead.
* @return String value of version in JacobVersion.Properties or "" if none
*/
@Deprecated
public static String getBuildDate() {
return JacobReleaseInfo.getBuildDate();
}
/**
* Loads JacobVersion.Properties and returns the value of version in it
*
* @deprecated use JacobReleaseInfo.getBuildVersion() instead.
* @return String value of version in JacobVersion.Properties or "" if none
*/
@Deprecated
public static String getBuildVersion() {
return JacobReleaseInfo.getBuildVersion();
}
/**
* Very basic debugging function.
*
* @param istrMessage
*/
protected static void debug(String istrMessage) {
if (isDebugEnabled()) {
System.out.println(Thread.currentThread().getName() + ": "
+ istrMessage);
}
}
/**
* force the jacob DLL to be loaded whenever this class is referenced
*/
static {
LibraryLoader.loadJacobLibrary();
}
}

View File

@@ -1,96 +0,0 @@
package com.jacob.com;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* An interface to the version properties file. This code was removed from
* JacobObject because it doesn't belong there.
*
*/
public class JacobReleaseInfo {
/**
* holds the build version as retrieved from the version properties file
* that exists in the JAR. This can be retrieved by calling the static
* method getBuildVersion()
*
* @see #getBuildVersion()
*/
private static String buildVersion = "";
/**
* holds the build date as retrieved from the version properties file that
* exists in the JAR This can be retrieved by calling the static method
* getBuildDate()
*
* @see #getBuildDate()
*/
private static String buildDate = "";
/** the name of the jacob version properties file */
private static final String PROPERTY_FILE_NAME = "META-INF/JacobVersion.properties";
/**
* Loads version information from PROPERTY_FILE_NAME that was built as part
* of this release.
*
* @throws IllegalStateException
* when it can't find the version properties file
*/
private static void loadVersionProperties() {
Properties versionProps = new Properties();
// can't use system class loader cause won't work in JavaWebStart
InputStream stream = JacobReleaseInfo.class.getClassLoader()
.getResourceAsStream(PROPERTY_FILE_NAME);
// This should never happen. This is an attempt to make something work
// for WebSphere. They may be using some kind of Servlet loader that
// needs an absolute path based search
if (stream == null) {
stream = JacobReleaseInfo.class.getClassLoader()
.getResourceAsStream("/" + PROPERTY_FILE_NAME);
}
// A report came in that WebSphere had trouble finding the file
// so lets trap it. Plus, it's a good idea anyway.
if (stream == null) {
throw new IllegalStateException(
"Can't find "
+ PROPERTY_FILE_NAME
+ " using JacobReleaseInfo.class.getClassLoader().getResourceAsStream()");
} else {
try {
versionProps.load(stream);
stream.close();
buildVersion = (String) versionProps.get("version");
buildDate = (String) versionProps.get("build.date");
} catch (IOException ioe) {
ioe.printStackTrace();
System.err.println("Warning! Couldn't load props " + ioe);
}
}
}
/**
* loads PROPERT_FILE_NAME and returns the value of version in it
*
* @return String value of version in PROPERT_FILE_NAME or "" if none
*/
public static String getBuildDate() {
if (buildDate.equals("")) {
loadVersionProperties();
}
return buildDate;
}
/**
* loads PROPERT_FILE_NAME and returns the value of version in it
*
* @return String value of version in PROPERT_FILE_NAME or "" if none
*/
public static String getBuildVersion() {
if (buildVersion.equals("")) {
loadVersionProperties();
}
return buildVersion;
}
}

View File

@@ -1,230 +0,0 @@
/*
* Copyright (c) 1999-2007 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Set;
/**
* Utility class to centralize the way in which the jacob JNI library is loaded.
* <p>
*
* This supports defining the path or library name using system properties or a
* custom resource file. If desired, jacob can auto-detect the correct version
* of the DLL for 32 or 64 bit windows, as long as you have named them
* differently.
*
* <ol>
* <li> If system property {@link #JACOB_DLL_PATH} is defined, the file located
* there will be loaded as the jacob dll using System.load(). </li>
*
* <li> If system property {@link #JACOB_DLL_NAME} is defined, the file located
* there will be loaded as the jacob dll. </li>
* <li> If system property {@link #JACOB_DLL_NAME_X86} and
* {@link #JACOB_DLL_NAME_X64} are defined, the file located there will be
* loaded as the jacob dll, depending on the version of Windows. </li>
*
* <li> If {@link #JACOB_DLL_NAME} is defined in the
* {@code com.jacob.com.JacobLibraryLoader} resource file, the specified dll
* will be loaded from the {@code java.library.path}. </li>
* <li> If {@link #JACOB_DLL_NAME_X86} and {@link #JACOB_DLL_NAME_X64} are
* defined in the {@code com.jacob.com.JacobLibraryLoader} resource file, the
* specified dll will be loaded from the {@code java.library.path}, depending
* on the version of Windows. </li>
*
* <li> If none of the above are true, the default is to load the library named
* "jacob-&lt;version&gt;-&lt;arch&gt" (or
* "jacob-&lt;version&gt;-&lt;arch&rt;.dll") from the {@code java.library.path}.
* </li>
* </ol>
*
* The standard behavior for most applications is that {@code LoadLibrary()}
* will be called to load the dll. {@code LoadLibary()} searches directories
* specified in the variable {@code java.library.path}. This is why most test
* cases specify -Djava.library.path in their command line arguments.
* <p>
* JACOB_DLL_PATH submitted sourceforge ticket 1493647 Added 1.11 <br>
* JACOB_DLL_NAME, JACOB_DLL_NAME_32, JACOB_DLL_NAME_64 submitted sourceforge
* ticket 1845039 Added 1.14M7
*
* @author Scott Dickerson (sjd78)
* @author Jason Smith
*/
public final class LibraryLoader {
/**
* Name of system property (currently <tt>jacob.dll.path</tt>) that may
* contain an absolute path to the JNI library.
*/
public static final String JACOB_DLL_PATH = "jacob.dll.path";
/**
* Name of system property (currently <tt>jacob.dll.name</tt>) that may
* contain an alternate name for the JNI library (default is 'jacob').
*/
public static final String JACOB_DLL_NAME = "jacob.dll.name";
/**
* Name of system property (currently <tt>jacob.dll.name</tt>) that may
* contain an alternate name for the JNI library (default is 'jacob'), 32
* bit windows.
*/
public static final String JACOB_DLL_NAME_X86 = "jacob.dll.name.x86";
/**
* Name of system property (currently <tt>jacob.dll.name</tt>) that may
* contain an alternate name for the JNI library (default is 'jacob'), 64
* bit windows.
*/
public static final String JACOB_DLL_NAME_X64 = "jacob.dll.name.x64";
/**
* Appended to "jacob" when building DLL name This string must EXACTLY match
* the string in the build.xml file
*/
public static final String DLL_NAME_MODIFIER_32_BIT = "x86";
/**
* Appended to "jacob" when building DLL name This string must EXACTLY match
* the string in the build.xml file
*/
public static final String DLL_NAME_MODIFIER_64_BIT = "x64";
/**
* Load the jacob dll either from an absolute path or by a library name,
* both of which may be defined in various ways.
*
* @throws UnsatisfiedLinkError
* if the library does not exist.
*/
public static void loadJacobLibrary() {
// In some cases, a library that uses Jacob won't be able to set system
// properties
// prior to Jacob being loaded. The resource bundle provides an
// alternate way to
// override DLL name or path that will be loaded with Jacob regardless
// of other
// initialization order.
ResourceBundle resources = null;
Set<String> keys = new HashSet<String>();
try {
resources = ResourceBundle.getBundle(LibraryLoader.class.getName(),
Locale.getDefault(), LibraryLoader.class.getClassLoader());
for (Enumeration<String> i = resources.getKeys(); i
.hasMoreElements();) {
String key = i.nextElement();
keys.add(key);
}
} catch (MissingResourceException e) {
// Do nothing. Expected.
}
// First, check for a defined PATH. System property overrides resource
// bundle.
String path = System.getProperty(JACOB_DLL_PATH);
if (path == null && resources != null && keys.contains(JACOB_DLL_PATH)) {
path = (String) resources.getObject(JACOB_DLL_PATH);
}
if (path != null) {
JacobObject.debug("Loading library " + path
+ " using System.loadLibrary ");
System.load(path);
} else {
// Path was not defined, so use the OS mechanism for loading
// libraries.
// Check for a defined NAME. System property overrides resource
// bundle.
String name = null;
if (System.getProperty(JACOB_DLL_NAME) != null) {
name = System.getProperty(JACOB_DLL_NAME);
} else if (System.getProperty(JACOB_DLL_NAME_X86) != null
&& shouldLoad32Bit()) {
name = System.getProperty(JACOB_DLL_NAME_X86);
} else if (System.getProperty(JACOB_DLL_NAME_X64) != null
&& !shouldLoad32Bit()) {
name = System.getProperty(JACOB_DLL_NAME_X64);
} else if (resources != null && keys.contains(JACOB_DLL_NAME)) {
name = resources.getString(JACOB_DLL_NAME);
} else if (resources != null && keys.contains(JACOB_DLL_NAME_X86)
&& shouldLoad32Bit()) {
name = resources.getString(JACOB_DLL_NAME_X86);
} else if (resources != null && keys.contains(JACOB_DLL_NAME_X64)
&& !shouldLoad32Bit()) {
name = resources.getString(JACOB_DLL_NAME_X64);
} else {
// No alternate NAME or PATH was defined, so use the default.
// We will almost always end up here.
name = getPreferredDLLName();
}
JacobObject.debug("Loading library " + name
+ " using System.loadLibrary ");
// System.out.println("Loading " + name);
System.loadLibrary(name);
}
}
/**
* Developer note: This method MUST be synchronized with the DLL names
* created as part of the build process in build.xml
* <p>
* The DLL name is "jacob\<PLATFORM\>.release"
*
* @return the preferred name of the DLL adjusted for this platform and
* version without the ".dll" extension
*/
public static String getPreferredDLLName() {
if (shouldLoad32Bit()) {
return "jacob" + "-" + JacobReleaseInfo.getBuildVersion() + "-"
+ DLL_NAME_MODIFIER_32_BIT;
} else {
return "jacob" + "-" + JacobReleaseInfo.getBuildVersion() + "-"
+ DLL_NAME_MODIFIER_64_BIT;
}
}
/**
* Detects whether this is a 32-bit JVM.
*
* @return {@code true} if this is a 32-bit JVM.
*/
protected static boolean shouldLoad32Bit() {
// This guesses whether we are running 32 or 64 bit Java.
// This works for Sun and IBM JVMs version 5.0 or later.
// May need to be adjusted for non-Sun JVMs.
String bits = System.getProperty("sun.arch.data.model", "?");
if (bits.equals("32"))
return true;
else if (bits.equals("64"))
return false;
// this works for jRocket
String arch = System.getProperty("java.vm.name", "?");
if (arch.toLowerCase().indexOf("64-bit") >= 0)
return false;
return true;
}
} // LibraryLoader

View File

@@ -1,29 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* We provide our own main sta thread to avoid COM tagging a random thread as
* the main STA - this is the thread in which all Apartment threaded components
* will be created if the client chooses an MTA threading model for the java
* side of the app.
*/
public class MainSTA extends STA {
}

View File

@@ -1,41 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* Thrown by java APIs that are not implemented either because they were never
* implemented or because they are being deprecated This is a subclass of
* ComException so callers can still just catch ComException.
*/
public class NotImplementedException extends JacobException {
/**
*
*/
private static final long serialVersionUID = -9169900832852356445L;
/**
* @param description
*/
public NotImplementedException(String description) {
super(description);
}
}

View File

@@ -1,279 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
/**
* The Running Object Table (ROT) maps each thread to a collection of all the
* JacobObjects that were created in that thread. It always operates on the
* current thread so all the methods are static and they implicitly get the
* current thread.
* <p>
* The clearObjects method is used to release all the COM objects created by
* Jacob in the current thread prior to uninitializing COM for that thread.
* <p>
* Prior to 1.9, manual garbage collection was the only option in Jacob, but
* from 1.9 onward, setting the com.jacob.autogc system property allows the
* objects referenced by the ROT to be automatically GCed. Automatic GC may be
* preferable in systems with heavy event callbacks.
* <p>
* Is [ 1116101 ] jacob-msg 0284 relevant???
*/
public abstract class ROT {
/**
* Manual garbage collection was the only option pre 1.9 Can staticly cache
* the results because only one value and we don't let it change during a
* run
*/
protected static final boolean USE_AUTOMATIC_GARBAGE_COLLECTION = "true"
.equalsIgnoreCase(System.getProperty("com.jacob.autogc"));
/**
* If the code is ran from an applet that is called from javascript the Java
* Plugin does not give full permissions to the code and thus System
* properties cannot be accessed. They can be accessed at class
* initialization time.
*
* The default behavior is to include all classes in the ROT, setting a
* boolean here to indicate this prevents a call to System.getProperty as
* part of the general call flow.
*/
protected static final Boolean INCLUDE_ALL_CLASSES_IN_ROT = Boolean
.valueOf(System.getProperty("com.jacob.includeAllClassesInROT",
"true"));
/**
* Suffix added to class name to make up property name that determines if
* this object should be stored in the ROT. This 1.13 "feature" makes it
* possible to cause VariantViaEvent objects to not be added to the ROT in
* event callbacks.
* <p>
* We don't have a static for the actual property because there is a
* different property for each class that may make use of this feature.
*/
protected static String PUT_IN_ROT_SUFFIX = ".PutInROT";
/**
* A hash table where each element is another HashMap that represents a
* thread. Each thread HashMap contains the com objects created in that
* thread
*/
private static HashMap<String, Map<JacobObject, String>> rot = new HashMap<String, Map<JacobObject, String>>();
/**
* adds a new thread storage area to rot
*
* @return Map corresponding to the thread that this call was made in
*/
protected synchronized static Map<JacobObject, String> addThread() {
// should use the id here instead of the name because the name can be
// changed
String t_name = Thread.currentThread().getName();
if (rot.containsKey(t_name)) {
// nothing to do
} else {
Map<JacobObject, String> tab = null;
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: Automatic GC flag == "
+ USE_AUTOMATIC_GARBAGE_COLLECTION);
}
if (!USE_AUTOMATIC_GARBAGE_COLLECTION) {
tab = new HashMap<JacobObject, String>();
} else {
tab = new WeakHashMap<JacobObject, String>();
}
rot.put(t_name, tab);
}
return getThreadObjects(false);
}
/**
* Returns the pool for this thread if it exists. can create a new one if
* you wish by passing in TRUE
*
* @param createIfDoesNotExist
* @return Map the collection that holds the objects created in the current
* thread
*/
protected synchronized static Map<JacobObject, String> getThreadObjects(
boolean createIfDoesNotExist) {
String t_name = Thread.currentThread().getName();
if (!rot.containsKey(t_name) && createIfDoesNotExist) {
addThread();
}
return rot.get(t_name);
}
/**
* Iterates across all of the entries in the Hashmap in the rot that
* corresponds to this thread. This calls safeRelease() on each entry and
* then clears the map when done and removes it from the rot. All traces of
* this thread's objects will disappear. This is called by COMThread in the
* tear down and provides a synchronous way of releasing memory
*/
protected static void clearObjects() {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: " + rot.keySet().size()
+ " thread tables exist");
}
Map<JacobObject, String> tab = getThreadObjects(false);
if (tab != null) {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: " + tab.keySet().size()
+ " objects to clear in this thread's ROT ");
}
// walk the values
Iterator<JacobObject> it = tab.keySet().iterator();
while (it.hasNext()) {
JacobObject o = it.next();
if (o != null
// can't use this cause creates a Variant if calling SafeAray
// and we get an exception modifying the collection while
// iterating
// && o.toString() != null
) {
if (JacobObject.isDebugEnabled()) {
if (o instanceof SafeArray) {
// SafeArray create more objects when calling
// toString()
// which causes a concurrent modification exception
// in HashMap
JacobObject.debug("ROT: removing "
+ o.getClass().getName());
} else {
// Variant toString() is probably always bad in here
JacobObject.debug("ROT: removing " + o.hashCode()
+ "->" + o.getClass().getName());
}
}
o.safeRelease();
}
}
// empty the collection
tab.clear();
// remove the collection from rot
ROT.removeThread();
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: thread table cleared and removed");
}
} else {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: nothing to clear!");
}
}
}
/**
* Removes the map from the rot that is associated with the current thread.
*/
private synchronized static void removeThread() {
// should this see if it exists first?
rot.remove(Thread.currentThread().getName());
}
/**
* @deprecated the java model leave the responsibility of clearing up
* objects to the Garbage Collector. Our programming model
* should not require that the user specifically remove object
* from the thread. <br>
* This will remove an object from the ROT <br>
* This does not need to be synchronized because only the rot
* modification related methods need to synchronized. Each
* individual map is only modified in a single thread.
* @param o
*/
@Deprecated
protected static void removeObject(JacobObject o) {
Map<JacobObject, String> tab = ROT.getThreadObjects(false);
if (tab != null) {
tab.remove(o);
}
o.safeRelease();
}
/**
* Adds an object to the HashMap for the current thread. <br>
* <p>
* This method does not need to be threaded because the only concurrent
* modification risk is on the hash map that contains all of the thread
* related hash maps. The individual thread related maps are only used on a
* per thread basis so there isn't a locking issue.
* <p>
* In addition, this method cannot be threaded because it calls
* ComThread.InitMTA. The ComThread object has some methods that call ROT so
* we could end up deadlocked. This method should be safe without the
* synchronization because the ROT works on per thread basis and the methods
* that add threads and remove thread related entries are all synchronized
*
*
* @param o
*/
protected static void addObject(JacobObject o) {
String shouldIncludeClassInROT = "true";
// only call System.getProperty if we are not including all classes in
// the ROT. This lets us run with standard Jacob behavior in Applets
// without the security exception raised by System.getProperty in the
// flow
if (!ROT.INCLUDE_ALL_CLASSES_IN_ROT) {
shouldIncludeClassInROT = System.getProperty(o.getClass().getName()
+ PUT_IN_ROT_SUFFIX, "true");
}
if (shouldIncludeClassInROT.equalsIgnoreCase("false")) {
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("JacobObject: New instance of "
+ o.getClass().getName() + " not added to ROT");
}
} else {
// first see if we have a table for this thread
Map<JacobObject, String> tab = getThreadObjects(false);
if (tab == null) {
// this thread has not been initialized as a COM thread
// so make it part of MTA for backwards compatibility
ComThread.InitMTA(false);
// don't really need the "true" because the InitMTA will have
// called back to the ROT to create a table for this thread
tab = getThreadObjects(true);
}
if (JacobObject.isDebugEnabled()) {
JacobObject.debug("ROT: adding " + o + "->"
+ o.getClass().getName()
+ " table size prior to addition:" + tab.size());
}
// add the object to the table that is specific to this thread
if (tab != null) {
tab.put(o, null);
}
}
}
/**
* ROT can't be a subclass of JacobObject because of the way ROT pools are
* managed so we force a DLL load here by referencing JacobObject
*/
static {
LibraryLoader.loadJacobLibrary();
}
}

View File

@@ -1,101 +0,0 @@
/*
* Copyright (c) 1999-2004 Sourceforge JACOB Project.
* All rights reserved. Originator: Dan Adler (http://danadler.com).
* Get more information about JACOB at http://sourceforge.net/projects/jacob-project
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.jacob.com;
/**
* A class that implements a Single Threaded Apartment. Users will subclass this
* and override OnInit() and OnQuit() where they will create and destroy a COM
* component that wants to run in an STA other than the main STA.
*/
public class STA extends Thread {
/**
* referenced by STA.cpp
*/
public int threadID;
/**
* constructor for STA
*/
public STA() {
start(); // start the thread
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
public void run() {
// init COM
ComThread.InitSTA();
if (OnInit()) {
// this call blocks in the win32 message loop
// until quitMessagePump is called
doMessagePump();
}
OnQuit();
// uninit COM
ComThread.Release();
}
/**
* Override this method to create and initialize any COM component that you
* want to run in this thread. If anything fails, return false to terminate
* the thread.
*
* @return always returns true
*/
public boolean OnInit() {
return true;
}
/**
* Override this method to destroy any resource before the thread exits and
* COM in uninitialized
*/
public void OnQuit() {
// there is nothing to see here
}
/**
* calls quitMessagePump
*/
public void quit() {
quitMessagePump();
}
/**
* run a message pump for the main STA
*/
public native void doMessagePump();
/**
* quit message pump for the main STA
*/
public native void quitMessagePump();
/**
* STA isn't a subclass of JacobObject so a reference to it doesn't load the
* DLL without this
*/
static {
LibraryLoader.loadJacobLibrary();
}
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More