diff --git a/CHANGES.md b/CHANGES.md index 0b24787574..a3b868fc18 100755 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,15 @@ Next Release (3.5.2) Features -------- +[#163] +* Now the java guid structure can be used directly as alternative to +'Ole32Util.getGUIDFromString()'. @wolftobias +* The listening for usb devices is now working also with filter usage. @wolftobias +* Extension for listening to windows devices (usb). @wolftobias +* Code extension for creating and registering win32 native windows. @wolftobias +* Create new code for registering new win32 window classes and created a window +demo. Listening for win32 window events. Listening for logoff/logon events. @wolftobias +* Created new api for 'Wtsapi32.dll'. @wolftobias Bug Fixes --------- diff --git a/contrib/native_window_msg/.classpath b/contrib/native_window_msg/.classpath new file mode 100644 index 0000000000..a7dee2db96 --- /dev/null +++ b/contrib/native_window_msg/.classpath @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/contrib/native_window_msg/.project b/contrib/native_window_msg/.project new file mode 100644 index 0000000000..58da354f1a --- /dev/null +++ b/contrib/native_window_msg/.project @@ -0,0 +1,17 @@ + + + native_window_msg + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/contrib/native_window_msg/src/com/sun/jna/platform/win32/Win32WindowDemo.java b/contrib/native_window_msg/src/com/sun/jna/platform/win32/Win32WindowDemo.java new file mode 100644 index 0000000000..a49e8bbeaa --- /dev/null +++ b/contrib/native_window_msg/src/com/sun/jna/platform/win32/Win32WindowDemo.java @@ -0,0 +1,313 @@ +/* Copyright (c) 2012 Tobias Wolf, All Rights Reserved + * + * 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. + */ + +package com.sun.jna.platform.win32; + +import com.sun.jna.WString; +import com.sun.jna.platform.win32.DBT; +import com.sun.jna.platform.win32.DBT.DEV_BROADCAST_DEVICEINTERFACE; +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.User32; +import com.sun.jna.platform.win32.WinDef.HMODULE; +import com.sun.jna.platform.win32.WinDef.HWND; +import com.sun.jna.platform.win32.WinDef.LPARAM; +import com.sun.jna.platform.win32.WinDef.LRESULT; +import com.sun.jna.platform.win32.WinDef.WPARAM; +import com.sun.jna.platform.win32.WinUser; +import com.sun.jna.platform.win32.WinUser.HDEVNOTIFY; +import com.sun.jna.platform.win32.WinUser.MSG; +import com.sun.jna.platform.win32.WinUser.WNDCLASSEX; +import com.sun.jna.platform.win32.WinUser.WindowProc; +import com.sun.jna.platform.win32.Wtsapi32; + +// TODO: Auto-generated Javadoc +/** + * The Class Win32WindowTest. + */ +public class Win32WindowDemo implements WindowProc { + + /** + * Instantiates a new win32 window test. + */ + public Win32WindowDemo() { + // define new window class + WString windowClass = new WString("MyWindowClass"); + HMODULE hInst = Kernel32.INSTANCE.GetModuleHandle(""); + + WNDCLASSEX wClass = new WNDCLASSEX(); + wClass.hInstance = hInst; + wClass.lpfnWndProc = Win32WindowDemo.this; + wClass.lpszClassName = windowClass; + + // register window class + User32.INSTANCE.RegisterClassEx(wClass); + getLastError(); + + // create new window + HWND hWnd = User32.INSTANCE + .CreateWindowEx( + User32.WS_EX_TOPMOST, + windowClass, + "My hidden helper window, used only to catch the windows events", + 0, 0, 0, 0, 0, WinUser.HWND_MESSAGE, null, hInst, null); + + getLastError(); + System.out.println("window sucessfully created! window hwnd: " + + hWnd.getPointer().toString()); + + Wtsapi32.INSTANCE.WTSRegisterSessionNotification(hWnd, + Wtsapi32.NOTIFY_FOR_THIS_SESSION); + + /* this filters for all device classes */ + // DEV_BROADCAST_HDR notificationFilter = new DEV_BROADCAST_HDR(); + // notificationFilter.dbch_devicetype = DBT.DBT_DEVTYP_DEVICEINTERFACE; + + /* this filters for all usb device classes */ + DEV_BROADCAST_DEVICEINTERFACE notificationFilter = new DEV_BROADCAST_DEVICEINTERFACE(); + notificationFilter.dbcc_devicetype = DBT.DBT_DEVTYP_DEVICEINTERFACE; + notificationFilter.dbcc_classguid = DBT.GUID_DEVINTERFACE_USB_DEVICE; + + /* + * use User32.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES instead of + * DEVICE_NOTIFY_WINDOW_HANDLE to ignore the dbcc_classguid value + */ + HDEVNOTIFY hDevNotify = User32.INSTANCE.RegisterDeviceNotification( + hWnd, notificationFilter, User32.DEVICE_NOTIFY_WINDOW_HANDLE); + + getLastError(); + if (hDevNotify != null) + System.out.println("RegisterDeviceNotification was sucessfully!"); + + MSG msg = new MSG(); + while (User32.INSTANCE.GetMessage(msg, hWnd, 0, 0) != 0) { + User32.INSTANCE.TranslateMessage(msg); + User32.INSTANCE.DispatchMessage(msg); + } + + User32.INSTANCE.UnregisterDeviceNotification(hDevNotify); + Wtsapi32.INSTANCE.WTSUnRegisterSessionNotification(hWnd); + User32.INSTANCE.UnregisterClass(windowClass, hInst); + User32.INSTANCE.DestroyWindow(hWnd); + + System.out.println("program exit!"); + } + + /* + * (non-Javadoc) + * + * @see + * com.sun.jna.platform.win32.User32.WindowProc#callback(com.sun.jna.platform + * .win32.WinDef.HWND, int, com.sun.jna.platform.win32.WinDef.WPARAM, + * com.sun.jna.platform.win32.WinDef.LPARAM) + */ + public LRESULT callback(HWND hwnd, int uMsg, WPARAM wParam, LPARAM lParam) { + switch (uMsg) { + case WinUser.WM_CREATE: { + onCreate(wParam, lParam); + return new LRESULT(0); + } + case WinUser.WM_DESTROY: { + User32.INSTANCE.PostQuitMessage(0); + return new LRESULT(0); + } + case WinUser.WM_SESSION_CHANGE: { + this.onSessionChange(wParam, lParam); + return new LRESULT(0); + } + case WinUser.WM_DEVICECHANGE: { + this.onDeviceChange(wParam, lParam); + return new LRESULT(0); + } + default: + return User32.INSTANCE.DefWindowProc(hwnd, uMsg, wParam, lParam); + } + } + + /** + * Gets the last error. + * + * @return the last error + */ + public int getLastError() { + int rc = Kernel32.INSTANCE.GetLastError(); + + if (rc != 0) + System.out.println("error: " + rc); + + return rc; + } + + /** + * On session change. + * + * @param wParam + * the w param + * @param lParam + * the l param + */ + protected void onSessionChange(WPARAM wParam, LPARAM lParam) { + switch (wParam.intValue()) { + case Wtsapi32.WTS_CONSOLE_CONNECT: { + this.onConsoleConnect(lParam.intValue()); + break; + } + case Wtsapi32.WTS_CONSOLE_DISCONNECT: { + this.onConsoleDisconnect(lParam.intValue()); + break; + } + case Wtsapi32.WTS_SESSION_LOGON: { + this.onMachineLogon(lParam.intValue()); + break; + } + case Wtsapi32.WTS_SESSION_LOGOFF: { + this.onMachineLogoff(lParam.intValue()); + break; + } + case Wtsapi32.WTS_SESSION_LOCK: { + this.onMachineLocked(lParam.intValue()); + break; + } + case Wtsapi32.WTS_SESSION_UNLOCK: { + this.onMachineUnlocked(lParam.intValue()); + break; + } + } + } + + /** + * On console connect. + * + * @param sessionId + * the session id + */ + protected void onConsoleConnect(int sessionId) { + System.out.println("onConsoleConnect: " + sessionId); + } + + /** + * On console disconnect. + * + * @param sessionId + * the session id + */ + protected void onConsoleDisconnect(int sessionId) { + System.out.println("onConsoleDisconnect: " + sessionId); + } + + /** + * On machine locked. + * + * @param sessionId + * the session id + */ + protected void onMachineLocked(int sessionId) { + System.out.println("onMachineLocked: " + sessionId); + } + + /** + * On machine unlocked. + * + * @param sessionId + * the session id + */ + protected void onMachineUnlocked(int sessionId) { + System.out.println("onMachineUnlocked: " + sessionId); + } + + /** + * On machine logon. + * + * @param sessionId + * the session id + */ + protected void onMachineLogon(int sessionId) { + System.out.println("onMachineLogon: " + sessionId); + } + + /** + * On machine logoff. + * + * @param sessionId + * the session id + */ + protected void onMachineLogoff(int sessionId) { + System.out.println("onMachineLogoff: " + sessionId); + } + + /** + * On device change. + * + * @param wParam + * the w param + * @param lParam + * the l param + */ + protected void onDeviceChange(WPARAM wParam, LPARAM lParam) { + // + // This is the actual message from the interface via Windows messaging. + // This code includes some additional decoding for this particular + // device type + // and some common validation checks. + // + // Note that not all devices utilize these optional parameters in the + // same + // way. Refer to the extended information for your particular device + // type + // specified by your GUID. + // + DEV_BROADCAST_DEVICEINTERFACE bdif = new DEV_BROADCAST_DEVICEINTERFACE( + lParam.longValue()); + System.out.println("dbcc_devicetype: " + bdif.dbcc_devicetype); + System.out.println("dbcc_name: " + bdif.getDbcc_name()); + System.out.println("dbcc_classguid: " + + bdif.dbcc_classguid.toGuidString()); + + // Output some messages to the window. + switch (wParam.intValue()) { + case DBT.DBT_DEVICEARRIVAL: + System.out.println("Message DBT_DEVICEARRIVAL"); + break; + case DBT.DBT_DEVICEREMOVECOMPLETE: + System.out.println("Message DBT_DEVICEREMOVECOMPLETE"); + break; + case DBT.DBT_DEVNODES_CHANGED: + System.out.println("Message DBT_DEVNODES_CHANGED"); + break; + default: + System.out + .println("Message WM_DEVICECHANGE message received, value unhandled."); + } + } + + /** + * On create. + * + * @param wParam + * the w param + * @param lParam + * the l param + */ + protected void onCreate(WPARAM wParam, LPARAM lParam) { + System.out.println("onCreate: WM_CREATE"); + } + + /** + * The main method. + * + * @param args + * the arguments + */ + public static void main(String[] args) { + new Win32WindowDemo(); + } +} diff --git a/contrib/platform/src/com/sun/jna/platform/win32/DBT.java b/contrib/platform/src/com/sun/jna/platform/win32/DBT.java new file mode 100644 index 0000000000..608189a912 --- /dev/null +++ b/contrib/platform/src/com/sun/jna/platform/win32/DBT.java @@ -0,0 +1,519 @@ +package com.sun.jna.platform.win32; + +import java.util.Arrays; +import java.util.List; + +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.Structure; +import com.sun.jna.platform.win32.Guid.GUID; +import com.sun.jna.platform.win32.WinDef.LONG; +import com.sun.jna.platform.win32.WinNT.HANDLE; +import com.sun.jna.platform.win32.WinUser.HDEVNOTIFY; +import com.sun.jna.win32.StdCallLibrary; + +// TODO: Auto-generated Javadoc +/** + * Based on dbt.h (various types) + * + * @author Tobias Wolf, wolf.tobias@gmx.net + */ +@SuppressWarnings("serial") +public interface DBT extends StdCallLibrary { + + /** The dbt no disk space. */ + int DBT_NO_DISK_SPACE = 0x0047; + + /** The dbt low disk space. */ + int DBT_LOW_DISK_SPACE = 0x0048; + + /** The dbt configmgprivate. */ + int DBT_CONFIGMGPRIVATE = 0x7FFF; + + /** The dbt devicearrival. */ + int DBT_DEVICEARRIVAL = 0x8000; + + /** The dbt devicequeryremove. */ + int DBT_DEVICEQUERYREMOVE = 0x8001; + + /** The dbt devicequeryremovefailed. */ + int DBT_DEVICEQUERYREMOVEFAILED = 0x8002; + + /** The dbt deviceremovepending. */ + int DBT_DEVICEREMOVEPENDING = 0x8003; + + /** The dbt deviceremovecomplete. */ + int DBT_DEVICEREMOVECOMPLETE = 0x8004; + + /** A device has been added to or removed from the system. */ + int DBT_DEVNODES_CHANGED = 0x0007; + + /** The dbt devicetypespecific. */ + int DBT_DEVICETYPESPECIFIC = 0x8005; + + /** The dbt customevent. */ + int DBT_CUSTOMEVENT = 0x8006; + + /** The guid devinterface usb device. */ + public GUID GUID_DEVINTERFACE_USB_DEVICE = new GUID( + "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"); + + /** The guid devinterface hid. */ + public GUID GUID_DEVINTERFACE_HID = new GUID( + "{4D1E55B2-F16F-11CF-88CB-001111000030}"); + + /** The guid devinterface volume. */ + public GUID GUID_DEVINTERFACE_VOLUME = new GUID( + "{53F5630D-B6BF-11D0-94F2-00A0C91EFB8B}"); + + /** The guid devinterface keyboard. */ + public GUID GUID_DEVINTERFACE_KEYBOARD = new GUID( + "{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"); + + /** The guid devinterface mouse. */ + public GUID GUID_DEVINTERFACE_MOUSE = new GUID( + "{378DE44C-56EF-11D1-BC8C-00A0C91405DD}"); + + /** + * The Class DEV_BROADCAST_HDR. + */ + public class DEV_BROADCAST_HDR extends Structure { + + /** The dbch_size. */ + public int dbch_size = size(); + + /** The dbch_devicetype. */ + public int dbch_devicetype; + + /** The dbch_reserved. */ + public int dbch_reserved; + + /** + * Instantiates a new dev broadcast hdr. + */ + public DEV_BROADCAST_HDR() { + } + + /** + * Instantiates a new dev broadcast hdr. + * + * @param pointer + * the pointer + */ + public DEV_BROADCAST_HDR(long pointer) { + this(new Pointer(pointer)); + } + + /** + * Instantiates a new dev broadcast hdr. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_HDR(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbch_size", "dbch_devicetype", + "dbch_reserved" }); + } + } + + /** The dbt devtyp oem. */ + int DBT_DEVTYP_OEM = 0x00000000; + + /** The dbt devtyp devnode. */ + int DBT_DEVTYP_DEVNODE = 0x00000001; + + /** The dbt devtyp volume. */ + int DBT_DEVTYP_VOLUME = 0x00000002; + + /** The dbt devtyp port. */ + int DBT_DEVTYP_PORT = 0x00000003; + + /** The dbt devtyp net. */ + int DBT_DEVTYP_NET = 0x00000004; + + /** The dbt devtyp deviceinterface. */ + int DBT_DEVTYP_DEVICEINTERFACE = 0x00000005; + + /** The dbt devtyp handle. */ + int DBT_DEVTYP_HANDLE = 0x00000006; + + /** + * The Class DEV_BROADCAST_OEM. + */ + public class DEV_BROADCAST_OEM extends Structure { + + /** The dbco_size. */ + public int dbco_size = size(); + + /** The dbco_devicetype. */ + public int dbco_devicetype; + + /** The dbco_reserved. */ + public int dbco_reserved; + + /** The dbco_identifier. */ + public int dbco_identifier; + + /** The dbco_suppfunc. */ + public int dbco_suppfunc; + + /** + * Instantiates a new dev broadcast oem. + */ + public DEV_BROADCAST_OEM() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast oem. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_OEM(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbco_size", "dbco_devicetype", + "dbco_reserved", "dbco_identifier", "dbco_suppfunc" }); + } + } + + /** + * The Class DEV_BROADCAST_DEVNODE. + */ + public class DEV_BROADCAST_DEVNODE extends Structure { + + /** The dbcd_size. */ + public int dbcd_size = size(); + + /** The dbcd_devicetype. */ + public int dbcd_devicetype; + + /** The dbcd_reserved. */ + public int dbcd_reserved; + + /** The dbcd_devnode. */ + public int dbcd_devnode; + + /** + * Instantiates a new dev broadcast devnode. + */ + public DEV_BROADCAST_DEVNODE() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast devnode. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_DEVNODE(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbcd_size", "dbcd_devicetype", + "dbcd_reserved", "dbcd_devnode" }); + } + } + + /** + * The Class DEV_BROADCAST_VOLUME. + */ + public class DEV_BROADCAST_VOLUME extends Structure { + + /** The dbcv_size. */ + public int dbcv_size = size(); + + /** The dbcv_devicetype. */ + public int dbcv_devicetype; + + /** The dbcv_reserved. */ + public int dbcv_reserved; + + /** The dbcv_unitmask. */ + public int dbcv_unitmask; + + /** The dbcv_flags. */ + public short dbcv_flags; + + /** + * Instantiates a new dev broadcast volume. + */ + public DEV_BROADCAST_VOLUME() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast volume. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_VOLUME(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbcv_size", "dbcv_devicetype", + "dbcv_reserved", "dbcv_unitmask", "dbcv_flags" }); + } + } + + /** + * The Class DEV_BROADCAST_PORT. + */ + public class DEV_BROADCAST_PORT extends Structure { + + /** The dbcp_size. */ + public int dbcp_size = size(); + + /** The dbcp_devicetype. */ + public int dbcp_devicetype; + + /** The dbcp_reserved. */ + public int dbcp_reserved; + + /** The dbcp_name. */ + public char[] dbcp_name = new char[1]; + + /** + * Instantiates a new dev broadcast port. + */ + public DEV_BROADCAST_PORT() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast port. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_PORT(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbcp_size", "dbcp_devicetype", + "dbcp_reserved", "dbcp_name" }); + } + } + + /** + * The Class DEV_BROADCAST_NET. + */ + public class DEV_BROADCAST_NET extends Structure { + + /** The dbcn_size. */ + public int dbcn_size = size(); + + /** The dbcn_devicetype. */ + public int dbcn_devicetype; + + /** The dbcn_reserved. */ + public int dbcn_reserved; + + /** The dbcn_resource. */ + public int dbcn_resource; + + /** The dbcn_flags. */ + public int dbcn_flags; + + /** + * Instantiates a new dev broadcast net. + */ + public DEV_BROADCAST_NET() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast net. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_NET(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbcn_size", "dbcn_devicetype", + "dbcn_reserved", "dbcn_resource", "dbcn_flags" }); + } + } + + /** + * The Class DEV_BROADCAST_DEVICEINTERFACE. + */ + public class DEV_BROADCAST_DEVICEINTERFACE extends Structure { + + /** The dbcc_size. */ + public int dbcc_size; + + /** The dbcc_devicetype. */ + public int dbcc_devicetype; + + /** The dbcc_reserved. */ + public int dbcc_reserved; + + /** The dbcc_classguid. */ + public GUID dbcc_classguid; + + /** The dbcc_name. */ + public char[] dbcc_name = new char[1]; + + /** + * Instantiates a new dev broadcast deviceinterface. + */ + public DEV_BROADCAST_DEVICEINTERFACE() { + // TODO Auto-generated constructor stub + } + + /** + * Dev broadcast hdr. + * + * @param pointer + * the pointer + */ + public DEV_BROADCAST_DEVICEINTERFACE(long pointer) { + this(new Pointer(pointer)); + } + + /** + * Instantiates a new dev broadcast deviceinterface. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_DEVICEINTERFACE(Pointer memory) { + super(memory); + this.dbcc_size = (Integer) this.readField("dbcc_size"); + // figure out how long dbcc_name should be based on the size + int len = 1 + this.dbcc_size - size(); + this.dbcc_name = new char[len]; + read(); + } + + /** + * Gets the dbcc_name. + * + * @return the dbcc_name + */ + public String getDbcc_name() { + return Native.toString(this.dbcc_name); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbcc_size", "dbcc_devicetype", + "dbcc_reserved", "dbcc_classguid", "dbcc_name" }); + } + } + + /** + * The Class DEV_BROADCAST_HANDLE. + */ + public class DEV_BROADCAST_HANDLE extends Structure { + + /** The dbch_size. */ + public int dbch_size = size(); + + /** The dbch_devicetype. */ + public int dbch_devicetype; + + /** The dbch_reserved. */ + public int dbch_reserved; + + /** The dbch_handle. */ + public HANDLE dbch_handle; + + /** The dbch_hdevnotify. */ + public HDEVNOTIFY dbch_hdevnotify; + + /** The dbch_eventguid. */ + public GUID dbch_eventguid; + + /** The dbch_nameoffset. */ + public LONG dbch_nameoffset; + + /** The dbch_data. */ + public byte[] dbch_data; + + /** + * Instantiates a new dev broadcast handle. + */ + public DEV_BROADCAST_HANDLE() { + // TODO Auto-generated constructor stub + } + + /** + * Instantiates a new dev broadcast handle. + * + * @param memory + * the memory + */ + public DEV_BROADCAST_HANDLE(Pointer memory) { + super(memory); + read(); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dbch_size", "dbch_devicetype", + "dbch_reserved", "dbch_handle", "dbch_hdevnotify", + "dbch_eventguid", "dbch_nameoffset", "dbch_data" }); + } + } +} diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Guid.java b/contrib/platform/src/com/sun/jna/platform/win32/Guid.java index a00ca9798b..6c04a2f386 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/Guid.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/Guid.java @@ -1,100 +1,356 @@ /* Copyright (c) 2010 Daniel Doubrovkine, All Rights Reserved - * + * * 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. + * Lesser General Public License for more details. */ package com.sun.jna.platform.win32; +import java.security.SecureRandom; import java.util.Arrays; import java.util.List; import com.sun.jna.Pointer; import com.sun.jna.Structure; +// TODO: Auto-generated Javadoc /** - * Ported from Guid.h. - * Microsoft Windows SDK 6.0A. + * Ported from Guid.h. Microsoft Windows SDK 6.0A. + * * @author dblock[at]dblock.org */ public interface Guid { - - public static class GUID extends Structure { - - public static class ByReference extends GUID implements Structure.ByReference { - public ByReference() { - } - - public ByReference(GUID guid) { - super(guid.getPointer()); - - Data1 = guid.Data1; - Data2 = guid.Data2; - Data3 = guid.Data3; - Data4 = guid.Data4; - } - - public ByReference(Pointer memory) { - super(memory); - } - } - - public GUID() { - - } - - public GUID(Pointer memory) { - super(memory); - read(); - } - - public GUID(byte[] data) { - if (data.length != 16) { - throw new IllegalArgumentException("Invalid data length: " + data.length); - } - - long data1Temp = data[3] & 0xff; - data1Temp <<= 8; - data1Temp |= data[2] & 0xff; - data1Temp <<= 8; - data1Temp |= data[1] & 0xff; - data1Temp <<= 8; - data1Temp |= data[0] & 0xff; - Data1 = (int) data1Temp; - - int data2Temp = data[5] & 0xff; - data2Temp <<= 8; - data2Temp |= data[4] & 0xff; - Data2 = (short) data2Temp; - - int data3Temp = data[7] & 0xff; - data3Temp <<= 8; - data3Temp |= data[6] & 0xff; - Data3 = (short) data3Temp; - - Data4[0] = data[8]; - Data4[1] = data[9]; - Data4[2] = data[10]; - Data4[3] = data[11]; - Data4[4] = data[12]; - Data4[5] = data[13]; - Data4[6] = data[14]; - Data4[7] = data[15]; - } - - public int Data1; - public short Data2; - public short Data3; - public byte[] Data4 = new byte[8]; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "Data1", "Data2", "Data3", "Data4" }); - } - } + + /** + * The Class GUID. + */ + public static class GUID extends Structure { + + /** + * The Class ByReference. + */ + public static class ByReference extends GUID implements + Structure.ByReference { + + /** + * Instantiates a new by reference. + */ + public ByReference() { + } + + /** + * Instantiates a new by reference. + * + * @param guid + * the guid + */ + public ByReference(GUID guid) { + super(guid.getPointer()); + + Data1 = guid.Data1; + Data2 = guid.Data2; + Data3 = guid.Data3; + Data4 = guid.Data4; + } + + /** + * Instantiates a new by reference. + * + * @param memory + * the memory + */ + public ByReference(Pointer memory) { + super(memory); + } + } + + /** The Data1. */ + public int Data1; + + /** The Data2. */ + public short Data2; + + /** The Data3. */ + public short Data3; + + /** The Data4. */ + public byte[] Data4 = new byte[8]; + + /** + * Instantiates a new guid. + */ + public GUID() { + } + + /** + * Instantiates a new guid. + * + * @param guid + * the guid + */ + public GUID(GUID guid) { + this.Data1 = guid.Data1; + this.Data2 = guid.Data2; + this.Data3 = guid.Data3; + this.Data4 = guid.Data4; + + this.writeFieldsToMemory(); + } + + /** + * Instantiates a new guid. + * + * @param guid + * the guid + */ + public GUID(String guid) { + this(fromString(guid)); + } + + /** + * Instantiates a new guid. + * + * @param data + * the data + */ + public GUID(byte[] data) { + this(fromBinary(data)); + } + + /** + * Instantiates a new guid. + * + * @param memory + * the memory + */ + public GUID(Pointer memory) { + super(memory); + read(); + } + + /** + * From binary. + * + * @param data + * the data + * @return the guid + */ + public static GUID fromBinary(byte[] data) { + if (data.length != 16) { + throw new IllegalArgumentException("Invalid data length: " + + data.length); + } + + GUID newGuid = new GUID(); + long data1Temp = data[0] & 0xff; + data1Temp <<= 8; + data1Temp |= data[1] & 0xff; + data1Temp <<= 8; + data1Temp |= data[2] & 0xff; + data1Temp <<= 8; + data1Temp |= data[3] & 0xff; + newGuid.Data1 = (int) data1Temp; + + int data2Temp = data[4] & 0xff; + data2Temp <<= 8; + data2Temp |= data[5] & 0xff; + newGuid.Data2 = (short) data2Temp; + + int data3Temp = data[6] & 0xff; + data3Temp <<= 8; + data3Temp |= data[7] & 0xff; + newGuid.Data3 = (short) data3Temp; + + newGuid.Data4[0] = data[8]; + newGuid.Data4[1] = data[9]; + newGuid.Data4[2] = data[10]; + newGuid.Data4[3] = data[11]; + newGuid.Data4[4] = data[12]; + newGuid.Data4[5] = data[13]; + newGuid.Data4[6] = data[14]; + newGuid.Data4[7] = data[15]; + + newGuid.writeFieldsToMemory(); + + return newGuid; + } + + /** + * From string. + * + * @param guid + * the guid + * @return the guid + */ + public static GUID fromString(String guid) { + int y = 0; + char[] _cnewguid = new char[32]; + char[] _cguid = guid.toCharArray(); + byte[] bdata = new byte[16]; + GUID newGuid = new GUID(); + + // we not accept a string longer than 38 chars + if (guid.length() > 38) { + throw new IllegalArgumentException("Invalid guid length: " + + guid.length()); + } + + // remove '{', '}' and '-' from guid string + for (int i = 0; i < _cguid.length; i++) { + if ((_cguid[i] != '{') && (_cguid[i] != '-') + && (_cguid[i] != '}')) + _cnewguid[y++] = _cguid[i]; + } + + // convert char to byte + for (int i = 0; i < 32; i += 2) { + bdata[i / 2] = (byte) ((Character.digit(_cnewguid[i], 16) << 4) + + Character.digit(_cnewguid[i + 1], 16) & 0xff); + } + + if (bdata.length != 16) { + throw new IllegalArgumentException("Invalid data length: " + + bdata.length); + } + + long data1Temp = bdata[0] & 0xff; + data1Temp <<= 8; + data1Temp |= bdata[1] & 0xff; + data1Temp <<= 8; + data1Temp |= bdata[2] & 0xff; + data1Temp <<= 8; + data1Temp |= bdata[3] & 0xff; + newGuid.Data1 = (int) data1Temp; + + int data2Temp = bdata[4] & 0xff; + data2Temp <<= 8; + data2Temp |= bdata[5] & 0xff; + newGuid.Data2 = (short) data2Temp; + + int data3Temp = bdata[6] & 0xff; + data3Temp <<= 8; + data3Temp |= bdata[7] & 0xff; + newGuid.Data3 = (short) data3Temp; + + newGuid.Data4[0] = bdata[8]; + newGuid.Data4[1] = bdata[9]; + newGuid.Data4[2] = bdata[10]; + newGuid.Data4[3] = bdata[11]; + newGuid.Data4[4] = bdata[12]; + newGuid.Data4[5] = bdata[13]; + newGuid.Data4[6] = bdata[14]; + newGuid.Data4[7] = bdata[15]; + + newGuid.writeFieldsToMemory(); + + return newGuid; + } + + /** + * Generates a new guid. Code taken from the standard jdk + * implementation (see UUID class). + * + * @param guid + * the guid + * @return the guid + */ + public static GUID newGuid() { + SecureRandom ng = new SecureRandom(); + byte[] randomBytes = new byte[16]; + + ng.nextBytes(randomBytes); + randomBytes[6] &= 0x0f; + randomBytes[6] |= 0x40; + randomBytes[8] &= 0x3f; + randomBytes[8] |= 0x80; + + return new GUID(randomBytes); + } + + /** + * To byte array. + * + * @return the byte[] + */ + public byte[] toByteArray() { + byte[] guid = new byte[16]; + + byte[] bytes1 = new byte[4]; + bytes1[0] = (byte) (Data1 >> 24); + bytes1[1] = (byte) (Data1 >> 16); + bytes1[2] = (byte) (Data1 >> 8); + bytes1[3] = (byte) (Data1 >> 0); + + byte[] bytes2 = new byte[4]; + bytes2[0] = (byte) (Data2 >> 24); + bytes2[1] = (byte) (Data2 >> 16); + bytes2[2] = (byte) (Data2 >> 8); + bytes2[3] = (byte) (Data2 >> 0); + + byte[] bytes3 = new byte[4]; + bytes3[0] = (byte) (Data3 >> 24); + bytes3[1] = (byte) (Data3 >> 16); + bytes3[2] = (byte) (Data3 >> 8); + bytes3[3] = (byte) (Data3 >> 0); + + System.arraycopy(bytes1, 0, guid, 0, 4); + System.arraycopy(bytes2, 2, guid, 4, 2); + System.arraycopy(bytes3, 2, guid, 6, 2); + System.arraycopy(Data4, 0, guid, 8, 8); + + return guid; + } + + /** + * The value of this Guid, formatted as follows: + * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. + * + * @return the string + */ + public String toGuidString() { + final String HEXES = "0123456789ABCDEF"; + byte[] bGuid = toByteArray(); + + final StringBuilder hexStr = new StringBuilder(2 * bGuid.length); + hexStr.append("{"); + + for (int i = 0; i < bGuid.length; i++) { + char ch1 = HEXES.charAt((bGuid[i] & 0xF0) >> 4); + char ch2 = HEXES.charAt(bGuid[i] & 0x0F); + hexStr.append(ch1).append(ch2); + + if ((i == 3) || (i == 5) || (i == 7) || (i == 9)) + hexStr.append("-"); + } + + hexStr.append("}"); + return hexStr.toString(); + } + + /** + * Write fields to backing memory. + */ + protected void writeFieldsToMemory() { + this.writeField("Data1"); + this.writeField("Data2"); + this.writeField("Data3"); + this.writeField("Data4"); + } + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "Data1", "Data2", "Data3", + "Data4" }); + } + } } diff --git a/contrib/platform/src/com/sun/jna/platform/win32/User32.java b/contrib/platform/src/com/sun/jna/platform/win32/User32.java index 57bbf2eabd..f7feaf736e 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/User32.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/User32.java @@ -1,1087 +1,1687 @@ -/* Copyright (c) 2007 Timothy Wall, All Rights Reserved - * - * 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. - */ -package com.sun.jna.platform.win32; - -import com.sun.jna.Native; -import com.sun.jna.Pointer; -import com.sun.jna.platform.win32.BaseTSD.LONG_PTR; -import com.sun.jna.platform.win32.WinNT.HANDLE; -import com.sun.jna.ptr.ByteByReference; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.win32.StdCallLibrary; -import com.sun.jna.win32.W32APIOptions; - -/** - * Provides access to the w32 user32 library. Incomplete implementation to - * support demos. - * - * @author Todd Fast, todd.fast@sun.com - * @author twalljava@dev.java.net - */ -public interface User32 extends StdCallLibrary, WinUser { - - User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, - W32APIOptions.DEFAULT_OPTIONS); - - /** - * This function retrieves a handle to a display device context (DC) for the - * client area of the specified window. The display device context can be - * used in subsequent graphics display interface (GDI) functions to draw in - * the client area of the window. - * @param hWnd - * Handle to the window whose device context is to be retrieved. - * If this value is NULL, GetDC retrieves the device context for - * the entire screen. - * @return - * The handle the device context for the specified window's client - * area indicates success. NULL indicates failure. To get extended - * error information, call GetLastError. - */ - HDC GetDC(HWND hWnd); - - /** - * This function releases a device context (DC), freeing it for use by other - * applications. The effect of ReleaseDC depends on the type of device - * context. - * - * @param hWnd - * Handle to the window whose device context is to be released. - * @param hDC - * Handle to the device context to be released. - * @return - * The return value specifies whether the device context is - * released. 1 indicates that the device context is released. Zero - * indicates that the device context is not released. - */ - int ReleaseDC(HWND hWnd, HDC hDC); - - /** - * This function retrieves the handle to the top-level window whose class name and - * window name match the specified strings. This function does not search child windows. - * @param lpClassName - * Long pointer to a null-terminated string that specifies the class name or is an atom - * that identifies the class-name string. If this parameter is an atom, it must be a - * global atom created by a previous call to the GlobalAddAtom function. The atom, a - * 16-bit value, must be placed in the low-order word of lpClassName; the high-order - * word must be zero. - * @param lpWindowName - * Long pointer to a null-terminated string that specifies the window name (the window's - * title). If this parameter is NULL, all window names match. - * @return - * A handle to the window that has the specified class name and window name indicates - * success. NULL indicates failure. To get extended error information, call GetLastError. - */ - HWND FindWindow(String lpClassName, String lpWindowName); - - /** - * This function retrieves the name of the class to which the specified window belongs. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param lpClassName - * Long pointer to the buffer that is to receive the class name string. - * @param nMaxCount - * Specifies the length, in characters, of the buffer pointed to by the lpClassName - * parameter. The class name string is truncated if it is longer than the buffer. - * @return - * The number of characters copied to the specified buffer indicates success. Zero - * indicates failure. To get extended error information, call GetLastError. - */ - int GetClassName(HWND hWnd, char[] lpClassName, int nMaxCount); - - /** - * Retrieves information about the active window or a specified graphical user - * interface (GUI) thread. - * @param idThread - * Identifies the thread for which information is to be retrieved. To retrieve - * this value, use the GetWindowThreadProcessId function. If this parameter is NULL, - * the function returns information for the foreground thread. - * @param lpgui - * Pointer to a GUITHREADINFO structure that receives information describing the thread. - * Note that you must set GUITHREADINFO.cbSize to sizeof(GUITHREADINFO) before calling this function. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean GetGUIThreadInfo(int idThread, GUITHREADINFO lpgui); - - /** - * The GetWindowInfo function retrieves information about the specified window. - * @param hWnd - * Handle to the window whose information is to be retrieved. - * @param pwi - * Pointer to a WINDOWINFO structure to receive the information. Note that you must set WINDOWINFO.cbSize - * to sizeof(WINDOWINFO) before calling this function. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. - */ - boolean GetWindowInfo(HWND hWnd, WINDOWINFO pwi); - - /** - * This function retrieves the dimensions of the bounding rectangle of the specified window. The - * dimensions are given in screen coordinates that are relative to the upper-left corner of the screen. - * @param hWnd - * Handle to the window. - * @param rect - * Long pointer to a RECT structure that receives the screen coordinates of the upper-left and lower-right - * corners of the window. - * @return - * Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError. - */ - boolean GetWindowRect(HWND hWnd, RECT rect); - - /** - * This function copies the text of the specified window's title bar - if it has one - into a buffer. If - * the specified window is a control, the text of the control is copied. - * @param hWnd - * Handle to the window or control containing the text. - * @param lpString - * Long pointer to the buffer that will receive the text. - * @param nMaxCount - * Specifies the maximum number of characters to copy to the buffer, including the NULL character. - * If the text exceeds this limit, it is truncated. - * @return - * The length, in characters, of the copied string, not including the terminating null character, - * indicates success. Zero indicates that the window has no title bar or text, if the title bar is - * empty, or if the window or control handle is invalid. To get extended error information, call - * GetLastError. This function cannot retrieve the text of an edit control in another application. - */ - int GetWindowText(HWND hWnd, char[] lpString, int nMaxCount); - - /** - * This function retrieves the length, in characters, of the specified window's title bar text - - * if the window has a title bar. If the specified window is a control, the function retrieves the - * length of the text within the control. - * @param hWnd - * Handle to the window or control. - * @return - * The length, in characters, of the text indicates success. Under certain conditions, this value - * may actually be greater than the length of the text. Zero indicates that the window has no text. - * To get extended error information, call GetLastError. - */ - int GetWindowTextLength(HWND hWnd); - - /** - * The GetWindowModuleFileName function retrieves the full path and file name of the module associated - * with the specified window handle. - * @param hWnd - * Handle to the window whose module file name will be retrieved. - * @param lpszFileName - * Pointer to a buffer that receives the path and file name. - * @param cchFileNameMax - * Specifies the maximum number of TCHARs that can be copied into the lpszFileName buffer. - * @return - * The return value is the total number of TCHARs copied into the buffer. - */ - int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, - int cchFileNameMax); - - /** - * This function retrieves the identifier of the thread that created the specified window and, optionally, - * the identifier of the process that created the window. - * @param hWnd - * Handle to the window. - * @param lpdwProcessId - * Pointer to a 32-bit value that receives the process identifier. If this parameter is not NULL, - * GetWindowThreadProcessId copies the identifier of the process to the 32-bit value; otherwise, - * it does not. - * @return - * The return value is the identifier of the thread that created the window. - */ - int GetWindowThreadProcessId(HWND hWnd, IntByReference lpdwProcessId); - - /** - * This function enumerates all top-level windows on the screen by passing the handle to each window, - * in turn, to an application-defined callback function. EnumWindows continues until the last top-level - * window is enumerated or the callback function returns FALSE. - * @param lpEnumFunc - * Long pointer to an application-defined callback function. - * @param data - * Specifies an application-defined value to be passed to the callback function. - * @return - * Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError. - */ - boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer data); - - /** - * The EnumChildWindows function enumerates the child windows that belong to the specified parent window - * by passing the handle to each child window, in turn, to an application-defined callback function. - * EnumChildWindows continues until the last child window is enumerated or the callback function returns FALSE. - * @param hWnd - * Handle to the parent window whose child windows are to be enumerated. If this parameter is NULL, this - * function is equivalent to EnumWindows. - * @param lpEnumFunc - * Pointer to an application-defined callback function. - * @param data - * Specifies an application-defined value to be passed to the callback function. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - * If EnumChildProc returns zero, the return value is also zero. In this case, the callback function - * should call SetLastError to obtain a meaningful error code to be returned to the caller of - * EnumChildWindows. - */ - boolean EnumChildWindows(HWND hWnd, WNDENUMPROC lpEnumFunc, Pointer data); - - /** - * The EnumThreadWindows function enumerates all nonchild windows associated with a thread by passing - * the handle to each window, in turn, to an application-defined callback function. EnumThreadWindows - * continues until the last window is enumerated or the callback function returns FALSE. To enumerate - * child windows of a particular window, use the EnumChildWindows function. - * @param dwThreadId - * Identifies the thread whose windows are to be enumerated. - * @param lpEnumFunc - * Pointer to an application-defined callback function. - * @param data - * Specifies an application-defined value to be passed to the callback function. - * @return - * If the callback function returns TRUE for all windows in the thread specified by dwThreadId, the - * return value is TRUE. If the callback function returns FALSE on any enumerated window, or if there - * are no windows found in the thread specified by dwThreadId, the return value is FALSE. - */ - boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, - Pointer data); - - /** - * The FlashWindowEx function flashes the specified window. It does not change the active state of the window. - * @param pfwi - * Pointer to the FLASHWINFO structure. - * @return - * The return value specifies the window's state before the call to the FlashWindowEx function. If the window - * caption was drawn as active before the call, the return value is nonzero. Otherwise, the return value is zero. - */ - boolean FlashWindowEx(FLASHWINFO pfwi); - - /** - * This function loads the specified icon resource from the executable (.exe) file associated with an - * application instance. - * @param hInstance - * Handle to an instance of the module whose executable file contains the icon to be loaded. - * This parameter must be NULL when a standard icon is being loaded. - * @param iconName - * Long pointer to a null-terminated string that contains the name of the icon resource to be loaded. - * Alternatively, this parameter can contain the resource identifier in the low-order word and zero - * in the high-order word. Use the MAKEINTRESOURCE macro to create this value. - * @return - * A handle to the newly loaded icon indicates success. NULL indicates failure. To get extended - * error information, call GetLastError. - */ - HICON LoadIcon(HINSTANCE hInstance, String iconName); - - /** - * This function loads an icon, cursor, or bitmap. - * @param hinst - * Handle to an instance of the module that contains the image to be loaded. - * @param name - * Pointer to a null-terminated string that contains the name of the image resource - * in the hinst module that identifies the image to load. - * @param type - * Specifies the type of image to be loaded. - * @param xDesired - * Specifies the width, in pixels, of the icon or cursor. If this parameter is zero, the function uses - * the SM_CXICON or SM_CXCURSOR system metric value to set the width. If uType is IMAGE_BITMAP, this - * parameter must be zero. - * @param yDesired - * Specifies the height, in pixels, of the icon or cursor. If this parameter is zero, the function uses - * the SM_CYICON or SM_CYCURSOR system metric value to set the height. If uType is IMAGE_BITMAP, this - * parameter must be zero. - * @param load - * Set to zero. - * @return - * The handle of the newly loaded image indicates success. NULL indicates failure. To get extended error information, call GetLastError. - */ - HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, - int yDesired, int load); - - /** - * This function destroys an icon and frees any memory the icon occupied. - * @param hicon - * Handle to the icon to be destroyed. The icon must not be in use. - * @return - * Nonzero indicates success. Zero indicates failure. To get extended error information, call GetLastError. - */ - boolean DestroyIcon(HICON hicon); - - /** - * This function retrieves information about the specified window. GetWindowLong also retrieves - * the 32-bit (long) value at the specified offset into the extra window memory of a window. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be retrieved. - * @return - * The requested 32-bit value indicates success. Zero indicates failure. To get extended error - * information, call GetLastError. - */ - int GetWindowLong(HWND hWnd, int nIndex); - - /** - * This function changes an attribute of the specified window. SetWindowLong also sets a 32-bit (LONG) - * value at the specified offset into the extra window memory of a window. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLong - * Specifies the replacement value. - * @return - * The previous value of the specified 32-bit integer indicates success. Zero indicates failure. - * To get extended error information, call GetLastError. - */ - int SetWindowLong(HWND hWnd, int nIndex, int dwNewLong); - - /** - * This function changes an attribute of the specified window. SetWindowLong also sets a - * 32-bit (LONG) value at the specified offset into the extra window memory of a window. - * Do not use this version on Windows-64. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLong - * Specifies the replacement value. - * @return - * The previous value of the specified 32-bit integer indicates success. Zero indicates failure. - * To get extended error information, call GetLastError. - */ - Pointer SetWindowLong(HWND hWnd, int nIndex, Pointer dwNewLong); - - /** - * The GetWindowLongPtr function retrieves information about the specified window. - * The function also retrieves the value at a specified offset into the extra window memory. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be retrieved. - * @return - * If the function succeeds, the return value is the requested value. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - * If SetWindowLong or SetWindowLongPtr has not been called previously, GetWindowLongPtr returns zero for - * values in the extra window or class memory. - */ - LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); - - /** - * The SetWindowLongPtr function changes an attribute of the specified window. The function also - * sets a value at the specified offset in the extra window memory. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLongPtr - * Specifies the replacement value. - * @return - * If the function succeeds, the return value is the previous value of the specified offset. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - * If the previous value is zero and the function succeeds, the return value is zero, but the function - * does not clear the last error information. To determine success or failure, clear the last error - * information by calling SetLastError(0), then call SetWindowLongPtr. Function failure will be indicated - * by a return value of zero and a GetLastError result that is nonzero. - */ - LONG_PTR SetWindowLongPtr(HWND hWnd, int nIndex, LONG_PTR dwNewLongPtr); - - /** - * The SetWindowLongPtr function changes an attribute of the specified window. The function also - * sets a value at the specified offset in the extra window memory. - * @param hWnd - * Handle to the window and, indirectly, the class to which the window belongs. - * @param nIndex - * Specifies the zero-based offset to the value to be set. - * @param dwNewLongPtr - * Specifies the replacement value. - * @return - * If the function succeeds, the return value is the previous value of the specified offset. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - * If the previous value is zero and the function succeeds, the return value is zero, but the function - * does not clear the last error information. To determine success or failure, clear the last error - * information by calling SetLastError(0), then call SetWindowLongPtr. Function failure will be indicated - * by a return value of zero and a GetLastError result that is nonzero. - */ - Pointer SetWindowLongPtr(HWND hWnd, int nIndex, Pointer dwNewLongPtr); - - /** - * The SetLayeredWindowAttributes function sets the opacity and transparency color key of a layered window. - * @param hwnd - * Handle to the layered window. - * @param crKey - * COLORREF structure that specifies the transparency color key to be used when composing the layered window. - * @param bAlpha - * Alpha value used to describe the opacity of the layered window. - * @param dwFlags - * Specifies an action to take. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean SetLayeredWindowAttributes(HWND hwnd, int crKey, byte bAlpha, - int dwFlags); - - /** - * The GetLayeredWindowAttributes function retrieves the opacity and transparency color - * key of a layered window. - * @param hwnd - * Handle to the layered window. A layered window is created by specifying WS_EX_LAYERED - * when creating the window with the CreateWindowEx function or by setting WS_EX_LAYERED - * via SetWindowLong after the window has been created. - * @param pcrKey - * Pointer to a COLORREF value that receives the transparency color key to be used when - * composing the layered window. All pixels painted by the window in this color will be - * transparent. This can be NULL if the argument is not needed. - * @param pbAlpha - * Pointer to a BYTE that receives the Alpha value used to describe the opacity of the - * layered window. Similar to the SourceConstantAlpha member of the BLENDFUNCTION structure. - * When the variable referred to by pbAlpha is 0, the window is completely transparent. - * When the variable referred to by pbAlpha is 255, the window is opaque. This can be NULL - * if the argument is not needed. - * @param pdwFlags - * Pointer to a DWORD that receives a layering flag. This can be NULL if the argument is not needed. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean GetLayeredWindowAttributes(HWND hwnd, IntByReference pcrKey, - ByteByReference pbAlpha, IntByReference pdwFlags); - - /** - * The UpdateLayeredWindow function updates the position, size, shape, content, and - * translucency of a layered window. - * @param hwnd - * Handle to a layered window. A layered window is created by specifying WS_EX_LAYERED - * when creating the window with the CreateWindowEx function. - * @param hdcDst - * Handle to a device context (DC) for the screen. This handle is obtained by specifying NULL - * when calling the function. It is used for palette color matching when the window contents - * are updated. If hdcDst isNULL, the default palette will be used. If hdcSrc is NULL, hdcDst must be NULL. - * @param pptDst - * Pointer to a POINT structure that specifies the new screen position of the layered window. - * If the current position is not changing, pptDst can be NULL. - * @param psize - * Pointer to a SIZE structure that specifies the new size of the layered window. If the size of the window - * is not changing, psize can be NULL. If hdcSrc is NULL, psize must be NULL. - * @param hdcSrc - * Handle to a DC for the surface that defines the layered window. This handle can be obtained by calling - * the CreateCompatibleDC function. If the shape and visual context of the window are not changing, hdcSrc - * can be NULL. - * @param pptSrc - * Pointer to a POINT structure that specifies the location of the layer in the device context. - * If hdcSrc is NULL, pptSrc should be NULL. - * @param crKey - * Pointer to a COLORREF value that specifies the color key to be used when composing the layered window. - * To generate a COLORREF, use the RGB macro. - * @param pblend - * Pointer to a BLENDFUNCTION structure that specifies the transparency value to be used when composing - * the layered window. - * @param dwFlags - * ULW_* flags. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, - SIZE psize, HDC hdcSrc, POINT pptSrc, int crKey, - BLENDFUNCTION pblend, int dwFlags); - - /** - * This function sets the window region of a window. The window region determines the area within the - * window where the system permits drawing. The system does not display any portion of a window that lies - * outside of the window region. - * @param hWnd - * Handle to the window whose window region is to be set. - * @param hRgn - * Handle to a region. The function sets the window region of the window to this region. - * If hRgn is NULL, the function sets the window region to NULL. - * @param bRedraw - * Specifies whether the system redraws the window after setting the window region. - * If bRedraw is TRUE, the system does so; otherwise, it does not. - * Typically, you set bRedraw to TRUE if the window is visible. - * @return - * Nonzero indicates success. - * Zero indicates failure. - * To get extended error information, call GetLastError. - */ - int SetWindowRgn(HWND hWnd, HRGN hRgn, boolean bRedraw); - - /** - * The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer. - * @param lpKeyState - * Pointer to the 256-byte array that receives the status data for each virtual key. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean GetKeyboardState(byte[] lpKeyState); - - /** - * This function determines whether a key is up or down at the time the function is called, - * and whether the key was pressed after a previous call to GetAsyncKeyState. - * @param vKey - * Specifies one of 256 possible virtual-key codes. - * @return - * If the function succeeds, the return value specifies whether the key was pressed since the last - * call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant - * bit is set, the key is down. - */ - short GetAsyncKeyState(int vKey); - - /** - * The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. - * You would install a hook procedure to monitor the system for certain types of events. These - * events are associated either with a specific thread or with all threads in the same desktop - * as the calling thread. - * @param idHook - * Specifies the type of hook procedure to be installed. - * @param lpfn - * Pointer to the hook procedure. - * @param hMod - * Handle to the DLL containing the hook procedure pointed to by the lpfn parameter. - * @param dwThreadId - * Specifies the identifier of the thread with which the hook procedure is to be associated. - * @return - * If the function succeeds, the return value is the handle to the hook procedure. - * If the function fails, the return value is NULL. To get extended error information, call GetLastError. - */ - HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, - int dwThreadId); - - /** - * The CallNextHookEx function passes the hook information to the next hook procedure - * in the current hook chain. A hook procedure can call this function either before or - * after processing the hook information. - * @param hhk - * Ignored. - * @param nCode - * Specifies the hook code passed to the current hook procedure. The next hook procedure - * uses this code to determine how to process the hook information. - * @param wParam - * Specifies the wParam value passed to the current hook procedure. The meaning of this - * parameter depends on the type of hook associated with the current hook chain. - * @param lParam - * Specifies the lParam value passed to the current hook procedure. The meaning of this - * parameter depends on the type of hook associated with the current hook chain. - * @return - * This value is returned by the next hook procedure in the chain. The current hook procedure - * must also return this value. The meaning of the return value depends on the hook type. - */ - LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, LPARAM lParam); - - /** - * The CallNextHookEx function passes the hook information to the next hook procedure - * in the current hook chain. A hook procedure can call this function either before or - * after processing the hook information. - * @param hhk - * Ignored. - * @param nCode - * Specifies the hook code passed to the current hook procedure. The next hook procedure - * uses this code to determine how to process the hook information. - * @param wParam - * Specifies the wParam value passed to the current hook procedure. The meaning of this - * parameter depends on the type of hook associated with the current hook chain. - * @param lParam - * Specifies the lParam value passed to the current hook procedure. The meaning of this - * parameter depends on the type of hook associated with the current hook chain. - * @return - * This value is returned by the next hook procedure in the chain. The current hook procedure - * must also return this value. The meaning of the return value depends on the hook type. - */ - LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, Pointer lParam); - - /** - * The UnhookWindowsHookEx function removes a hook procedure installed in - * a hook chain by the SetWindowsHookEx function. - * @param hhk - * Handle to the hook to be removed. This parameter is a hook handle obtained - * by a previous call to SetWindowsHookEx. - * @return - * If the function succeeds, the return value is nonzero. - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean UnhookWindowsHookEx(HHOOK hhk); - - /** - * This function retrieves a message from the calling thread's message queue - * and places it in the specified structure. - * @param lpMsg - * Pointer to an MSG structure that receives message information from the thread's message queue. - * @param hWnd - * Handle to the window whose messages are to be retrieved. One value has a special meaning. - * @param wMsgFilterMin - * Specifies the integer value of the lowest message value to be retrieved. - * @param wMsgFilterMax - * Specifies the integer value of the highest message value to be retrieved. - * @return - * Nonzero indicates that the function retrieves a message other than WM_QUIT. Zero indicates - * that the function retrieves the WM_QUIT message, or that lpMsg is an invalid pointer. To - * get extended error information, call GetLastError. - */ - int GetMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, int wMsgFilterMax); - - /** - * This function checks a thread message queue for a message and places the - * message (if any) in the specified structure. - * @param lpMsg - * Pointer to an MSG structure that receives message information. - * @param hWnd - * Handle to the window whose messages are to be examined. - * @param wMsgFilterMin - * Specifies the value of the first message in the range of messages to be examined. - * @param wMsgFilterMax - * Specifies the value of the last message in the range of messages to be examined. - * @param wRemoveMsg - * Specifies how messages are handled. This parameter can be one of the following values. - * @return - * Nonzero indicates success. Zero indicates failure. - */ - boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, - int wMsgFilterMax, int wRemoveMsg); - - /** - * This function translates virtual-key messages into character messages. The character messages - * are posted to the calling thread's message queue, to be read the next time the thread calls the - * GetMessage or PeekMessage function. - * @param lpMsg - * Pointer to an MSG structure that contains message information retrieved from the calling thread's - * message queue by using the GetMessage or PeekMessage function. - * @return - * Nonzero indicates that the message is translated, that is, a character message is posted to the - * thread's message queue. If the message is WM_KEYDOWN or WM_SYSKEYDOWN, the return value is nonzero, - * regardless of the translation. Zero indicates that the message is not translated, that is, a - * character message is not posted to the thread's message queue. - */ - boolean TranslateMessage(MSG lpMsg); - - /** - * This function dispatches a message to a window procedure. It is typically used - * to dispatch a message retrieved by the GetMessage function. - * @param lpMsg - * Pointer to an MSG structure that contains the message. - * @return - * The return value specifies the value returned by the window procedure. Although its meaning - * depends on the message being dispatched, the return value generally is ignored. - */ - LRESULT DispatchMessage(MSG lpMsg); - - /** - * This function places a message in the message queue associated with the thread that - * created the specified window and then returns without waiting for the thread to process - * the message. Messages in a message queue are retrieved by calls to the GetMessage - * or PeekMessage function. - * @param hWnd - * Handle to the window whose window procedure is to receive the message. - * @param msg - * Specifies the message to be posted. - * @param wParam - * Specifies additional message-specific information. - * @param lParam - * Specifies additional message-specific information. - */ - void PostMessage(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam); - - /** - * This function indicates to Windows that a thread has made a request to terminate (quit). - * It is typically used in response to a WM_DESTROY message. - * @param nExitCode - * Specifies an application exit code. This value is used as the wParam parameter of - * the WM_QUIT message. - */ - void PostQuitMessage(int nExitCode); - - /** - * The GetSystemMetrics function retrieves various system metrics (widths - * and heights of display elements) and system configuration settings. All - * dimensions retrieved by GetSystemMetrics are in pixels. - * @param nIndex - * System metric or configuration setting to retrieve. This - * parameter can be one of the following values. Note that all - * SM_CX* values are widths and all SM_CY* values are heights. - * Also note that all settings designed to return Boolean data - * represent TRUE as any nonzero value, and FALSE as a zero - * value. - * @return - * If the function succeeds, the return value is the requested - * system metric or configuration setting. If the function fails, - * the return value is zero. GetLastError does not provide extended - * error information. - */ - public int GetSystemMetrics(int nIndex); - - /** - * Changes the parent window of the specified child window. - * - * @param hWndChild - * A handle to the child window. - * - * @param hWndNewParent - * A handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent - * window. If this parameter is HWND_MESSAGE, the child window becomes a message-only window. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - HWND SetParent(HWND hWndChild, HWND hWndNewParent); - - /** - * Determines the visibility state of the specified window. - * - * @param hWnd - * A handle to the window to be tested. - * - * @return - * If the specified window, its parent window, its parent's parent window, and so forth, have the WS_VISIBLE - * style, the return value is nonzero. Otherwise, the return value is zero. - * - * Because the return value specifies whether the window has the WS_VISIBLE style, it may be nonzero even if the - * window is totally obscured by other windows. - */ - boolean IsWindowVisible(HWND hWnd); - - /** - * Changes the position and dimensions of the specified window. For a top-level window, the position and dimensions - * are relative to the upper-left corner of the screen. For a child window, they are relative to the upper-left - * corner of the parent window's client area. - * - * @param hWnd - * A handle to the window. - * - * @param X - * The new position of the left side of the window. - * - * @param Y - * The new position of the top of the window. - * - * @param nWidth - * The new width of the window. - * - * @param nHeight - * The new height of the window. - * - * @param bRepaint - * Indicates whether the window is to be repainted. If this parameter is TRUE, the window receives a message. If - * the parameter is FALSE, no repainting of any kind occurs. This applies to the client area, the nonclient area - * (including the title bar and scroll bars), and any part of the parent window uncovered as a result of moving - * a child window. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean MoveWindow(HWND hWnd, int X,int Y, int nWidth, int nHeight, boolean bRepaint); - - /** - * Changes the size, position, and Z order of a child, pop-up, or top-level window. These windows are ordered - * according to their appearance on the screen. The topmost window receives the highest rank and is the first window - * in the Z order. - * - * @param hWnd - * A handle to the window. - * - * @param hWndInsertAfter - * A handle to the window to precede the positioned window in the Z order. - * - * @param X - * The new position of the left side of the window, in client coordinates. - * - * @param Y - * The new position of the top of the window, in client coordinates. - * - * @param cx - * The new width of the window, in pixels. - * - * @param cy - * The new height of the window, in pixels. - * - * @param uFlags - * The window sizing and positioning flags. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags); - - /** - * Attaches or detaches the input processing mechanism of one thread to that of another thread. - * - * @param idAttach - * The identifier of the thread to be attached to another thread. The thread to be attached cannot be a system - * thread. - * - * @param idAttachTo - * The identifier of the thread to which idAttach will be attached. This thread cannot be a system thread. A - * thread cannot attach to itself. Therefore, idAttachTo cannot equal idAttach. - * - * @param fAttach - * If this parameter is TRUE, the two threads are attached. If the parameter is FALSE, the threads are detached. - * - * @return - * If the function succeeds, the return value is nonzero. - */ - boolean AttachThreadInput(DWORD idAttach, DWORD idAttachTo, boolean fAttach); - - /** - * Brings the thread that created the specified window into the foreground and activates the window. Keyboard input - * is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher - * priority to the thread that created the foreground window than it does to other threads. - * - * @param hWnd - * A handle to the window that should be activated and brought to the foreground. - * - * @return - * If the window was brought to the foreground, the return value is nonzero. - */ - boolean SetForegroundWindow(HWND hWnd); - - /** - * Retrieves a handle to the foreground window (the window with which the user is currently working). The system - * assigns a slightly higher priority to the thread that creates the foreground window than it does to other - * threads. - * - * @return The return value is a handle to the foreground window. The foreground window can be NULL in certain - * circumstances, such as when a window is losing activation. - */ - HWND GetForegroundWindow(); - - /** - * Sets the keyboard focus to the specified window. The window must be attached to the calling thread's message - * queue. - * - * @param hWnd - * A handle to the window that will receive the keyboard input. If this parameter is NULL, keystrokes are ignored. - * - * @return - * If the function succeeds, the return value is the handle to the window that previously had the keyboard focus. - * If the hWnd parameter is invalid or the window is not attached to the calling thread's message queue, the - * return value is NULL. To get extended error information, call GetLastError. - */ - HWND SetFocus(HWND hWnd); - - /** - * Synthesizes keystrokes, mouse motions, and button clicks. - * - * @param nInputs - * The number of structures in the pInputs array. - * - * @param pInputs - * An array of INPUT structures. Each structure represents an event to be inserted into the keyboard or mouse - * input stream. - * - * @param cbSize - * The size, in bytes, of an INPUT structure. If cbSize is not the size of an INPUT structure, the function fails. - * - * @return - * The function returns the number of events that it successfully inserted into the keyboard or mouse input - * stream. If the function returns zero, the input was already blocked by another thread. To get extended error - * information, call GetLastError. - * - * This function fails when it is blocked by UIPI. Note that neither GetLastError nor the return value will - * indicate the failure was caused by UIPI blocking. - */ - DWORD SendInput(DWORD nInputs, WinUser.INPUT[] pInputs,int cbSize); - - /** - * Waits until the specified process has finished processing its initial input and is waiting for user input with no - * input pending, or until the time-out interval has elapsed. - * - * @param hProcess - * A handle to the process. If this process is a console application or does not have a message queue, - * WaitForInputIdle returns immediately. - * - * @param dwMilliseconds - * The time-out interval, in milliseconds. If dwMilliseconds is INFINITE, the function does not return until the - * process is idle. - * - * @return - * The following table shows the possible return values for this function. - * - * - * - * - * - *
Return code/valueDescription
0The wait was satisfied successfully.
WAIT_TIMEOUTThe wait was terminated because the time-out interval elapsed.
WAIT_FAILEDAn error occurred.
- */ - DWORD WaitForInputIdle(HANDLE hProcess, DWORD dwMilliseconds); - - /** - * The InvalidateRect function adds a rectangle to the specified window's update region. The update region - * represents the portion of the window's client area that must be redrawn. - * - * @param hWnd - * A handle to the window whose update region has changed. If this parameter is NULL, the system invalidates and - * redraws all windows, not just the windows for this application, and sends the WM_ERASEBKGND and WM_NCPAINT - * messages before the function returns. Setting this parameter to NULL is not recommended. - * - * @param lpRect - * A pointer to a RECT structure that contains the client coordinates of the rectangle to be added to the update - * region. If this parameter is NULL, the entire client area is added to the update region. - * - * @param bErase - * Specifies whether the background within the update region is to be erased when the update region is processed. - * If this parameter is TRUE, the background is erased when the BeginPaint function is called. If this parameter - * is FALSE, the background remains unchanged. - * - * @return - * If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. - */ - boolean InvalidateRect(HWND hWnd, RECT.ByReference lpRect, boolean bErase); - - /** - * The RedrawWindow function updates the specified rectangle or region in a window's client area. - * - * @param hWnd - * A handle to the window to be redrawn. If this parameter is NULL, the desktop window is updated. - * - * @param lprcUpdate - * A pointer to a RECT structure containing the coordinates, in device units, of the update rectangle. This - * parameter is ignored if the hrgnUpdate parameter identifies a region. - * - * @param hrgnUpdate - * A handle to the update region. If both the hrgnUpdate and lprcUpdate parameters are NULL, the entire client - * area is added to the update region. - * - * @param flags - * One or more redraw flags. This parameter can be used to invalidate or validate a window, control repainting, - * and control which windows are affected by RedrawWindow. - * - * @return - * If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. - */ - boolean RedrawWindow(HWND hWnd, RECT.ByReference lprcUpdate, HRGN hrgnUpdate, DWORD flags); - - /** - * Retrieves a handle to a window that has the specified relationship (Z-Order or owner) to the specified window. - * - * @param hWnd - * A handle to a window. The window handle retrieved is relative to this window, based on the value of the uCmd - * parameter. - * - * @param uCmd - * The relationship between the specified window and the window whose handle is to be retrieved. - * - * @return - * If the function succeeds, the return value is a window handle. If no window exists with the specified - * relationship to the specified window, the return value is NULL. To get extended error information, call - * GetLastError. - */ - HWND GetWindow(HWND hWnd, DWORD uCmd); - - /** - * The UpdateWindow function updates the client area of the specified window by sending a WM_PAINT message to the - * window if the window's update region is not empty. The function sends a WM_PAINT message directly to the window - * procedure of the specified window, bypassing the application queue. If the update region is empty, no message is - * sent. - * - * @param - * hWnd Handle to the window to be updated. - * - * @return - * If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. - */ - boolean UpdateWindow(HWND hWnd); - - /** - * Sets the specified window's show state. - * - * @param hWnd - * A handle to the window. - * - * @param nCmdShow - * Controls how the window is to be shown. This parameter is ignored the first time an application calls - * ShowWindow, if the program that launched the application provides a STARTUPINFO structure. Otherwise, the - * first time ShowWindow is called, the value should be the value obtained by the WinMain function in its - * nCmdShow parameter. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean ShowWindow(HWND hWnd, int nCmdShow); - - /** - * Minimizes (but does not destroy) the specified window. - * - * @param hWnd - * A handle to the window to be minimized. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. To get extended error information, call GetLastError. - */ - boolean CloseWindow(HWND hWnd); - - /** - * Defines a system-wide hot key. - * - * @param hWnd - * A handle to the window that will receive {@link WinUser#WM_HOTKEY} messages generated by the hot key - * - * @param id - * The identifier of the hot key - * - * @param fsModifiers - * The keys that must be pressed in combination with the key specified by the - * uVirtKey parameter in order to generate the {@link WinUser#WM_HOTKEY} message.
- * A combination of the following values - *

- * @param vk The virtual-key code of the hot key - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. - * To get extended error information, call {@link Kernel32#GetLastError}. - */ - boolean RegisterHotKey(HWND hWnd, int id, int fsModifiers, int vk); - - /** - * Frees a hot key previously registered by the calling thread. - * - * @param hWnd - * A handle to the window associated with the hot key to be freed. This parameter should be NULL if the hot key is not associated with a window. - * - * @param id - * The identifier of the hot key to be freed. - * - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. - * To get extended error information, call {@link Kernel32#GetLastError}. - */ - boolean UnregisterHotKey(Pointer hWnd, int id); - - /** - * Retrieves the time of the last input event. - * - * @param plii - * structure that receives the time of the last input event - * @return - * If the function succeeds, the return value is nonzero. - * - * If the function fails, the return value is zero. - * To get extended error information, call {@link Kernel32#GetLastError}. - */ - boolean GetLastInputInfo(LASTINPUTINFO plii); -} +/* Copyright (c) 2007 Timothy Wall, All Rights Reserved + * + * 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. + */ +package com.sun.jna.platform.win32; + +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.Structure; +import com.sun.jna.WString; +import com.sun.jna.platform.win32.BaseTSD.LONG_PTR; +import com.sun.jna.platform.win32.WinNT.HANDLE; +import com.sun.jna.ptr.ByteByReference; +import com.sun.jna.ptr.IntByReference; +import com.sun.jna.win32.StdCallLibrary; +import com.sun.jna.win32.W32APIOptions; + +// TODO: Auto-generated Javadoc +/** + * Provides access to the w32 user32 library. Incomplete implementation to + * support demos. + * + * @author Todd Fast, todd.fast@sun.com + * @author twalljava@dev.java.net + * @author Tobias Wolf, wolf.tobias@gmx.net + */ +public interface User32 extends StdCallLibrary, WinUser { + + /** The instance. */ + User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class, + W32APIOptions.DEFAULT_OPTIONS); + + /** The cs globalclass. */ + int CS_GLOBALCLASS = 0x4000; + + /** The ws ex topmost. */ + int WS_EX_TOPMOST = 0x00000008; + + /** The ws overlapped. */ + int WS_OVERLAPPED = 0x00000000; + + /** The hRecipient parameter is a window handle. */ + int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000; + + /** The hRecipient parameter is a service status handle. */ + int DEVICE_NOTIFY_SERVICE_HANDLE = 0x00000001; + + /** The device notify all interface classes. */ + int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x00000004; + + /** + * This function retrieves a handle to a display device context (DC) for the + * client area of the specified window. The display device context can be + * used in subsequent graphics display interface (GDI) functions to draw in + * the client area of the window. + * + * @param hWnd + * Handle to the window whose device context is to be retrieved. + * If this value is NULL, GetDC retrieves the device context for + * the entire screen. + * @return The handle the device context for the specified window's client + * area indicates success. NULL indicates failure. To get extended + * error information, call GetLastError. + */ + HDC GetDC(HWND hWnd); + + /** + * This function releases a device context (DC), freeing it for use by other + * applications. The effect of ReleaseDC depends on the type of device + * context. + * + * @param hWnd + * Handle to the window whose device context is to be released. + * @param hDC + * Handle to the device context to be released. + * @return The return value specifies whether the device context is + * released. 1 indicates that the device context is released. Zero + * indicates that the device context is not released. + */ + int ReleaseDC(HWND hWnd, HDC hDC); + + /** + * This function retrieves the handle to the top-level window whose class + * name and window name match the specified strings. This function does not + * search child windows. + * + * @param lpClassName + * Long pointer to a null-terminated string that specifies the + * class name or is an atom that identifies the class-name + * string. If this parameter is an atom, it must be a global atom + * created by a previous call to the GlobalAddAtom function. The + * atom, a 16-bit value, must be placed in the low-order word of + * lpClassName; the high-order word must be zero. + * @param lpWindowName + * Long pointer to a null-terminated string that specifies the + * window name (the window's title). If this parameter is NULL, + * all window names match. + * @return A handle to the window that has the specified class name and + * window name indicates success. NULL indicates failure. To get + * extended error information, call GetLastError. + */ + HWND FindWindow(String lpClassName, String lpWindowName); + + /** + * This function retrieves the name of the class to which the specified + * window belongs. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param lpClassName + * Long pointer to the buffer that is to receive the class name + * string. + * @param nMaxCount + * Specifies the length, in characters, of the buffer pointed to + * by the lpClassName parameter. The class name string is + * truncated if it is longer than the buffer. + * @return The number of characters copied to the specified buffer indicates + * success. Zero indicates failure. To get extended error + * information, call GetLastError. + */ + int GetClassName(HWND hWnd, char[] lpClassName, int nMaxCount); + + /** + * Retrieves information about the active window or a specified graphical + * user interface (GUI) thread. + * + * @param idThread + * Identifies the thread for which information is to be + * retrieved. To retrieve this value, use the + * GetWindowThreadProcessId function. If this parameter is NULL, + * the function returns information for the foreground thread. + * @param lpgui + * Pointer to a GUITHREADINFO structure that receives information + * describing the thread. Note that you must set + * GUITHREADINFO.cbSize to sizeof(GUITHREADINFO) before calling + * this function. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean GetGUIThreadInfo(int idThread, GUITHREADINFO lpgui); + + /** + * The GetWindowInfo function retrieves information about the specified + * window. + * + * @param hWnd + * Handle to the window whose information is to be retrieved. + * @param pwi + * Pointer to a WINDOWINFO structure to receive the information. + * Note that you must set WINDOWINFO.cbSize to sizeof(WINDOWINFO) + * before calling this function. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. + */ + boolean GetWindowInfo(HWND hWnd, WINDOWINFO pwi); + + /** + * This function retrieves the dimensions of the bounding rectangle of the + * specified window. The dimensions are given in screen coordinates that are + * relative to the upper-left corner of the screen. + * + * @param hWnd + * Handle to the window. + * @param rect + * Long pointer to a RECT structure that receives the screen + * coordinates of the upper-left and lower-right corners of the + * window. + * @return Nonzero indicates success. Zero indicates failure. To get + * extended error information, call GetLastError. + */ + boolean GetWindowRect(HWND hWnd, RECT rect); + + /** + * This function copies the text of the specified window's title bar - if it + * has one - into a buffer. If the specified window is a control, the text + * of the control is copied. + * + * @param hWnd + * Handle to the window or control containing the text. + * @param lpString + * Long pointer to the buffer that will receive the text. + * @param nMaxCount + * Specifies the maximum number of characters to copy to the + * buffer, including the NULL character. If the text exceeds this + * limit, it is truncated. + * @return The length, in characters, of the copied string, not including + * the terminating null character, indicates success. Zero indicates + * that the window has no title bar or text, if the title bar is + * empty, or if the window or control handle is invalid. To get + * extended error information, call GetLastError. This function + * cannot retrieve the text of an edit control in another + * application. + */ + int GetWindowText(HWND hWnd, char[] lpString, int nMaxCount); + + /** + * This function retrieves the length, in characters, of the specified + * window's title bar text - if the window has a title bar. If the specified + * window is a control, the function retrieves the length of the text within + * the control. + * + * @param hWnd + * Handle to the window or control. + * @return The length, in characters, of the text indicates success. Under + * certain conditions, this value may actually be greater than the + * length of the text. Zero indicates that the window has no text. + * To get extended error information, call GetLastError. + */ + int GetWindowTextLength(HWND hWnd); + + /** + * The GetWindowModuleFileName function retrieves the full path and file + * name of the module associated with the specified window handle. + * + * @param hWnd + * Handle to the window whose module file name will be retrieved. + * @param lpszFileName + * Pointer to a buffer that receives the path and file name. + * @param cchFileNameMax + * Specifies the maximum number of TCHARs that can be copied into + * the lpszFileName buffer. + * @return The return value is the total number of TCHARs copied into the + * buffer. + */ + int GetWindowModuleFileName(HWND hWnd, char[] lpszFileName, + int cchFileNameMax); + + /** + * This function retrieves the identifier of the thread that created the + * specified window and, optionally, the identifier of the process that + * created the window. + * + * @param hWnd + * Handle to the window. + * @param lpdwProcessId + * Pointer to a 32-bit value that receives the process + * identifier. If this parameter is not NULL, + * GetWindowThreadProcessId copies the identifier of the process + * to the 32-bit value; otherwise, it does not. + * @return The return value is the identifier of the thread that created the + * window. + */ + int GetWindowThreadProcessId(HWND hWnd, IntByReference lpdwProcessId); + + /** + * This function enumerates all top-level windows on the screen by passing + * the handle to each window, in turn, to an application-defined callback + * function. EnumWindows continues until the last top-level window is + * enumerated or the callback function returns FALSE. + * + * @param lpEnumFunc + * Long pointer to an application-defined callback function. + * @param data + * Specifies an application-defined value to be passed to the + * callback function. + * @return Nonzero indicates success. Zero indicates failure. To get + * extended error information, call GetLastError. + */ + boolean EnumWindows(WNDENUMPROC lpEnumFunc, Pointer data); + + /** + * The EnumChildWindows function enumerates the child windows that belong to + * the specified parent window by passing the handle to each child window, + * in turn, to an application-defined callback function. EnumChildWindows + * continues until the last child window is enumerated or the callback + * function returns FALSE. + * + * @param hWnd + * Handle to the parent window whose child windows are to be + * enumerated. If this parameter is NULL, this function is + * equivalent to EnumWindows. + * @param lpEnumFunc + * Pointer to an application-defined callback function. + * @param data + * Specifies an application-defined value to be passed to the + * callback function. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. If EnumChildProc returns zero, + * the return value is also zero. In this case, the callback + * function should call SetLastError to obtain a meaningful error + * code to be returned to the caller of EnumChildWindows. + */ + boolean EnumChildWindows(HWND hWnd, WNDENUMPROC lpEnumFunc, Pointer data); + + /** + * The EnumThreadWindows function enumerates all nonchild windows associated + * with a thread by passing the handle to each window, in turn, to an + * application-defined callback function. EnumThreadWindows continues until + * the last window is enumerated or the callback function returns FALSE. To + * enumerate child windows of a particular window, use the EnumChildWindows + * function. + * + * @param dwThreadId + * Identifies the thread whose windows are to be enumerated. + * @param lpEnumFunc + * Pointer to an application-defined callback function. + * @param data + * Specifies an application-defined value to be passed to the + * callback function. + * @return If the callback function returns TRUE for all windows in the + * thread specified by dwThreadId, the return value is TRUE. If the + * callback function returns FALSE on any enumerated window, or if + * there are no windows found in the thread specified by dwThreadId, + * the return value is FALSE. + */ + boolean EnumThreadWindows(int dwThreadId, WNDENUMPROC lpEnumFunc, + Pointer data); + + /** + * The FlashWindowEx function flashes the specified window. It does not + * change the active state of the window. + * + * @param pfwi + * Pointer to the FLASHWINFO structure. + * @return The return value specifies the window's state before the call to + * the FlashWindowEx function. If the window caption was drawn as + * active before the call, the return value is nonzero. Otherwise, + * the return value is zero. + */ + boolean FlashWindowEx(FLASHWINFO pfwi); + + /** + * This function loads the specified icon resource from the executable + * (.exe) file associated with an application instance. + * + * @param hInstance + * Handle to an instance of the module whose executable file + * contains the icon to be loaded. This parameter must be NULL + * when a standard icon is being loaded. + * @param iconName + * Long pointer to a null-terminated string that contains the + * name of the icon resource to be loaded. Alternatively, this + * parameter can contain the resource identifier in the low-order + * word and zero in the high-order word. Use the MAKEINTRESOURCE + * macro to create this value. + * @return A handle to the newly loaded icon indicates success. NULL + * indicates failure. To get extended error information, call + * GetLastError. + */ + HICON LoadIcon(HINSTANCE hInstance, String iconName); + + /** + * This function loads an icon, cursor, or bitmap. + * + * @param hinst + * Handle to an instance of the module that contains the image to + * be loaded. + * @param name + * Pointer to a null-terminated string that contains the name of + * the image resource in the hinst module that identifies the + * image to load. + * @param type + * Specifies the type of image to be loaded. + * @param xDesired + * Specifies the width, in pixels, of the icon or cursor. If this + * parameter is zero, the function uses the SM_CXICON or + * SM_CXCURSOR system metric value to set the width. If uType is + * IMAGE_BITMAP, this parameter must be zero. + * @param yDesired + * Specifies the height, in pixels, of the icon or cursor. If + * this parameter is zero, the function uses the SM_CYICON or + * SM_CYCURSOR system metric value to set the height. If uType is + * IMAGE_BITMAP, this parameter must be zero. + * @param load + * Set to zero. + * @return The handle of the newly loaded image indicates success. NULL + * indicates failure. To get extended error information, call + * GetLastError. + */ + HANDLE LoadImage(HINSTANCE hinst, String name, int type, int xDesired, + int yDesired, int load); + + /** + * This function destroys an icon and frees any memory the icon occupied. + * + * @param hicon + * Handle to the icon to be destroyed. The icon must not be in + * use. + * @return Nonzero indicates success. Zero indicates failure. To get + * extended error information, call GetLastError. + */ + boolean DestroyIcon(HICON hicon); + + /** + * This function retrieves information about the specified window. + * GetWindowLong also retrieves the 32-bit (long) value at the specified + * offset into the extra window memory of a window. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be retrieved. + * @return The requested 32-bit value indicates success. Zero indicates + * failure. To get extended error information, call GetLastError. + */ + int GetWindowLong(HWND hWnd, int nIndex); + + /** + * This function changes an attribute of the specified window. SetWindowLong + * also sets a 32-bit (LONG) value at the specified offset into the extra + * window memory of a window. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be set. + * @param dwNewLong + * Specifies the replacement value. + * @return The previous value of the specified 32-bit integer indicates + * success. Zero indicates failure. To get extended error + * information, call GetLastError. + */ + int SetWindowLong(HWND hWnd, int nIndex, int dwNewLong); + + /** + * This function changes an attribute of the specified window. SetWindowLong + * also sets a 32-bit (LONG) value at the specified offset into the extra + * window memory of a window. Do not use this version on Windows-64. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be set. + * @param dwNewLong + * Specifies the replacement value. + * @return The previous value of the specified 32-bit integer indicates + * success. Zero indicates failure. To get extended error + * information, call GetLastError. + */ + Pointer SetWindowLong(HWND hWnd, int nIndex, Pointer dwNewLong); + + /** + * The GetWindowLongPtr function retrieves information about the specified + * window. The function also retrieves the value at a specified offset into + * the extra window memory. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be retrieved. + * @return If the function succeeds, the return value is the requested + * value. If the function fails, the return value is zero. To get + * extended error information, call GetLastError. If SetWindowLong + * or SetWindowLongPtr has not been called previously, + * GetWindowLongPtr returns zero for values in the extra window or + * class memory. + */ + LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); + + /** + * The SetWindowLongPtr function changes an attribute of the specified + * window. The function also sets a value at the specified offset in the + * extra window memory. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be set. + * @param dwNewLongPtr + * Specifies the replacement value. + * @return If the function succeeds, the return value is the previous value + * of the specified offset. If the function fails, the return value + * is zero. To get extended error information, call GetLastError. If + * the previous value is zero and the function succeeds, the return + * value is zero, but the function does not clear the last error + * information. To determine success or failure, clear the last + * error information by calling SetLastError(0), then call + * SetWindowLongPtr. Function failure will be indicated by a return + * value of zero and a GetLastError result that is nonzero. + */ + LONG_PTR SetWindowLongPtr(HWND hWnd, int nIndex, LONG_PTR dwNewLongPtr); + + /** + * The SetWindowLongPtr function changes an attribute of the specified + * window. The function also sets a value at the specified offset in the + * extra window memory. + * + * @param hWnd + * Handle to the window and, indirectly, the class to which the + * window belongs. + * @param nIndex + * Specifies the zero-based offset to the value to be set. + * @param dwNewLongPtr + * Specifies the replacement value. + * @return If the function succeeds, the return value is the previous value + * of the specified offset. If the function fails, the return value + * is zero. To get extended error information, call GetLastError. If + * the previous value is zero and the function succeeds, the return + * value is zero, but the function does not clear the last error + * information. To determine success or failure, clear the last + * error information by calling SetLastError(0), then call + * SetWindowLongPtr. Function failure will be indicated by a return + * value of zero and a GetLastError result that is nonzero. + */ + Pointer SetWindowLongPtr(HWND hWnd, int nIndex, Pointer dwNewLongPtr); + + /** + * The SetLayeredWindowAttributes function sets the opacity and transparency + * color key of a layered window. + * + * @param hwnd + * Handle to the layered window. + * @param crKey + * COLORREF structure that specifies the transparency color key + * to be used when composing the layered window. + * @param bAlpha + * Alpha value used to describe the opacity of the layered + * window. + * @param dwFlags + * Specifies an action to take. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean SetLayeredWindowAttributes(HWND hwnd, int crKey, byte bAlpha, + int dwFlags); + + /** + * The GetLayeredWindowAttributes function retrieves the opacity and + * transparency color key of a layered window. + * + * @param hwnd + * Handle to the layered window. A layered window is created by + * specifying WS_EX_LAYERED when creating the window with the + * CreateWindowEx function or by setting WS_EX_LAYERED via + * SetWindowLong after the window has been created. + * @param pcrKey + * Pointer to a COLORREF value that receives the transparency + * color key to be used when composing the layered window. All + * pixels painted by the window in this color will be + * transparent. This can be NULL if the argument is not needed. + * @param pbAlpha + * Pointer to a BYTE that receives the Alpha value used to + * describe the opacity of the layered window. Similar to the + * SourceConstantAlpha member of the BLENDFUNCTION structure. + * When the variable referred to by pbAlpha is 0, the window is + * completely transparent. When the variable referred to by + * pbAlpha is 255, the window is opaque. This can be NULL if the + * argument is not needed. + * @param pdwFlags + * Pointer to a DWORD that receives a layering flag. This can be + * NULL if the argument is not needed. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean GetLayeredWindowAttributes(HWND hwnd, IntByReference pcrKey, + ByteByReference pbAlpha, IntByReference pdwFlags); + + /** + * The UpdateLayeredWindow function updates the position, size, shape, + * content, and translucency of a layered window. + * + * @param hwnd + * Handle to a layered window. A layered window is created by + * specifying WS_EX_LAYERED when creating the window with the + * CreateWindowEx function. + * @param hdcDst + * Handle to a device context (DC) for the screen. This handle is + * obtained by specifying NULL when calling the function. It is + * used for palette color matching when the window contents are + * updated. If hdcDst isNULL, the default palette will be used. + * If hdcSrc is NULL, hdcDst must be NULL. + * @param pptDst + * Pointer to a POINT structure that specifies the new screen + * position of the layered window. If the current position is not + * changing, pptDst can be NULL. + * @param psize + * Pointer to a SIZE structure that specifies the new size of the + * layered window. If the size of the window is not changing, + * psize can be NULL. If hdcSrc is NULL, psize must be NULL. + * @param hdcSrc + * Handle to a DC for the surface that defines the layered + * window. This handle can be obtained by calling the + * CreateCompatibleDC function. If the shape and visual context + * of the window are not changing, hdcSrc can be NULL. + * @param pptSrc + * Pointer to a POINT structure that specifies the location of + * the layer in the device context. If hdcSrc is NULL, pptSrc + * should be NULL. + * @param crKey + * Pointer to a COLORREF value that specifies the color key to be + * used when composing the layered window. To generate a + * COLORREF, use the RGB macro. + * @param pblend + * Pointer to a BLENDFUNCTION structure that specifies the + * transparency value to be used when composing the layered + * window. + * @param dwFlags + * ULW_* flags. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean UpdateLayeredWindow(HWND hwnd, HDC hdcDst, POINT pptDst, + SIZE psize, HDC hdcSrc, POINT pptSrc, int crKey, + BLENDFUNCTION pblend, int dwFlags); + + /** + * This function sets the window region of a window. The window region + * determines the area within the window where the system permits drawing. + * The system does not display any portion of a window that lies outside of + * the window region. + * + * @param hWnd + * Handle to the window whose window region is to be set. + * @param hRgn + * Handle to a region. The function sets the window region of the + * window to this region. If hRgn is NULL, the function sets the + * window region to NULL. + * @param bRedraw + * Specifies whether the system redraws the window after setting + * the window region. If bRedraw is TRUE, the system does so; + * otherwise, it does not. Typically, you set bRedraw to TRUE if + * the window is visible. + * @return Nonzero indicates success. Zero indicates failure. To get + * extended error information, call GetLastError. + */ + int SetWindowRgn(HWND hWnd, HRGN hRgn, boolean bRedraw); + + /** + * The GetKeyboardState function copies the status of the 256 virtual keys + * to the specified buffer. + * + * @param lpKeyState + * Pointer to the 256-byte array that receives the status data + * for each virtual key. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean GetKeyboardState(byte[] lpKeyState); + + /** + * This function determines whether a key is up or down at the time the + * function is called, and whether the key was pressed after a previous call + * to GetAsyncKeyState. + * + * @param vKey + * Specifies one of 256 possible virtual-key codes. + * @return If the function succeeds, the return value specifies whether the + * key was pressed since the last call to GetAsyncKeyState, and + * whether the key is currently up or down. If the most significant + * bit is set, the key is down. + */ + short GetAsyncKeyState(int vKey); + + /** + * The SetWindowsHookEx function installs an application-defined hook + * procedure into a hook chain. You would install a hook procedure to + * monitor the system for certain types of events. These events are + * associated either with a specific thread or with all threads in the same + * desktop as the calling thread. + * + * @param idHook + * Specifies the type of hook procedure to be installed. + * @param lpfn + * Pointer to the hook procedure. + * @param hMod + * Handle to the DLL containing the hook procedure pointed to by + * the lpfn parameter. + * @param dwThreadId + * Specifies the identifier of the thread with which the hook + * procedure is to be associated. + * @return If the function succeeds, the return value is the handle to the + * hook procedure. If the function fails, the return value is NULL. + * To get extended error information, call GetLastError. + */ + HHOOK SetWindowsHookEx(int idHook, HOOKPROC lpfn, HINSTANCE hMod, + int dwThreadId); + + /** + * The CallNextHookEx function passes the hook information to the next hook + * procedure in the current hook chain. A hook procedure can call this + * function either before or after processing the hook information. + * + * @param hhk + * Ignored. + * @param nCode + * Specifies the hook code passed to the current hook procedure. + * The next hook procedure uses this code to determine how to + * process the hook information. + * @param wParam + * Specifies the wParam value passed to the current hook + * procedure. The meaning of this parameter depends on the type + * of hook associated with the current hook chain. + * @param lParam + * Specifies the lParam value passed to the current hook + * procedure. The meaning of this parameter depends on the type + * of hook associated with the current hook chain. + * @return This value is returned by the next hook procedure in the chain. + * The current hook procedure must also return this value. The + * meaning of the return value depends on the hook type. + */ + LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, LPARAM lParam); + + /** + * The CallNextHookEx function passes the hook information to the next hook + * procedure in the current hook chain. A hook procedure can call this + * function either before or after processing the hook information. + * + * @param hhk + * Ignored. + * @param nCode + * Specifies the hook code passed to the current hook procedure. + * The next hook procedure uses this code to determine how to + * process the hook information. + * @param wParam + * Specifies the wParam value passed to the current hook + * procedure. The meaning of this parameter depends on the type + * of hook associated with the current hook chain. + * @param lParam + * Specifies the lParam value passed to the current hook + * procedure. The meaning of this parameter depends on the type + * of hook associated with the current hook chain. + * @return This value is returned by the next hook procedure in the chain. + * The current hook procedure must also return this value. The + * meaning of the return value depends on the hook type. + */ + LRESULT CallNextHookEx(HHOOK hhk, int nCode, WPARAM wParam, Pointer lParam); + + /** + * The UnhookWindowsHookEx function removes a hook procedure installed in a + * hook chain by the SetWindowsHookEx function. + * + * @param hhk + * Handle to the hook to be removed. This parameter is a hook + * handle obtained by a previous call to SetWindowsHookEx. + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. To get extended error + * information, call GetLastError. + */ + boolean UnhookWindowsHookEx(HHOOK hhk); + + /** + * This function retrieves a message from the calling thread's message queue + * and places it in the specified structure. + * + * @param lpMsg + * Pointer to an MSG structure that receives message information + * from the thread's message queue. + * @param hWnd + * Handle to the window whose messages are to be retrieved. One + * value has a special meaning. + * @param wMsgFilterMin + * Specifies the integer value of the lowest message value to be + * retrieved. + * @param wMsgFilterMax + * Specifies the integer value of the highest message value to be + * retrieved. + * @return Nonzero indicates that the function retrieves a message other + * than WM_QUIT. Zero indicates that the function retrieves the + * WM_QUIT message, or that lpMsg is an invalid pointer. To get + * extended error information, call GetLastError. + */ + int GetMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, int wMsgFilterMax); + + /** + * This function checks a thread message queue for a message and places the + * message (if any) in the specified structure. + * + * @param lpMsg + * Pointer to an MSG structure that receives message information. + * @param hWnd + * Handle to the window whose messages are to be examined. + * @param wMsgFilterMin + * Specifies the value of the first message in the range of + * messages to be examined. + * @param wMsgFilterMax + * Specifies the value of the last message in the range of + * messages to be examined. + * @param wRemoveMsg + * Specifies how messages are handled. This parameter can be one + * of the following values. + * @return Nonzero indicates success. Zero indicates failure. + */ + boolean PeekMessage(MSG lpMsg, HWND hWnd, int wMsgFilterMin, + int wMsgFilterMax, int wRemoveMsg); + + /** + * This function translates virtual-key messages into character messages. + * The character messages are posted to the calling thread's message queue, + * to be read the next time the thread calls the GetMessage or PeekMessage + * function. + * + * @param lpMsg + * Pointer to an MSG structure that contains message information + * retrieved from the calling thread's message queue by using the + * GetMessage or PeekMessage function. + * @return Nonzero indicates that the message is translated, that is, a + * character message is posted to the thread's message queue. If the + * message is WM_KEYDOWN or WM_SYSKEYDOWN, the return value is + * nonzero, regardless of the translation. Zero indicates that the + * message is not translated, that is, a character message is not + * posted to the thread's message queue. + */ + boolean TranslateMessage(MSG lpMsg); + + /** + * This function dispatches a message to a window procedure. It is typically + * used to dispatch a message retrieved by the GetMessage function. + * + * @param lpMsg + * Pointer to an MSG structure that contains the message. + * @return The return value specifies the value returned by the window + * procedure. Although its meaning depends on the message being + * dispatched, the return value generally is ignored. + */ + LRESULT DispatchMessage(MSG lpMsg); + + /** + * This function places a message in the message queue associated with the + * thread that created the specified window and then returns without waiting + * for the thread to process the message. Messages in a message queue are + * retrieved by calls to the GetMessage or PeekMessage function. + * + * @param hWnd + * Handle to the window whose window procedure is to receive the + * message. + * @param msg + * Specifies the message to be posted. + * @param wParam + * Specifies additional message-specific information. + * @param lParam + * Specifies additional message-specific information. + */ + void PostMessage(HWND hWnd, int msg, WPARAM wParam, LPARAM lParam); + + /** + * This function indicates to Windows that a thread has made a request to + * terminate (quit). It is typically used in response to a WM_DESTROY + * message. + * + * @param nExitCode + * Specifies an application exit code. This value is used as the + * wParam parameter of the WM_QUIT message. + */ + void PostQuitMessage(int nExitCode); + + /** + * The GetSystemMetrics function retrieves various system metrics (widths + * and heights of display elements) and system configuration settings. All + * dimensions retrieved by GetSystemMetrics are in pixels. + * + * @param nIndex + * System metric or configuration setting to retrieve. This + * parameter can be one of the following values. Note that all + * SM_CX* values are widths and all SM_CY* values are heights. + * Also note that all settings designed to return Boolean data + * represent TRUE as any nonzero value, and FALSE as a zero + * value. + * @return If the function succeeds, the return value is the requested + * system metric or configuration setting. If the function fails, + * the return value is zero. GetLastError does not provide extended + * error information. + */ + public int GetSystemMetrics(int nIndex); + + /** + * Changes the parent window of the specified child window. + * + * @param hWndChild + * A handle to the child window. + * + * @param hWndNewParent + * A handle to the new parent window. If this parameter is NULL, + * the desktop window becomes the new parent window. If this + * parameter is HWND_MESSAGE, the child window becomes a + * message-only window. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + HWND SetParent(HWND hWndChild, HWND hWndNewParent); + + /** + * Determines the visibility state of the specified window. + * + * @param hWnd + * A handle to the window to be tested. + * + * @return If the specified window, its parent window, its parent's parent + * window, and so forth, have the WS_VISIBLE style, the return value + * is nonzero. Otherwise, the return value is zero. + * + * Because the return value specifies whether the window has the + * WS_VISIBLE style, it may be nonzero even if the window is totally + * obscured by other windows. + */ + boolean IsWindowVisible(HWND hWnd); + + /** + * Changes the position and dimensions of the specified window. For a + * top-level window, the position and dimensions are relative to the + * upper-left corner of the screen. For a child window, they are relative to + * the upper-left corner of the parent window's client area. + * + * @param hWnd + * A handle to the window. + * + * @param X + * The new position of the left side of the window. + * + * @param Y + * The new position of the top of the window. + * + * @param nWidth + * The new width of the window. + * + * @param nHeight + * The new height of the window. + * + * @param bRepaint + * Indicates whether the window is to be repainted. If this + * parameter is TRUE, the window receives a message. If the + * parameter is FALSE, no repainting of any kind occurs. This + * applies to the client area, the nonclient area (including the + * title bar and scroll bars), and any part of the parent window + * uncovered as a result of moving a child window. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + boolean MoveWindow(HWND hWnd, int X, int Y, int nWidth, int nHeight, + boolean bRepaint); + + /** + * Changes the size, position, and Z order of a child, pop-up, or top-level + * window. These windows are ordered according to their appearance on the + * screen. The topmost window receives the highest rank and is the first + * window in the Z order. + * + * @param hWnd + * A handle to the window. + * + * @param hWndInsertAfter + * A handle to the window to precede the positioned window in the + * Z order. + * + * @param X + * The new position of the left side of the window, in client + * coordinates. + * + * @param Y + * The new position of the top of the window, in client + * coordinates. + * + * @param cx + * The new width of the window, in pixels. + * + * @param cy + * The new height of the window, in pixels. + * + * @param uFlags + * The window sizing and positioning flags. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + boolean SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int X, int Y, int cx, + int cy, int uFlags); + + /** + * Attaches or detaches the input processing mechanism of one thread to that + * of another thread. + * + * @param idAttach + * The identifier of the thread to be attached to another thread. + * The thread to be attached cannot be a system thread. + * + * @param idAttachTo + * The identifier of the thread to which idAttach will be + * attached. This thread cannot be a system thread. A thread + * cannot attach to itself. Therefore, idAttachTo cannot equal + * idAttach. + * + * @param fAttach + * If this parameter is TRUE, the two threads are attached. If + * the parameter is FALSE, the threads are detached. + * + * @return If the function succeeds, the return value is nonzero. + */ + boolean AttachThreadInput(DWORD idAttach, DWORD idAttachTo, boolean fAttach); + + /** + * Brings the thread that created the specified window into the foreground + * and activates the window. Keyboard input is directed to the window, and + * various visual cues are changed for the user. The system assigns a + * slightly higher priority to the thread that created the foreground window + * than it does to other threads. + * + * @param hWnd + * A handle to the window that should be activated and brought to + * the foreground. + * + * @return If the window was brought to the foreground, the return value is + * nonzero. + */ + boolean SetForegroundWindow(HWND hWnd); + + /** + * Retrieves a handle to the foreground window (the window with which the + * user is currently working). The system assigns a slightly higher priority + * to the thread that creates the foreground window than it does to other + * threads. + * + * @return The return value is a handle to the foreground window. The + * foreground window can be NULL in certain circumstances, such as + * when a window is losing activation. + */ + HWND GetForegroundWindow(); + + /** + * Sets the keyboard focus to the specified window. The window must be + * attached to the calling thread's message queue. + * + * @param hWnd + * A handle to the window that will receive the keyboard input. + * If this parameter is NULL, keystrokes are ignored. + * + * @return If the function succeeds, the return value is the handle to the + * window that previously had the keyboard focus. If the hWnd + * parameter is invalid or the window is not attached to the calling + * thread's message queue, the return value is NULL. To get extended + * error information, call GetLastError. + */ + HWND SetFocus(HWND hWnd); + + /** + * Synthesizes keystrokes, mouse motions, and button clicks. + * + * @param nInputs + * The number of structures in the pInputs array. + * + * @param pInputs + * An array of INPUT structures. Each structure represents an + * event to be inserted into the keyboard or mouse input stream. + * + * @param cbSize + * The size, in bytes, of an INPUT structure. If cbSize is not + * the size of an INPUT structure, the function fails. + * + * @return The function returns the number of events that it successfully + * inserted into the keyboard or mouse input stream. If the function + * returns zero, the input was already blocked by another thread. To + * get extended error information, call GetLastError. + * + * This function fails when it is blocked by UIPI. Note that neither + * GetLastError nor the return value will indicate the failure was + * caused by UIPI blocking. + */ + DWORD SendInput(DWORD nInputs, WinUser.INPUT[] pInputs, int cbSize); + + /** + * Waits until the specified process has finished processing its initial + * input and is waiting for user input with no input pending, or until the + * time-out interval has elapsed. + * + * @param hProcess + * A handle to the process. If this process is a console + * application or does not have a message queue, WaitForInputIdle + * returns immediately. + * + * @param dwMilliseconds + * The time-out interval, in milliseconds. If dwMilliseconds is + * INFINITE, the function does not return until the process is + * idle. + * + * @return The following table shows the possible return values for this + * function. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Return code/valueDescription
0The wait was satisfied successfully.
WAIT_TIMEOUTThe wait was terminated because the time-out interval + * elapsed.
WAIT_FAILEDAn error occurred.
+ */ + DWORD WaitForInputIdle(HANDLE hProcess, DWORD dwMilliseconds); + + /** + * The InvalidateRect function adds a rectangle to the specified window's + * update region. The update region represents the portion of the window's + * client area that must be redrawn. + * + * @param hWnd + * A handle to the window whose update region has changed. If + * this parameter is NULL, the system invalidates and redraws all + * windows, not just the windows for this application, and sends + * the WM_ERASEBKGND and WM_NCPAINT messages before the function + * returns. Setting this parameter to NULL is not recommended. + * + * @param lpRect + * A pointer to a RECT structure that contains the client + * coordinates of the rectangle to be added to the update region. + * If this parameter is NULL, the entire client area is added to + * the update region. + * + * @param bErase + * Specifies whether the background within the update region is + * to be erased when the update region is processed. If this + * parameter is TRUE, the background is erased when the + * BeginPaint function is called. If this parameter is FALSE, the + * background remains unchanged. + * + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. + */ + boolean InvalidateRect(HWND hWnd, RECT.ByReference lpRect, boolean bErase); + + /** + * The RedrawWindow function updates the specified rectangle or region in a + * window's client area. + * + * @param hWnd + * A handle to the window to be redrawn. If this parameter is + * NULL, the desktop window is updated. + * + * @param lprcUpdate + * A pointer to a RECT structure containing the coordinates, in + * device units, of the update rectangle. This parameter is + * ignored if the hrgnUpdate parameter identifies a region. + * + * @param hrgnUpdate + * A handle to the update region. If both the hrgnUpdate and + * lprcUpdate parameters are NULL, the entire client area is + * added to the update region. + * + * @param flags + * One or more redraw flags. This parameter can be used to + * invalidate or validate a window, control repainting, and + * control which windows are affected by RedrawWindow. + * + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. + */ + boolean RedrawWindow(HWND hWnd, RECT.ByReference lprcUpdate, + HRGN hrgnUpdate, DWORD flags); + + /** + * Retrieves a handle to a window that has the specified relationship + * (Z-Order or owner) to the specified window. + * + * @param hWnd + * A handle to a window. The window handle retrieved is relative + * to this window, based on the value of the uCmd parameter. + * + * @param uCmd + * The relationship between the specified window and the window + * whose handle is to be retrieved. + * + * @return If the function succeeds, the return value is a window handle. If + * no window exists with the specified relationship to the specified + * window, the return value is NULL. To get extended error + * information, call GetLastError. + */ + HWND GetWindow(HWND hWnd, DWORD uCmd); + + /** + * The UpdateWindow function updates the client area of the specified window + * by sending a WM_PAINT message to the window if the window's update region + * is not empty. The function sends a WM_PAINT message directly to the + * window procedure of the specified window, bypassing the application + * queue. If the update region is empty, no message is sent. + * + * @param hWnd + * Handle to the window to be updated. + * + * @return If the function succeeds, the return value is nonzero. If the + * function fails, the return value is zero. + */ + boolean UpdateWindow(HWND hWnd); + + /** + * Sets the specified window's show state. + * + * @param hWnd + * A handle to the window. + * + * @param nCmdShow + * Controls how the window is to be shown. This parameter is + * ignored the first time an application calls ShowWindow, if the + * program that launched the application provides a STARTUPINFO + * structure. Otherwise, the first time ShowWindow is called, the + * value should be the value obtained by the WinMain function in + * its nCmdShow parameter. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + boolean ShowWindow(HWND hWnd, int nCmdShow); + + /** + * Minimizes (but does not destroy) the specified window. + * + * @param hWnd + * A handle to the window to be minimized. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + boolean CloseWindow(HWND hWnd); + + /** + * Defines a system-wide hot key. + * + * @param hWnd + * A handle to the window that will receive + * @param id + * The identifier of the hot key + * @param fsModifiers + * The keys that must be pressed in combination with the key + * specified by the uVirtKey parameter in order to generate the + * @param vk + * The virtual-key code of the hot key + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + * {@link WinUser#WM_HOTKEY} messages generated by the hot key + * {@link WinUser#WM_HOTKEY} message.
+ * A combination of the following values + *

+ */ + boolean RegisterHotKey(HWND hWnd, int id, int fsModifiers, int vk); + + /** + * Frees a hot key previously registered by the calling thread. + * + * @param hWnd + * A handle to the window associated with the hot key to be + * freed. This parameter should be NULL if the hot key is not + * associated with a window. + * + * @param id + * The identifier of the hot key to be freed. + * + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + boolean UnregisterHotKey(Pointer hWnd, int id); + + /** + * Retrieves the time of the last input event. + * + * @param plii + * structure that receives the time of the last input event + * @return If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + boolean GetLastInputInfo(LASTINPUTINFO plii); + + /** + * Registers a window class for subsequent use in calls to the CreateWindow + * or CreateWindowEx function. + * + * @param lpwcx + * Type: const WNDCLASSEX* A pointer to a WNDCLASSEX structure. + * You must fill the structure with the appropriate class + * attributes before passing it to the function. + * + * @return If the function succeeds, the return value is a class atom that + * uniquely identifies the class being registered. This atom can + * only be used by the CreateWindow, CreateWindowEx, GetClassInfo, + * GetClassInfoEx, FindWindow, FindWindowEx, and UnregisterClass + * functions and the IActiveIMMap::FilterClientWindows method. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + public ATOM RegisterClassEx(WNDCLASSEX lpwcx); + + /** + * Unregisters a window class, freeing the memory required for the class. + * + * @param lpClassName + * [in] Type: LPCTSTR + * + * A null-terminated string or a class atom. If lpClassName is a + * string, it specifies the window class name. This class name + * must have been registered by a previous call to the + * RegisterClass or RegisterClassEx function. System classes, + * such as dialog box controls, cannot be unregistered. If this + * parameter is an atom, it must be a class atom created by a + * previous call to the RegisterClass or RegisterClassEx + * function. The atom must be in the low-order word of + * lpClassName; the high-order word must be zero. + * + * @param hInstance + * [in,optional] Type: HINSTANCE A handle to the instance of the + * module that created the class. * + * + * @return Type: BOOL If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + public boolean UnregisterClass(WString lpClassName, HINSTANCE hInstance); + + /** + * Creates an overlapped, pop-up, or child window with an extended window + * style; otherwise, this function is identical to the CreateWindow + * function. For more information about creating a window and for full + * descriptions of the other parameters of CreateWindowEx, see CreateWindow. + * + * @param dwExStyle + * [in] Type: DWORD + * + * The extended window style of the window being created. For a + * list of possible values,see Extended Window Styles. + * + * @param lpClassName + * [in, optional] Type: LPCTSTR + * + * A null-terminated string or a class atom created by a previous + * call to the RegisterClass or RegisterClassEx function. The + * atom must be in the low-order word of lpClassName; the + * high-order word must be zero. If lpClassName is a string, it + * specifies the window class name. The class name can be any + * name registered with RegisterClass or RegisterClassEx, + * provided that the module that registers the class is also the + * module that creates the window. The class name can also be any + * of the predefined system class names. + * + * @param lpWindowName + * [in, optional] Type: LPCTSTR + * + * The window name. If the window style specifies a title bar, + * the window title pointed to by lpWindowName is displayed in + * the title bar. When using CreateWindow to create controls, + * such as buttons, check boxes, and static controls, use + * lpWindowName to specify the text of the control. When creating + * a static control with the SS_ICON style, use lpWindowName to + * specify the icon name or identifier. To specify an identifier, + * use the syntax "#num". + * + * @param dwStyle + * [in] Type: DWORD + * + * The style of the window being created. This parameter can be a + * combination of the window style values, plus the control + * styles indicated in the Remarks section. + * + * @param x + * [in] Type: int + * + * The initial horizontal position of the window. For an + * overlapped or pop-up window, the x parameter is the initial + * x-coordinate of the window's upper-left corner, in screen + * coordinates. For a child window, x is the x-coordinate of the + * upper-left corner of the window relative to the upper-left + * corner of the parent window's client area. If x is set to + * CW_USEDEFAULT, the system selects the default position for the + * window's upper-left corner and ignores the y parameter. + * CW_USEDEFAULT is valid only for overlapped windows; if it is + * specified for a pop-up or child window, the x and y parameters + * are set to zero. + * + * @param y + * [in] Type: int + * + * The initial vertical position of the window. For an overlapped + * or pop-up window, the y parameter is the initial y-coordinate + * of the window's upper-left corner, in screen coordinates. For + * a child window, y is the initial y-coordinate of the + * upper-left corner of the child window relative to the + * upper-left corner of the parent window's client area. For a + * list box y is the initial y-coordinate of the upper-left + * corner of the list box's client area relative to the + * upper-left corner of the parent window's client area. + * + * If an overlapped window is created with the WS_VISIBLE style + * bit set and the x parameter is set to CW_USEDEFAULT, then the + * y parameter determines how the window is shown. If the y + * parameter is CW_USEDEFAULT, then the window manager calls + * ShowWindow with the SW_SHOW flag after the window has been + * created. If the y parameter is some other value, then the + * window manager calls ShowWindow with that value as the + * nCmdShow parameter. + * + * @param nWidth + * [in] Type: int + * + * The width, in device units, of the window. For overlapped + * windows, nWidth is the window's width, in screen coordinates, + * or CW_USEDEFAULT. If nWidth is CW_USEDEFAULT, the system + * selects a default width and height for the window; the default + * width extends from the initial x-coordinates to the right edge + * of the screen; the default height extends from the initial + * y-coordinate to the top of the icon area. CW_USEDEFAULT is + * valid only for overlapped windows; if CW_USEDEFAULT is + * specified for a pop-up or child window, the nWidth and nHeight + * parameter are set to zero. + * + * @param nHeight + * [in] Type: int + * + * The height, in device units, of the window. For overlapped + * windows, nHeight is the window's height, in screen + * coordinates. If the nWidth parameter is set to CW_USEDEFAULT, + * the system ignores nHeight. + * + * @param hWndParent + * [in, optional] Type: HWND + * + * A handle to the parent or owner window of the window being + * created. To create a child window or an owned window, supply a + * valid window handle. This parameter is optional for pop-up + * windows. + * + * To create a message-only window, supply HWND_MESSAGE or a + * handle to an existing message-only window. + * + * @param hMenu + * [in, optional] Type: HMENU + * + * A handle to a menu, or specifies a child-window identifier, + * depending on the window style. For an overlapped or pop-up + * window, hMenu identifies the menu to be used with the window; + * it can be NULL if the class menu is to be used. For a child + * window, hMenu specifies the child-window identifier, an + * integer value used by a dialog box control to notify its + * parent about events. The application determines the + * child-window identifier; it must be unique for all child + * windows with the same parent window. + * + * @param hInstance + * [in, optional] Type: HINSTANCE + * + * A handle to the instance of the module to be associated with + * the window. + * + * @param lpParam + * [in, optional] Type: LPVOID + * + * Pointer to a value to be passed to the window through the + * CREATESTRUCT structure (lpCreateParams member) pointed to by + * the lParam param of the WM_CREATE message. This message is + * sent to the created window by this function before it returns. + * + * If an application calls CreateWindow to create a MDI client + * window, lpParam should point to a CLIENTCREATESTRUCT + * structure. If an MDI client window calls CreateWindow to + * create an MDI child window, lpParam should point to a + * MDICREATESTRUCT structure. lpParam may be NULL if no + * additional data is needed. + * + * @return Type: HWND + * + * If the function succeeds, the return value is a handle to the new + * window. + * + * If the function fails, the return value is NULL. To get extended + * error information, call GetLastError. + * + * This function typically fails for one of the following reasons: • + * an invalid parameter value • the system class was registered by a + * different module • The WH_CBT hook is installed and returns a + * failure code • if one of the controls in the dialog template is + * not registered, or its window window procedure fails WM_CREATE or + * WM_NCCREATE + */ + public HWND CreateWindowEx(int dwExStyle, WString lpClassName, + String lpWindowName, int dwStyle, int x, int y, int nWidth, + int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, + LPVOID lpParam); + + /** + * Destroys the specified window. The function sends WM_DESTROY and + * WM_NCDESTROY messages to the window to deactivate it and remove the + * keyboard focus from it. The function also destroys the window's menu, + * flushes the thread message queue, destroys timers, removes clipboard + * ownership, and breaks the clipboard viewer chain (if the window is at the + * top of the viewer chain). + * + * If the specified window is a parent or owner window, DestroyWindow + * automatically destroys the associated child or owned windows when it + * destroys the parent or owner window. The function first destroys child or + * owned windows, and then it destroys the parent or owner window. + * + * DestroyWindow also destroys modeless dialog boxes created by the + * CreateDialog function. + * + * @param hWnd + * [in] Type: HWND A handle to the window to be destroyed. + * + * @return Type: BOOL If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + public boolean DestroyWindow(HWND hWnd); + + /** + * Retrieves information about a window class, including a handle to the + * small icon associated with the window class. The GetClassInfo function + * does not retrieve a handle to the small icon. + * + * @param hinst + * [in, optional] Type: HINSTANCE + * + * A handle to the instance of the application that created the + * class. To retrieve information about classes defined by the + * system (such as buttons or list boxes), set this parameter to + * NULL. + * + * @param lpszClass + * [in] Type: LPCTSTR + * + * The class name. The name must be that of a preregistered class + * or a class registered by a previous call to the RegisterClass + * or RegisterClassEx function. Alternatively, this parameter can + * be a class atom created by a previous call to RegisterClass or + * RegisterClassEx. The atom must be in the low-order word of + * lpszClass; the high-order word must be zero. + * + * @param lpwcx + * [out] Type: LPWNDCLASSEX + * + * A pointer to a WNDCLASSEX structure that receives the + * information about the class. + * + * @return Type: BOOL If the function finds a matching class and + * successfully copies the data, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError} . + */ + public boolean GetClassInfoEx(HINSTANCE hinst, WString lpszClass, + WNDCLASSEX lpwcx); + + /** + * Calls the default window procedure to provide default processing for any + * window messages that an application does not process. This function + * ensures that every message is processed. DefWindowProc is called with the + * same parameters received by the window procedure. + * + * @param hWnd + * [in] Type: HWND + * + * A handle to the window procedure that received the message. + * + * @param Msg + * [in] Type: UINT + * + * The message. + * + * @param wParam + * [in] Type: WPARAM + * + * Additional message information. The content of this parameter + * depends on the value of the Msg parameter. + * + * @param lParam + * [in] Type: LPARAM + * + * Additional message information. The content of this parameter + * depends on the value of the Msg parameter. + * + * @return Type: LRESULT The return value is the result of the message + * processing and depends on the message. + * + * If the function fails, the return value is zero. To get extended + * error information, call {@link Kernel32#GetLastError}. + */ + public LRESULT DefWindowProc(HWND hWnd, int Msg, WPARAM wParam, + LPARAM lParam); + + /** + * Registers the device or type of device for which a window will receive + * notifications. + * + * @hRecipient [in] A handle to the window or service that will receive + * device events for the devices specified in the + * NotificationFilter parameter. The same window handle can be + * used in multiple calls to RegisterDeviceNotification. + * + * Services can specify either a window handle or service status + * handle. + * + * @param NotificationFilter + * [in] A pointer to a block of data that specifies the type of + * device for which notifications should be sent. This block + * always begins with the DEV_BROADCAST_HDR structure. The data + * following this header is dependent on the value of the + * dbch_devicetype member, which can be + * DBT_DEVTYP_DEVICEINTERFACE or DBT_DEVTYP_HANDLE. For more + * information, see Remarks. + * + * @param Flags + * [in] This parameter can be one of the following values. + * DEVICE_NOTIFY_WINDOW_HANDLE0x00000000 The hRecipient parameter + * is a window handle. + * + * DEVICE_NOTIFY_SERVICE_HANDLE0x00000001 The hRecipient + * parameter is a service status handle. + * + * In addition, you can specify the following value. + * + * DEVICE_NOTIFY_ALL_INTERFACE_CLASSES0x00000004 Notifies the + * recipient of device interface events for all device interface + * classes. (The dbcc_classguid member is ignored.) + * + * This value can be used only if the dbch_devicetype member is + * DBT_DEVTYP_DEVICEINTERFACE. + * + * @return value + * + * If the function succeeds, the return value is a device + * notification handle. + * + * If the function fails, the return value is NULL. To get extended + * error information, call GetLastError. + */ + HDEVNOTIFY RegisterDeviceNotification(HANDLE hRecipient, + Structure notificationFilter, int Flags); + + /** + * Closes the specified device notification handle. + * + * @Handle [in] Device notification handle returned by the + * RegisterDeviceNotification function. + * + * @return Return value + * + * If the function succeeds, the return value is nonzero. + * + * If the function fails, the return value is zero. To get extended + * error information, call GetLastError. + */ + boolean UnregisterDeviceNotification(HDEVNOTIFY Handle); +} diff --git a/contrib/platform/src/com/sun/jna/platform/win32/W32Errors.java b/contrib/platform/src/com/sun/jna/platform/win32/W32Errors.java index 3286a55060..1d5cf07268 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/W32Errors.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/W32Errors.java @@ -1,105 +1,181 @@ -/* Copyright (c) 2010,2011 Daniel Doubrovkine, All Rights Reserved - * - * 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. - */ -package com.sun.jna.platform.win32; - -import com.sun.jna.platform.win32.WinNT.HRESULT; - -/** - * Utility class for some common error functions. - */ -public abstract class W32Errors implements WinError { - /** - * Generic test for success on any status value (non-negative numbers - * indicate success). - */ - public static final boolean SUCCEEDED(int hr) { - return hr >= 0; - } - - /** - * and the inverse - */ - public static final boolean FAILED(int hr) { - return hr < 0; - } - - /** - * Extract error code from HRESULT - */ - public static final int HRESULT_CODE(int hr) { - return hr & 0xFFFF; - } - - /** - * Extract error code from SCODE - */ - public static final int SCODE_CODE(int sc) { - return sc & 0xFFFF; - } - - /** - * Return the facility - */ - public static final int HRESULT_FACILITY(int hr) { - return (hr >>= 16) & 0x1fff; - } - - public static final int SCODE_FACILITY(short sc) { - return (sc >>= 16) & 0x1fff; - } - - /** - * Return the severity - */ - public static short HRESULT_SEVERITY(int hr) { - return (short) ((hr >>= 31) & 0x1); - } - - public static short SCODE_SEVERITY(short sc) { - return (short) ((sc >>= 31) & 0x1); - } - - /** - * Create an HRESULT value from component pieces - */ - public static int MAKE_HRESULT(short sev, short fac, short code) { - return ((sev << 31) | (fac << 16) | code); - } - - public static final int MAKE_SCODE(short sev, short fac, short code) { - return ((sev << 31) | (fac << 16) | code); - } - - /** - * Map a WIN32 error value into a HRESULT - * Note: This assumes that WIN32 errors fall in the range -32k to=32k. - * @param x original w32 error code - * @return the converted value - */ - public static final HRESULT HRESULT_FROM_WIN32(int x) { - int f = FACILITY_WIN32; - return new HRESULT(x <= 0 ? x : ((x) & 0x0000FFFF) | (f <<= 16) | 0x80000000); - } - - /** - * FACILITY_USERMODE_FILTER_MANAGER - * - * Translation macro for converting: - * NTSTATUS --> HRESULT - */ - public static final int FILTER_HRESULT_FROM_FLT_NTSTATUS(int x) { - int f = FACILITY_USERMODE_FILTER_MANAGER; - return (((x) & 0x8000FFFF) | (f <<= 16)); - } - -} +/* Copyright (c) 2010,2011 Daniel Doubrovkine, All Rights Reserved + * + * 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. + */ +package com.sun.jna.platform.win32; + +import com.sun.jna.platform.win32.WinNT.HRESULT; + +// TODO: Auto-generated Javadoc +/** + * Utility class for some common error functions. + */ +public abstract class W32Errors implements WinError { + + /** + * Generic test for success on any status value (non-negative numbers + * indicate success). + * + * @param hr the hr + * @return true, if successful + */ + public static final boolean SUCCEEDED(int hr) { + return hr >= 0; + } + + /** + * and the inverse. + * + * @param hr the hr + * @return true, if successful + */ + public static final boolean FAILED(int hr) { + return hr < 0; + } + + /** + * Succeeded. + * + * @param hr the hr + * @return true, if successful + */ + public static final boolean SUCCEEDED(HRESULT hr) { + if (hr != null) + return hr.intValue() >= 0; + else + return false; + } + + /** + * Failed. + * + * @param hr the hr + * @return true, if successful + */ + public static final boolean FAILED(HRESULT hr) { + if (hr != null) + return hr.intValue() >= 0; + else + return false; + } + + /** + * Extract error code from HRESULT. + * + * @param hr the hr + * @return the int + */ + public static final int HRESULT_CODE(int hr) { + return hr & 0xFFFF; + } + + /** + * Extract error code from SCODE. + * + * @param sc the sc + * @return the int + */ + public static final int SCODE_CODE(int sc) { + return sc & 0xFFFF; + } + + /** + * Return the facility. + * + * @param hr the hr + * @return the int + */ + public static final int HRESULT_FACILITY(int hr) { + return (hr >>= 16) & 0x1fff; + } + + /** + * Scode facility. + * + * @param sc the sc + * @return the int + */ + public static final int SCODE_FACILITY(short sc) { + return (sc >>= 16) & 0x1fff; + } + + /** + * Return the severity. + * + * @param hr the hr + * @return the short + */ + public static short HRESULT_SEVERITY(int hr) { + return (short) ((hr >>= 31) & 0x1); + } + + /** + * Scode severity. + * + * @param sc the sc + * @return the short + */ + public static short SCODE_SEVERITY(short sc) { + return (short) ((sc >>= 31) & 0x1); + } + + /** + * Create an HRESULT value from component pieces. + * + * @param sev the sev + * @param fac the fac + * @param code the code + * @return the int + */ + public static int MAKE_HRESULT(short sev, short fac, short code) { + return ((sev << 31) | (fac << 16) | code); + } + + /** + * Make scode. + * + * @param sev the sev + * @param fac the fac + * @param code the code + * @return the int + */ + public static final int MAKE_SCODE(short sev, short fac, short code) { + return ((sev << 31) | (fac << 16) | code); + } + + /** + * Map a WIN32 error value into a HRESULT Note: This assumes that WIN32 + * errors fall in the range -32k to=32k. + * + * @param x + * original w32 error code + * @return the converted value + */ + public static final HRESULT HRESULT_FROM_WIN32(int x) { + int f = FACILITY_WIN32; + return new HRESULT(x <= 0 ? x : ((x) & 0x0000FFFF) | (f <<= 16) + | 0x80000000); + } + + /** + * FACILITY_USERMODE_FILTER_MANAGER + * + * Translation macro for converting: NTSTATUS --> HRESULT. + * + * @param x the x + * @return the int + */ + public static final int FILTER_HRESULT_FROM_FLT_NTSTATUS(int x) { + int f = FACILITY_USERMODE_FILTER_MANAGER; + return (((x) & 0x8000FFFF) | (f <<= 16)); + } + +} diff --git a/contrib/platform/src/com/sun/jna/platform/win32/WinDef.java b/contrib/platform/src/com/sun/jna/platform/win32/WinDef.java index 5c1d596019..94fabbc9bd 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/WinDef.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/WinDef.java @@ -24,360 +24,808 @@ import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.win32.StdCallLibrary; +// TODO: Auto-generated Javadoc /** - * Ported from Windef.h (various macros and types). - * Microsoft Windows SDK 6.0A. + * Ported from Windef.h (various macros and types). Microsoft Windows SDK 6.0A. + * * @author dblock[at]dblock.org */ @SuppressWarnings("serial") public interface WinDef extends StdCallLibrary { - int MAX_PATH = 260; - - /** - * 16-bit unsigned integer. - */ - public static class WORD extends IntegerType { - public WORD() { - this(0); - } - - public WORD(long value) { - super(2, value, true); - } - } - - /** - * 32-bit unsigned integer. - */ - public static class DWORD extends IntegerType { - public DWORD() { - this(0); - } - - public DWORD(long value) { - super(4, value, true); - } - - /** - * Low WORD. - * @return - * Low WORD. - */ - public WORD getLow() { - return new WORD(longValue() & 0xFFFF); - } - - /** - * High WORD. - * @return - * High WORD. - */ - public WORD getHigh() { - return new WORD((longValue() >> 16) & 0xFFFF); - } - } - - /** - * 32-bit signed integer. - */ - public static class LONG extends IntegerType { - public LONG() { - this(0); - } - - public LONG(long value) { - super(Native.LONG_SIZE, value); - } - } - - /** - * Handle to a device context (DC). - */ - public static class HDC extends HANDLE { - public HDC() { - - } - - public HDC(Pointer p) { - super(p); - } - } - - /** - * Handle to an icon. - */ - public static class HICON extends HANDLE { - public HICON() { - - } - - public HICON(Pointer p) { - super(p); - } - } - - /** - * Handle to a cursor. - */ - public static class HCURSOR extends HICON { - public HCURSOR() { - - } - - public HCURSOR(Pointer p) { - super(p); - } - } - - /** - * Handle to a cursor. - */ - public static class HMENU extends HANDLE { - public HMENU() { - - } - - public HMENU(Pointer p) { - super(p); - } - } - - /** - * Handle to a pen. - */ - public static class HPEN extends HANDLE { - public HPEN() { - - } - - public HPEN(Pointer p) { - super(p); - } - } - - /** - * Handle to a resource. - */ - public static class HRSRC extends HANDLE { - public HRSRC() { - - } - - public HRSRC(Pointer p) { - super(p); - } - } - - /** - * Handle to a palette. - */ - public static class HPALETTE extends HANDLE { - public HPALETTE() { - - } - - public HPALETTE(Pointer p) { - super(p); - } - } - - /** - * Handle to a bitmap. - */ - public static class HBITMAP extends HANDLE { - public HBITMAP() { - - } - - public HBITMAP(Pointer p) { - super(p); - } - } - - /** - * Handle to a region. - */ - public static class HRGN extends HANDLE { - public HRGN() { - - } - - public HRGN(Pointer p) { - super(p); - } - } - - /** - * Handle to a window. - */ - public static class HWND extends HANDLE { - public HWND() { - - } - - public HWND(Pointer p) { - super(p); - } - } - - /** - * Handle to an instance. - */ - public static class HINSTANCE extends HANDLE { - - } - - /** - * Handle to a module. The value is the base address of the module. - */ - public static class HMODULE extends HINSTANCE { - - } - - /** - * Handle to a font. - */ - public static class HFONT extends HANDLE { - public HFONT() { - - } - - public HFONT(Pointer p) { - super(p); - } - } - - /** - * Message parameter. - */ - public static class LPARAM extends LONG_PTR { - public LPARAM() { - this(0); - } - - public LPARAM(long value) { - super(value); - } - } - - /** - * Signed result of message processing. - */ - public static class LRESULT extends LONG_PTR { - public LRESULT() { - this(0); - } - - public LRESULT(long value) { - super(value); - } - } - - /** Integer type big enough for a pointer. */ - public static class INT_PTR extends IntegerType { - public INT_PTR() { - super(Pointer.SIZE); - } - - public INT_PTR(long value) { - super(Pointer.SIZE, value); - } - - public Pointer toPointer() { - return Pointer.createConstant(longValue()); - } - } - - /** - * Unsigned INT_PTR. - */ - public static class UINT_PTR extends IntegerType { - public UINT_PTR() { - super(Pointer.SIZE); - } - - public UINT_PTR(long value) { - super(Pointer.SIZE, value, true); - } - - public Pointer toPointer() { - return Pointer.createConstant(longValue()); - } - } - - /** - * Message parameter. - */ - public static class WPARAM extends UINT_PTR { - public WPARAM() { - this(0); - } - - public WPARAM(long value) { - super(value); - } - } - - public class RECT extends Structure { - public int left; - public int top; - public int right; - public int bottom; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "left", "top", "right", "bottom" }); - } - - public Rectangle toRectangle() { - return new Rectangle(left, top, right-left, bottom-top); - } - - public String toString() { - return "[(" + left + "," + top + ")(" + right + "," + bottom + ")]"; - } - } - - /** - * 32-bit unsigned integer. - */ - public static class ULONG extends IntegerType { - public ULONG() { - this(0); - } - - public ULONG(long value) { - super(Native.LONG_SIZE, value, true); - } - - public static class ByReference implements Structure.ByReference { - - } - } - - /** - * 64-bit unsigned integer. - */ - public static class ULONGLONG extends IntegerType { - public ULONGLONG() { - this(0); - } - - public ULONGLONG(long value) { - super(8, value, true); - } - } - - /** - * 64-bit unsigned integer. - */ - public static class DWORDLONG extends IntegerType { - public DWORDLONG() { - this(0); - } - - public DWORDLONG(long value) { - super(8, value, true); - } - } + /** The max path. */ + int MAX_PATH = 260; + + /** + * 16-bit unsigned integer. + */ + public static class WORD extends IntegerType { + + /** + * Instantiates a new word. + */ + public WORD() { + this(0); + } + + /** + * Instantiates a new word. + * + * @param value the value + */ + public WORD(long value) { + super(2, value, true); + } + } + + /** + * 32-bit unsigned integer. + */ + public static class DWORD extends IntegerType { + + /** + * Instantiates a new dword. + */ + public DWORD() { + this(0); + } + + /** + * Instantiates a new dword. + * + * @param value the value + */ + public DWORD(long value) { + super(4, value, true); + } + + /** + * Low WORD. + * + * @return Low WORD. + */ + public WORD getLow() { + return new WORD(longValue() & 0xFF); + } + + /** + * High WORD. + * + * @return High WORD. + */ + public WORD getHigh() { + return new WORD((longValue() >> 16) & 0xFF); + } + } + + /** + * 32-bit signed integer. + */ + public static class LONG extends IntegerType { + + /** + * Instantiates a new long. + */ + public LONG() { + this(0); + } + + /** + * Instantiates a new long. + * + * @param value the value + */ + public LONG(long value) { + super(Native.LONG_SIZE, value); + } + } + + /** + * Handle to a device context (DC). + */ + public static class HDC extends HANDLE { + + /** + * Instantiates a new hdc. + */ + public HDC() { + + } + + /** + * Instantiates a new hdc. + * + * @param p the p + */ + public HDC(Pointer p) { + super(p); + } + } + + /** + * Handle to an icon. + */ + public static class HICON extends HANDLE { + + /** + * Instantiates a new hicon. + */ + public HICON() { + + } + + /** + * Instantiates a new hicon. + * + * @param p the p + */ + public HICON(Pointer p) { + super(p); + } + } + + /** + * Handle to a cursor. + */ + public static class HCURSOR extends HICON { + + /** + * Instantiates a new hcursor. + */ + public HCURSOR() { + + } + + /** + * Instantiates a new hcursor. + * + * @param p the p + */ + public HCURSOR(Pointer p) { + super(p); + } + } + + /** + * Handle to a cursor. + */ + public static class HMENU extends HANDLE { + + /** + * Instantiates a new hmenu. + */ + public HMENU() { + + } + + /** + * Instantiates a new hmenu. + * + * @param p the p + */ + public HMENU(Pointer p) { + super(p); + } + } + + /** + * Handle to a pen. + */ + public static class HPEN extends HANDLE { + + /** + * Instantiates a new hpen. + */ + public HPEN() { + + } + + /** + * Instantiates a new hpen. + * + * @param p the p + */ + public HPEN(Pointer p) { + super(p); + } + } + + /** + * Handle to a resource. + */ + public static class HRSRC extends HANDLE { + + /** + * Instantiates a new hrsrc. + */ + public HRSRC() { + + } + + /** + * Instantiates a new hrsrc. + * + * @param p the p + */ + public HRSRC(Pointer p) { + super(p); + } + } + + /** + * Handle to a palette. + */ + public static class HPALETTE extends HANDLE { + + /** + * Instantiates a new hpalette. + */ + public HPALETTE() { + + } + + /** + * Instantiates a new hpalette. + * + * @param p the p + */ + public HPALETTE(Pointer p) { + super(p); + } + } + + /** + * Handle to a bitmap. + */ + public static class HBITMAP extends HANDLE { + + /** + * Instantiates a new hbitmap. + */ + public HBITMAP() { + + } + + /** + * Instantiates a new hbitmap. + * + * @param p the p + */ + public HBITMAP(Pointer p) { + super(p); + } + } + + /** + * Handle to a region. + */ + public static class HRGN extends HANDLE { + + /** + * Instantiates a new hrgn. + */ + public HRGN() { + + } + + /** + * Instantiates a new hrgn. + * + * @param p the p + */ + public HRGN(Pointer p) { + super(p); + } + } + + /** + * Handle to a window. + */ + public static class HWND extends HANDLE { + + /** + * Instantiates a new hwnd. + */ + public HWND() { + + } + + /** + * Instantiates a new hwnd. + * + * @param p the p + */ + public HWND(Pointer p) { + super(p); + } + } + + /** + * Handle to an instance. + */ + public static class HINSTANCE extends HANDLE { + + } + + /** + * Handle to a module. The value is the base address of the module. + */ + public static class HMODULE extends HINSTANCE { + + } + + /** + * Handle to a font. + */ + public static class HFONT extends HANDLE { + + /** + * Instantiates a new hfont. + */ + public HFONT() { + + } + + /** + * Instantiates a new hfont. + * + * @param p the p + */ + public HFONT(Pointer p) { + super(p); + } + } + + /** + * Message parameter. + */ + public static class LPARAM extends LONG_PTR { + + /** + * Instantiates a new lparam. + */ + public LPARAM() { + this(0); + } + + /** + * Instantiates a new lparam. + * + * @param value the value + */ + public LPARAM(long value) { + super(value); + } + } + + /** + * Signed result of message processing. + */ + public static class LRESULT extends LONG_PTR { + + /** + * Instantiates a new lresult. + */ + public LRESULT() { + this(0); + } + + /** + * Instantiates a new lresult. + * + * @param value the value + */ + public LRESULT(long value) { + super(value); + } + } + + /** Integer type big enough for a pointer. */ + public static class INT_PTR extends IntegerType { + + /** + * Instantiates a new int ptr. + */ + public INT_PTR() { + super(Pointer.SIZE); + } + + /** + * Instantiates a new int ptr. + * + * @param value the value + */ + public INT_PTR(long value) { + super(Pointer.SIZE, value); + } + + /** + * To pointer. + * + * @return the pointer + */ + public Pointer toPointer() { + return Pointer.createConstant(longValue()); + } + } + + /** + * Unsigned INT_PTR. + */ + public static class UINT_PTR extends IntegerType { + + /** + * Instantiates a new uint ptr. + */ + public UINT_PTR() { + super(Pointer.SIZE); + } + + /** + * Instantiates a new uint ptr. + * + * @param value the value + */ + public UINT_PTR(long value) { + super(Pointer.SIZE, value, true); + } + + /** + * To pointer. + * + * @return the pointer + */ + public Pointer toPointer() { + return Pointer.createConstant(longValue()); + } + } + + /** + * Message parameter. + */ + public static class WPARAM extends UINT_PTR { + + /** + * Instantiates a new wparam. + */ + public WPARAM() { + this(0); + } + + /** + * Instantiates a new wparam. + * + * @param value the value + */ + public WPARAM(long value) { + super(value); + } + } + + /** + * The Class RECT. + */ + public class RECT extends Structure { + + /** The left. */ + public int left; + + /** The top. */ + public int top; + + /** The right. */ + public int right; + + /** The bottom. */ + public int bottom; + + /* (non-Javadoc) + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "left", "top", "right", + "bottom" }); + } + + /** + * To rectangle. + * + * @return the rectangle + */ + public Rectangle toRectangle() { + return new Rectangle(left, top, right - left, bottom - top); + } + + /* (non-Javadoc) + * @see com.sun.jna.Structure#toString() + */ + public String toString() { + return "[(" + left + "," + top + ")(" + right + "," + bottom + ")]"; + } + } + + /** + * 32-bit unsigned integer. + */ + public static class ULONG extends IntegerType { + + /** + * Instantiates a new ulong. + */ + public ULONG() { + this(0); + } + + /** + * Instantiates a new ulong. + * + * @param value the value + */ + public ULONG(long value) { + super(Native.LONG_SIZE, value, true); + } + + /** + * The Class ByReference. + */ + public static class ByReference implements Structure.ByReference { + + } + } + + /** + * 64-bit unsigned integer. + */ + public static class ULONGLONG extends IntegerType { + + /** + * Instantiates a new ulonglong. + */ + public ULONGLONG() { + this(0); + } + + /** + * Instantiates a new ulonglong. + * + * @param value the value + */ + public ULONGLONG(long value) { + super(8, value, true); + } + } + + /** + * 64-bit unsigned integer. + */ + public static class DWORDLONG extends IntegerType { + + /** + * Instantiates a new dwordlong. + */ + public DWORDLONG() { + this(0); + } + + /** + * Instantiates a new dwordlong. + * + * @param value the value + */ + public DWORDLONG(long value) { + super(8, value, true); + } + } + + /** + * Handle to a bitmap. + */ + public static class HBRUSH extends HANDLE { + + /** + * Instantiates a new hbrush. + */ + public HBRUSH() { + + } + + /** + * Instantiates a new hbrush. + * + * @param p the p + */ + public HBRUSH(Pointer p) { + super(p); + } + } + + /** + * 16-bit unsigned integer. + */ + public static class ATOM extends WORD { + + /** + * Instantiates a new atom. + */ + public ATOM() { + this(0); + } + + /** + * Instantiates a new atom. + * + * @param value the value + */ + public ATOM(long value) { + super(value); + } + } + + /** + * The Class PVOID. + */ + public static class PVOID extends HANDLE { + + /** + * Instantiates a new pvoid. + */ + public PVOID() { + + } + + /** + * Instantiates a new pvoid. + * + * @param p the p + */ + public PVOID(Pointer p) { + super(p); + } + } + + /** + * Message parameter. + */ + public static class LPVOID extends LONG_PTR { + + /** + * Instantiates a new lpvoid. + */ + public LPVOID() { + this(0); + } + + /** + * Instantiates a new lpvoid. + * + * @param value the value + */ + public LPVOID(long value) { + super(value); + } + } + + /** + * The Class POINT. + */ + public class POINT extends Structure { + + /** + * The Class ByReference. + */ + public static class ByReference extends POINT implements + Structure.ByReference { + } + + /** + * Instantiates a new point. + */ + public POINT() { + } + + /** + * Instantiates a new point. + * + * @param memory the memory + */ + public POINT(Pointer memory) { + super(memory); + read(); + } + + /** The y. */ + public int x, y; + + /** + * Instantiates a new point. + * + * @param x the x + * @param y the y + */ + public POINT(int x, int y) { + this.x = x; + this.y = y; + } + + /* (non-Javadoc) + * @see com.sun.jna.Structure#getFieldOrder() + */ + protected List getFieldOrder() { + return Arrays.asList(new String[] { "x", "y" }); + } + } + + /** + * 16-bit unsigned short. + */ + public static class USHORT extends IntegerType { + + /** + * Instantiates a new ushort. + */ + public USHORT() { + this(0); + } + + /** + * Instantiates a new ushort. + * + * @param value the value + */ + public USHORT(long value) { + super(2, value, true); + } + } + + /** + * 32-bit unsigned short. + */ + public static class UINT extends IntegerType { + + /** + * Instantiates a new uint. + */ + public UINT() { + this(0); + } + + /** + * Instantiates a new uint. + * + * @param value the value + */ + public UINT(long value) { + super(4, value, true); + } + } + + /** + * The Class SCODE. + */ + public static class SCODE extends ULONG { + + /** + * Instantiates a new scode. + */ + public SCODE() { + this(0); + } + + /** + * Instantiates a new scode. + * + * @param value the value + */ + public SCODE(long value) { + super(value); + } + + /** + * The Class ByReference. + */ + public static class ByReference implements Structure.ByReference { + + } + } + } diff --git a/contrib/platform/src/com/sun/jna/platform/win32/WinUser.java b/contrib/platform/src/com/sun/jna/platform/win32/WinUser.java index b8224ce080..6c7724fadb 100644 --- a/contrib/platform/src/com/sun/jna/platform/win32/WinUser.java +++ b/contrib/platform/src/com/sun/jna/platform/win32/WinUser.java @@ -15,10 +15,20 @@ import java.util.Arrays; import java.util.List; +import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.Union; +import com.sun.jna.WString; import com.sun.jna.platform.win32.BaseTSD.ULONG_PTR; +import com.sun.jna.platform.win32.WinDef.HBRUSH; +import com.sun.jna.platform.win32.WinDef.HCURSOR; +import com.sun.jna.platform.win32.WinDef.HICON; +import com.sun.jna.platform.win32.WinDef.HINSTANCE; +import com.sun.jna.platform.win32.WinDef.HWND; +import com.sun.jna.platform.win32.WinDef.LPARAM; +import com.sun.jna.platform.win32.WinDef.LRESULT; +import com.sun.jna.platform.win32.WinDef.WPARAM; import com.sun.jna.platform.win32.WinNT.HANDLE; import com.sun.jna.win32.StdCallLibrary; @@ -28,667 +38,863 @@ * @author dblock[at]dblock.org */ public interface WinUser extends StdCallLibrary, WinDef { - HWND HWND_BROADCAST = new HWND(Pointer.createConstant(0xFFFF)); - - int FLASHW_STOP = 0; - int FLASHW_CAPTION = 1; - int FLASHW_TRAY = 2; - int FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY); - int FLASHW_TIMER = 4; - int FLASHW_TIMERNOFG = 12; - - int IMAGE_BITMAP = 0; - int IMAGE_ICON = 1; - int IMAGE_CURSOR = 2; - int IMAGE_ENHMETAFILE = 3; - - int LR_DEFAULTCOLOR = 0x0000; - int LR_MONOCHROME = 0x0001; - int LR_COLOR = 0x0002; - int LR_COPYRETURNORG = 0x0004; - int LR_COPYDELETEORG = 0x0008; - int LR_LOADFROMFILE = 0x0010; - int LR_LOADTRANSPARENT = 0x0020; - int LR_DEFAULTSIZE = 0x0040; - int LR_VGACOLOR = 0x0080; - int LR_LOADMAP3DCOLORS = 0x1000; - int LR_CREATEDIBSECTION = 0x2000; - int LR_COPYFROMRESOURCE = 0x4000; - int LR_SHARED = 0x8000; - - public class GUITHREADINFO extends Structure { - public int cbSize = size(); - public int flags; - public HWND hwndActive; - public HWND hwndFocus; - public HWND hwndCapture; - public HWND hwndMenuOwner; - public HWND hwndMoveSize; - public HWND hwndCaret; - public RECT rcCaret; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "cbSize", "flags", "hwndActive", "hwndFocus", "hwndCapture", "hwndMenuOwner", "hwndMoveSize", "hwndCaret", "rcCaret" }); - } - } - - public class WINDOWINFO extends Structure { - public int cbSize = size(); - public RECT rcWindow; - public RECT rcClient; - public int dwStyle; - public int dwExStyle; - public int dwWindowStatus; - public int cxWindowBorders; - public int cyWindowBorders; - public short atomWindowType; - public short wCreatorVersion; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "cbSize", "rcWindow", "rcClient", "dwStyle", "dwExStyle", "dwWindowStatus", "cxWindowBorders", "cyWindowBorders", "atomWindowType", "wCreatorVersion" }); - } - } - - int GWL_EXSTYLE = -20; - int GWL_STYLE = -16; - int GWL_WNDPROC = -4; - int GWL_HINSTANCE = -6; - int GWL_ID = -12; - int GWL_USERDATA = -21; - int DWL_DLGPROC = 4; - - int DWL_MSGRESULT = 0; - int DWL_USER = 8; - - int WS_MAXIMIZE = 0x01000000; - int WS_VISIBLE = 0x10000000; - int WS_MINIMIZE = 0x20000000; - int WS_CHILD = 0x40000000; - int WS_POPUP = 0x80000000; - int WS_EX_COMPOSITED = 0x20000000; - int WS_EX_LAYERED = 0x80000; - int WS_EX_TRANSPARENT = 32; - - int LWA_COLORKEY = 1; - int LWA_ALPHA = 2; - int ULW_COLORKEY = 1; - int ULW_ALPHA = 2; - int ULW_OPAQUE = 4; - - /** Defines the x- and y-coordinates of a point. */ - public class POINT extends Structure { - public int x, y; - public POINT() { } - public POINT(int x, int y) { - this.x = x; - this.y = y; - } - protected List getFieldOrder() { - return Arrays.asList(new String[] { "x", "y" }); - } - } - - public class MSG extends Structure { - public HWND hWnd; - public int message; - public WPARAM wParam; - public LPARAM lParam; - public int time; - public POINT pt; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "hWnd", "message", "wParam", "lParam", "time", "pt" }); - } - } - - public class FLASHWINFO extends Structure { - public int cbSize; - public HANDLE hWnd; - public int dwFlags; - public int uCount; - public int dwTimeout; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "cbSize", "hWnd", "dwFlags", "uCount", "dwTimeout" }); - } - } - - public interface WNDENUMPROC extends StdCallCallback { - /** Return whether to continue enumeration. */ - boolean callback(HWND hWnd, Pointer data); - } - - public interface LowLevelKeyboardProc extends HOOKPROC { - LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT lParam); - } + HWND HWND_BROADCAST = new HWND(Pointer.createConstant(0xFFFF)); + HWND HWND_MESSAGE = new HWND(Pointer.createConstant(-3)); + + /* RegisterDeviceNotification stuff */ + public static class HDEVNOTIFY extends PVOID { + public HDEVNOTIFY() { + + } + + public HDEVNOTIFY(Pointer p) { + super(p); + } + } + + int FLASHW_STOP = 0; + int FLASHW_CAPTION = 1; + int FLASHW_TRAY = 2; + int FLASHW_ALL = (FLASHW_CAPTION | FLASHW_TRAY); + int FLASHW_TIMER = 4; + int FLASHW_TIMERNOFG = 12; + + int IMAGE_BITMAP = 0; + int IMAGE_ICON = 1; + int IMAGE_CURSOR = 2; + int IMAGE_ENHMETAFILE = 3; + + int LR_DEFAULTCOLOR = 0x0000; + int LR_MONOCHROME = 0x0001; + int LR_COLOR = 0x0002; + int LR_COPYRETURNORG = 0x0004; + int LR_COPYDELETEORG = 0x0008; + int LR_LOADFROMFILE = 0x0010; + int LR_LOADTRANSPARENT = 0x0020; + int LR_DEFAULTSIZE = 0x0040; + int LR_VGACOLOR = 0x0080; + int LR_LOADMAP3DCOLORS = 0x1000; + int LR_CREATEDIBSECTION = 0x2000; + int LR_COPYFROMRESOURCE = 0x4000; + int LR_SHARED = 0x8000; + + public class GUITHREADINFO extends Structure { + public int cbSize = size(); + public int flags; + public HWND hwndActive; + public HWND hwndFocus; + public HWND hwndCapture; + public HWND hwndMenuOwner; + public HWND hwndMoveSize; + public HWND hwndCaret; + public RECT rcCaret; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cbSize", "flags", + "hwndActive", "hwndFocus", "hwndCapture", "hwndMenuOwner", + "hwndMoveSize", "hwndCaret", "rcCaret" }); + } + } + + public class WINDOWINFO extends Structure { + public int cbSize = size(); + public RECT rcWindow; + public RECT rcClient; + public int dwStyle; + public int dwExStyle; + public int dwWindowStatus; + public int cxWindowBorders; + public int cyWindowBorders; + public short atomWindowType; + public short wCreatorVersion; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cbSize", "rcWindow", + "rcClient", "dwStyle", "dwExStyle", "dwWindowStatus", + "cxWindowBorders", "cyWindowBorders", "atomWindowType", + "wCreatorVersion" }); + } + } + + int GWL_EXSTYLE = -20; + int GWL_STYLE = -16; + int GWL_WNDPROC = -4; + int GWL_HINSTANCE = -6; + int GWL_ID = -12; + int GWL_USERDATA = -21; + int DWL_DLGPROC = 4; + + int DWL_MSGRESULT = 0; + int DWL_USER = 8; + + int WS_MAXIMIZE = 0x01000000; + int WS_VISIBLE = 0x10000000; + int WS_MINIMIZE = 0x20000000; + int WS_CHILD = 0x40000000; + int WS_POPUP = 0x80000000; + int WS_EX_COMPOSITED = 0x20000000; + int WS_EX_LAYERED = 0x80000; + int WS_EX_TRANSPARENT = 32; + + int LWA_COLORKEY = 1; + int LWA_ALPHA = 2; + int ULW_COLORKEY = 1; + int ULW_ALPHA = 2; + int ULW_OPAQUE = 4; + + /** Defines the x- and y-coordinates of a point. */ + public class POINT extends Structure { + public int x, y; + + public POINT() { + } + + public POINT(int x, int y) { + this.x = x; + this.y = y; + } + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "x", "y" }); + } + } + + public class MSG extends Structure { + public HWND hWnd; + public int message; + public WPARAM wParam; + public LPARAM lParam; + public int time; + public POINT pt; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "hWnd", "message", "wParam", + "lParam", "time", "pt" }); + } + } + + public class FLASHWINFO extends Structure { + public int cbSize; + public HANDLE hWnd; + public int dwFlags; + public int uCount; + public int dwTimeout; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cbSize", "hWnd", "dwFlags", + "uCount", "dwTimeout" }); + } + } + + public interface WNDENUMPROC extends StdCallCallback { + /** Return whether to continue enumeration. */ + boolean callback(HWND hWnd, Pointer data); + } + + public interface LowLevelKeyboardProc extends HOOKPROC { + LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT lParam); + } + + /** Specifies the width and height of a rectangle. */ + public class SIZE extends Structure { + public int cx, cy; + + public SIZE() { + } + + public SIZE(int w, int h) { + this.cx = w; + this.cy = h; + } + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cx", "cy" }); + } + } + + int AC_SRC_OVER = 0x00; + int AC_SRC_ALPHA = 0x01; + int AC_SRC_NO_PREMULT_ALPHA = 0x01; + int AC_SRC_NO_ALPHA = 0x02; + + public class BLENDFUNCTION extends Structure { + public byte BlendOp = AC_SRC_OVER; // only valid value + public byte BlendFlags = 0; // only valid value + public byte SourceConstantAlpha; + public byte AlphaFormat; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "BlendOp", "BlendFlags", + "SourceConstantAlpha", "AlphaFormat" }); + } + } + + int VK_SHIFT = 16; + int VK_LSHIFT = 0xA0; + int VK_RSHIFT = 0xA1; + int VK_CONTROL = 17; + int VK_LCONTROL = 0xA2; + int VK_RCONTROL = 0xA3; + int VK_MENU = 18; + int VK_LMENU = 0xA4; + int VK_RMENU = 0xA5; + + int MOD_ALT = 0x0001; + int MOD_CONTROL = 0x0002; + int MOD_NOREPEAT = 0x4000; + int MOD_SHIFT = 0x0004; + int MOD_WIN = 0x0008; + + int WH_KEYBOARD = 2; + int WH_MOUSE = 7; + int WH_KEYBOARD_LL = 13; + int WH_MOUSE_LL = 14; + + public class HHOOK extends HANDLE { + + } + + public interface HOOKPROC extends StdCallCallback { + + } + + /** + * The WM_PAINT message is sent when the system or another application makes + * a request to paint a portion of an \ application's window. + */ + int WM_PAINT = 0x000F; + + /** + * Sent as a signal that a window or an application should terminate. + */ + int WM_CLOSE = 0x0010; + + /** + * Indicates a request to terminate an application, and is generated when + * the application calls the PostQuitMessage function. + */ + int WM_QUIT = 0x0012; + + /** + * Sent to a window when the window is about to be hidden or shown. + */ + int WM_SHOWWINDOW = 0x0018; + + /** + * Sent to the parent window of an owner-drawn button, combo box, list box, + * or menu when a visual aspect of the button, combo box, list box, or menu + * has changed. + */ + int WM_DRAWITEM = 0x002B; + + /** + * Posted to the window with the keyboard focus when a nonsystem key is + * pressed. A nonsystem key is a key that is pressed when the ALT key is not + * pressed. + */ + int WM_KEYDOWN = 0x0100; + + /** + * Posted to the window with the keyboard focus when a WM_KEYDOWN message is + * translated by the TranslateMessage function. The WM_CHAR message contains + * the character code of the key that was pressed. + */ + int WM_CHAR = 0x0102; + + /** + * A window receives this message when the user chooses a command from the + * Window menu (formerly known as the system or control menu) or when the + * user chooses the maximize button, minimize button, restore button, or + * close button. + */ + int WM_SYSCOMMAND = 0x0112; + + /** + * An application sends the WM_MDIMAXIMIZE message to a multiple-document + * interface (MDI) client window to maximize an MDI child window. + */ + int WM_MDIMAXIMIZE = 0x0225; + + /** + * Posted when the user presses a hot key registered by the RegisterHotKey + * function. The message is placed at the top of the message queue + * associated with the thread that registered the hot key. + */ + int WM_HOTKEY = 0x0312; + + int WM_KEYUP = 257; + int WM_SYSKEYDOWN = 260; + int WM_SYSKEYUP = 261; + + int WM_SESSION_CHANGE = 0x2b1; + int WM_CREATE = 0x0001; + int WM_SIZE = 0x0005; + int WM_DESTROY = 0x0002; + + public static final int WM_DEVICECHANGE = 0x0219; + + public class KBDLLHOOKSTRUCT extends Structure { + public int vkCode; + public int scanCode; + public int flags; + public int time; + public ULONG_PTR dwExtraInfo; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "vkCode", "scanCode", "flags", + "time", "dwExtraInfo" }); + } + } + + int SM_CXSCREEN = 0; + int SM_CYSCREEN = 1; + int SM_CXVSCROLL = 2; + int SM_CYHSCROLL = 3; + int SM_CYCAPTION = 4; + int SM_CXBORDER = 5; + int SM_CYBORDER = 6; + int SM_CXDLGFRAME = 7; + int SM_CYDLGFRAME = 8; + int SM_CYVTHUMB = 9; + int SM_CXHTHUMB = 10; + int SM_CXICON = 11; + int SM_CYICON = 12; + int SM_CXCURSOR = 13; + int SM_CYCURSOR = 14; + int SM_CYMENU = 15; + int SM_CXFULLSCREEN = 16; + int SM_CYFULLSCREEN = 17; + int SM_CYKANJIWINDOW = 18; + int SM_MOUSEPRESENT = 19; + int SM_CYVSCROLL = 20; + int SM_CXHSCROLL = 21; + int SM_DEBUG = 22; + int SM_SWAPBUTTON = 23; + int SM_RESERVED1 = 24; + int SM_RESERVED2 = 25; + int SM_RESERVED3 = 26; + int SM_RESERVED4 = 27; + int SM_CXMIN = 28; + int SM_CYMIN = 29; + int SM_CXSIZE = 30; + int SM_CYSIZE = 31; + int SM_CXFRAME = 32; + int SM_CYFRAME = 33; + int SM_CXMINTRACK = 34; + int SM_CYMINTRACK = 35; + int SM_CXDOUBLECLK = 36; + int SM_CYDOUBLECLK = 37; + int SM_CXICONSPACING = 38; + int SM_CYICONSPACING = 39; + int SM_MENUDROPALIGNMENT = 40; + int SM_PENWINDOWS = 41; + int SM_DBCSENABLED = 42; + int SM_CMOUSEBUTTONS = 43; + + int SM_CXFIXEDFRAME = SM_CXDLGFRAME; /* ;win40 name change */ + int SM_CYFIXEDFRAME = SM_CYDLGFRAME; /* ;win40 name change */ + int SM_CXSIZEFRAME = SM_CXFRAME; /* ;win40 name change */ + int SM_CYSIZEFRAME = SM_CYFRAME; /* ;win40 name change */ + + int SM_SECURE = 44; + int SM_CXEDGE = 45; + int SM_CYEDGE = 46; + int SM_CXMINSPACING = 47; + int SM_CYMINSPACING = 48; + int SM_CXSMICON = 49; + int SM_CYSMICON = 50; + int SM_CYSMCAPTION = 51; + int SM_CXSMSIZE = 52; + int SM_CYSMSIZE = 53; + int SM_CXMENUSIZE = 54; + int SM_CYMENUSIZE = 55; + int SM_ARRANGE = 56; + int SM_CXMINIMIZED = 57; + int SM_CYMINIMIZED = 58; + int SM_CXMAXTRACK = 59; + int SM_CYMAXTRACK = 60; + int SM_CXMAXIMIZED = 61; + int SM_CYMAXIMIZED = 62; + int SM_NETWORK = 63; + int SM_CLEANBOOT = 67; + int SM_CXDRAG = 68; + int SM_CYDRAG = 69; + int SM_SHOWSOUNDS = 70; + int SM_CXMENUCHECK = 71; + int SM_CYMENUCHECK = 72; + int SM_SLOWMACHINE = 73; + int SM_MIDEASTENABLED = 74; + int SM_MOUSEWHEELPRESENT = 75; + int SM_XVIRTUALSCREEN = 76; + int SM_YVIRTUALSCREEN = 77; + int SM_CXVIRTUALSCREEN = 78; + int SM_CYVIRTUALSCREEN = 79; + int SM_CMONITORS = 80; + int SM_SAMEDISPLAYFORMAT = 81; + int SM_IMMENABLED = 82; + int SM_CXFOCUSBORDER = 83; + int SM_CYFOCUSBORDER = 84; + int SM_TABLETPC = 86; + int SM_MEDIACENTER = 87; + int SM_STARTER = 88; + int SM_SERVERR2 = 89; + int SM_MOUSEHORIZONTALWHEELPRESENT = 91; + int SM_CXPADDEDBORDER = 92; + int SM_REMOTESESSION = 0x1000; + int SM_SHUTTINGDOWN = 0x2000; + int SM_REMOTECONTROL = 0x2001; + int SM_CARETBLINKINGENABLED = 0x2002; + + int SW_HIDE = 0; + int SW_SHOWNORMAL = 1; + int SW_NORMAL = 1; + int SW_SHOWMINIMIZED = 2; + int SW_SHOWMAXIMIZED = 3; + int SW_MAXIMIZE = 3; + int SW_SHOWNOACTIVATE = 4; + int SW_SHOW = 5; + int SW_MINIMIZE = 6; + int SW_SHOWMINNOACTIVE = 7; + int SW_SHOWNA = 8; + int SW_RESTORE = 9; + int SW_SHOWDEFAULT = 10; + int SW_FORCEMINIMIZE = 11; + int SW_MAX = 11; + + int RDW_INVALIDATE = 0x0001; + int RDW_INTERNALPAINT = 0x0002; + int RDW_ERASE = 0x0004; + int RDW_VALIDATE = 0x0008; + int RDW_NOINTERNALPAINT = 0x0010; + int RDW_NOERASE = 0x0020; + int RDW_NOCHILDREN = 0x0040; + int RDW_ALLCHILDREN = 0x0080; + int RDW_UPDATENOW = 0x0100; + int RDW_ERASENOW = 0x0200; + int RDW_FRAME = 0x0400; + int RDW_NOFRAME = 0x0800; + + /** + * The retrieved handle identifies the window of the same type that is + * highest in the Z order. + * + * If the specified window is a topmost window, the handle identifies a + * topmost window. If the specified window is a top-level window, the handle + * identifies a top-level window. If the specified window is a child window, + * the handle identifies a sibling window. + */ + int GW_HWNDFIRST = 0; + + /** + * The retrieved handle identifies the window of the same type that is + * lowest in the Z order. + * + * If the specified window is a topmost window, the handle identifies a + * topmost window. If the specified window is a top-level window, the handle + * identifies a top-level window. If the specified window is a child window, + * the handle identifies a sibling window. + */ + int GW_HWNDLAST = 1; + + /** + * The retrieved handle identifies the window below the specified window in + * the Z order. + * + * If the specified window is a topmost window, the handle identifies a + * topmost window. If the specified window is a top-level window, the handle + * identifies a top-level window. If the specified window is a child window, + * the handle identifies a sibling window. + */ + int GW_HWNDNEXT = 2; + + /** + * The retrieved handle identifies the window above the specified window in + * the Z order. + * + * If the specified window is a topmost window, the handle identifies a + * topmost window. If the specified window is a top-level window, the handle + * identifies a top-level window. If the specified window is a child window, + * the handle identifies a sibling window. + */ + int GW_HWNDPREV = 3; + + /** + * The retrieved handle identifies the specified window's owner window, if + * any. For more information, see Owned Windows. + */ + int GW_OWNER = 4; + + /** + * The retrieved handle identifies the child window at the top of the Z + * order, if the specified window is a parent window; otherwise, the + * retrieved handle is NULL. The function examines only child windows of the + * specified window. It does not examine descendant windows. + */ + int GW_CHILD = 5; + + /** + * The retrieved handle identifies the enabled popup window owned by the + * specified window (the search uses the first such window found using + * GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the + * retrieved handle is that of the specified window. + */ + int GW_ENABLEDPOPUP = 6; + + /** + * Retains the current Z order (ignores the hWndInsertAfter parameter). + */ + int SWP_NOZORDER = 0x0004; + + /** + * Minimizes the window. + */ + int SC_MINIMIZE = 0xF020; + + /** + * Maximizes the window. + */ + int SC_MAXIMIZE = 0xF030; + + /** + * Contains information about a simulated message generated by an input + * device other than a keyboard or mouse. + */ + public static class HARDWAREINPUT extends Structure { + + public static class ByReference extends HARDWAREINPUT implements + Structure.ByReference { + public ByReference() { + } + + public ByReference(Pointer memory) { + super(memory); + } + } + + public HARDWAREINPUT() { + } + + public HARDWAREINPUT(Pointer memory) { + super(memory); + read(); + } + + public WinDef.DWORD uMsg; + public WinDef.WORD wParamL; + public WinDef.WORD wParamH; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "uMsg", "wParamL", "wParamH" }); + } + } + + /** + * Used by SendInput to store information for synthesizing input events such + * as keystrokes, mouse movement, and mouse clicks. + */ + public static class INPUT extends Structure { + + public static final int INPUT_MOUSE = 0; + public static final int INPUT_KEYBOARD = 1; + public static final int INPUT_HARDWARE = 2; + + public static class ByReference extends INPUT implements + Structure.ByReference { + public ByReference() { + } + + public ByReference(Pointer memory) { + super(memory); + } + } + + public INPUT() { + } + + public INPUT(Pointer memory) { + super(memory); + read(); + } + + public WinDef.DWORD type; + public INPUT_UNION input = new INPUT_UNION(); + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "type", "input" }); + } + + public static class INPUT_UNION extends Union { + + public INPUT_UNION() { + } + + public INPUT_UNION(Pointer memory) { + super(memory); + read(); + } + + public MOUSEINPUT mi; + public KEYBDINPUT ki; + public HARDWAREINPUT hi; + } + } + + /** + * Contains information about a simulated keyboard event. + */ + public static class KEYBDINPUT extends Structure { + + /** + * If specified, the scan code was preceded by a prefix byte that has + * the value 0xE0 (224). + */ + public static final int KEYEVENTF_EXTENDEDKEY = 0x0001; + + /** + * If specified, the key is being released. If not specified, the key is + * being pressed. + */ + public static final int KEYEVENTF_KEYUP = 0x0002; + + /** + * If specified, the system synthesizes a VK_PACKET keystroke. The wVk + * parameter must be zero. This flag can only be combined with the + * KEYEVENTF_KEYUP flag. For more information, see the Remarks section. + */ + public static final int KEYEVENTF_UNICODE = 0x0004; + + /** + * If specified, wScan identifies the key and wVk is ignored. + */ + public static final int KEYEVENTF_SCANCODE = 0x0008; + + public static class ByReference extends KEYBDINPUT implements + Structure.ByReference { + public ByReference() { + } + + public ByReference(Pointer memory) { + super(memory); + } + } + + public KEYBDINPUT() { + } + + public KEYBDINPUT(Pointer memory) { + super(memory); + read(); + } + + /** + * A virtual-key code. The code must be a value in the range 1 to 254. + * If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0. + */ + public WinDef.WORD wVk; + + /** + * A hardware scan code for the key. If dwFlags specifies + * KEYEVENTF_UNICODE, wScan specifies a Unicode character which is to be + * sent to the foreground application. + */ + public WinDef.WORD wScan; + + /** + * Specifies various aspects of a keystroke. This member can be certain + * combinations of the following values. + */ + public WinDef.DWORD dwFlags; + + /** + * The time stamp for the event, in milliseconds. If this parameter is + * zero, the system will provide its own time stamp. + */ + public WinDef.DWORD time; + + /** + * An additional value associated with the keystroke. Use the + * GetMessageExtraInfo function to obtain this information. + */ + public BaseTSD.ULONG_PTR dwExtraInfo; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "wVk", "wScan", "dwFlags", + "time", "dwExtraInfo" }); + } + } + + /** + * Contains information about a simulated mouse event. + */ + public static class MOUSEINPUT extends Structure { + + public static class ByReference extends MOUSEINPUT implements + Structure.ByReference { + public ByReference() { + } + + public ByReference(Pointer memory) { + super(memory); + } + } + + public MOUSEINPUT() { + } + + public MOUSEINPUT(Pointer memory) { + super(memory); + read(); + } + + public WinDef.LONG dx; + public WinDef.LONG dy; + public WinDef.DWORD mouseData; + public WinDef.DWORD dwFlags; + public WinDef.DWORD time; + public BaseTSD.ULONG_PTR dwExtraInfo; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "dx", "dy", "mouseData", + "dwFlags", "time", "dwExtraInfo" }); + } + } + + /** + * Contains the time of the last input. + */ + public static class LASTINPUTINFO extends Structure { + public int cbSize = size(); + + // Tick count of when the last input event was received. + public int dwTime; + + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cbSize", "dwTime" }); + } + } + + /** + * Contains window class information. It is used with the RegisterClassEx + * and GetClassInfoEx functions. + * + * The WNDCLASSEX structure is similar to the WNDCLASS structure. There are + * two differences. WNDCLASSEX includes the cbSize member, which specifies + * the size of the structure, and the hIconSm member, which contains a + * handle to a small icon associated with the window class. + */ + public class WNDCLASSEX extends Structure { + + /** + * The Class ByReference. + */ + public static class ByReference extends WNDCLASSEX implements + Structure.ByReference { + } + + /** + * Instantiates a new wndclassex. + */ + public WNDCLASSEX() { + } + + /** + * Instantiates a new wndclassex. + * + * @param memory + * the memory + */ + public WNDCLASSEX(Pointer memory) { + super(memory); + read(); + } + + /** The cb size. */ + public int cbSize = this.size(); + + /** The style. */ + public int style; + + /** The lpfn wnd proc. */ + public Callback lpfnWndProc; + + /** The cb cls extra. */ + public int cbClsExtra; + + /** The cb wnd extra. */ + public int cbWndExtra; + + /** The h instance. */ + public HINSTANCE hInstance; + + /** The h icon. */ + public HICON hIcon; + + /** The h cursor. */ + public HCURSOR hCursor; + + /** The hbr background. */ + public HBRUSH hbrBackground; + + /** The lpsz menu name. */ + public String lpszMenuName; + + /** The lpsz class name. */ + public WString lpszClassName; + + /** The h icon sm. */ + public HICON hIconSm; + + /* + * (non-Javadoc) + * + * @see com.sun.jna.Structure#getFieldOrder() + */ + @Override + protected List getFieldOrder() { + return Arrays.asList(new String[] { "cbSize", "style", + "lpfnWndProc", "cbClsExtra", "cbWndExtra", "hInstance", + "hIcon", "hCursor", "hbrBackground", "lpszMenuName", + "lpszClassName", "hIconSm" }); + } + } + + /** + * An application-defined function that processes messages sent to a window. + * The WNDPROC type defines a pointer to this callback function. + * + * WindowProc is a placeholder for the application-defined function name. + */ + public interface WindowProc extends Callback { + + /** + * @param hwnd + * [in] Type: HWND + * + * A handle to the window. + * + * @param uMsg + * [in] Type: UINT + * + * The message. + * + * For lists of the system-provided messages, see + * System-Defined Messages. + * + * @param wParam + * [in] Type: WPARAM + * + * Additional message information. The contents of this + * parameter depend on the value of the uMsg parameter. + * + * @param lParam + * [in] Type: LPARAM + * + * Additional message information. The contents of this + * parameter depend on the value of the uMsg parameter. + * + * @return the lresult + */ + LRESULT callback(HWND hwnd, int uMsg, WPARAM wParam, LPARAM lParam); + } - /** Specifies the width and height of a rectangle. */ - public class SIZE extends Structure { - public int cx, cy; - public SIZE() { } - public SIZE(int w, int h) { - this.cx = w; - this.cy = h; - } - protected List getFieldOrder() { - return Arrays.asList(new String[] { "cx", "cy" }); - } - } - - int AC_SRC_OVER = 0x00; - int AC_SRC_ALPHA = 0x01; - int AC_SRC_NO_PREMULT_ALPHA = 0x01; - int AC_SRC_NO_ALPHA = 0x02; - - public class BLENDFUNCTION extends Structure { - public byte BlendOp = AC_SRC_OVER; // only valid value - public byte BlendFlags = 0; // only valid value - public byte SourceConstantAlpha; - public byte AlphaFormat; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "BlendOp", "BlendFlags", "SourceConstantAlpha", "AlphaFormat"}); - } - } - - int VK_SHIFT = 16; - int VK_LSHIFT = 0xA0; - int VK_RSHIFT = 0xA1; - int VK_CONTROL = 17; - int VK_LCONTROL = 0xA2; - int VK_RCONTROL = 0xA3; - int VK_MENU = 18; - int VK_LMENU = 0xA4; - int VK_RMENU = 0xA5; - - int MOD_ALT = 0x0001; - int MOD_CONTROL = 0x0002; - int MOD_NOREPEAT = 0x4000; - int MOD_SHIFT = 0x0004; - int MOD_WIN = 0x0008; - - int WH_KEYBOARD = 2; - int WH_MOUSE = 7; - int WH_KEYBOARD_LL = 13; - int WH_MOUSE_LL = 14; - - public class HHOOK extends HANDLE { - - } - - public interface HOOKPROC extends StdCallCallback { - - } - - /** - * The WM_PAINT message is sent when the system or another application makes a request to paint a portion of an \ - * application's window. - */ - int WM_PAINT = 0x000F; - - /** - * Sent as a signal that a window or an application should terminate. - */ - int WM_CLOSE = 0x0010; - - /** - * Indicates a request to terminate an application, and is generated when the application calls the PostQuitMessage - * function. - */ - int WM_QUIT = 0x0012; - - /** - * Sent to a window when the window is about to be hidden or shown. - */ - int WM_SHOWWINDOW = 0x0018; - - /** - * Sent to the parent window of an owner-drawn button, combo box, list box, or menu when a visual aspect of the - * button, combo box, list box, or menu has changed. - */ - int WM_DRAWITEM = 0x002B; - - /** - * Posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is - * pressed when the ALT key is not pressed. - */ - int WM_KEYDOWN = 0x0100; - - /** - * Posted to the window with the keyboard focus when a WM_KEYDOWN message is translated by the TranslateMessage - * function. The WM_CHAR message contains the character code of the key that was pressed. - */ - int WM_CHAR = 0x0102; - - /** - * A window receives this message when the user chooses a command from the Window menu (formerly known as the system - * or control menu) or when the user chooses the maximize button, minimize button, restore button, or close button. - */ - int WM_SYSCOMMAND = 0x0112; - - /** - * An application sends the WM_MDIMAXIMIZE message to a multiple-document interface (MDI) client window to maximize - * an MDI child window. - */ - int WM_MDIMAXIMIZE = 0x0225; - - /** - * Posted when the user presses a hot key registered by the RegisterHotKey function. - * The message is placed at the top of the message queue associated with the thread that registered the hot key. - */ - int WM_HOTKEY = 0x0312; - - int WM_KEYUP = 257; - int WM_SYSKEYDOWN = 260; - int WM_SYSKEYUP = 261; - - public class KBDLLHOOKSTRUCT extends Structure { - public int vkCode; - public int scanCode; - public int flags; - public int time; - public ULONG_PTR dwExtraInfo; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "vkCode", "scanCode", "flags", "time", "dwExtraInfo" }); - } - } - - int SM_CXSCREEN = 0; - int SM_CYSCREEN = 1; - int SM_CXVSCROLL = 2; - int SM_CYHSCROLL = 3; - int SM_CYCAPTION = 4; - int SM_CXBORDER = 5; - int SM_CYBORDER = 6; - int SM_CXDLGFRAME = 7; - int SM_CYDLGFRAME = 8; - int SM_CYVTHUMB = 9; - int SM_CXHTHUMB = 10; - int SM_CXICON = 11; - int SM_CYICON = 12; - int SM_CXCURSOR = 13; - int SM_CYCURSOR = 14; - int SM_CYMENU = 15; - int SM_CXFULLSCREEN = 16; - int SM_CYFULLSCREEN = 17; - int SM_CYKANJIWINDOW = 18; - int SM_MOUSEPRESENT = 19; - int SM_CYVSCROLL = 20; - int SM_CXHSCROLL = 21; - int SM_DEBUG = 22; - int SM_SWAPBUTTON = 23; - int SM_RESERVED1 = 24; - int SM_RESERVED2 = 25; - int SM_RESERVED3 = 26; - int SM_RESERVED4 = 27; - int SM_CXMIN = 28; - int SM_CYMIN = 29; - int SM_CXSIZE = 30; - int SM_CYSIZE = 31; - int SM_CXFRAME = 32; - int SM_CYFRAME = 33; - int SM_CXMINTRACK = 34; - int SM_CYMINTRACK = 35; - int SM_CXDOUBLECLK = 36; - int SM_CYDOUBLECLK = 37; - int SM_CXICONSPACING = 38; - int SM_CYICONSPACING = 39; - int SM_MENUDROPALIGNMENT = 40; - int SM_PENWINDOWS = 41; - int SM_DBCSENABLED = 42; - int SM_CMOUSEBUTTONS = 43; - - int SM_CXFIXEDFRAME = SM_CXDLGFRAME; /* ;win40 name change */ - int SM_CYFIXEDFRAME = SM_CYDLGFRAME; /* ;win40 name change */ - int SM_CXSIZEFRAME = SM_CXFRAME; /* ;win40 name change */ - int SM_CYSIZEFRAME = SM_CYFRAME; /* ;win40 name change */ - - int SM_SECURE = 44; - int SM_CXEDGE = 45; - int SM_CYEDGE = 46; - int SM_CXMINSPACING = 47; - int SM_CYMINSPACING = 48; - int SM_CXSMICON = 49; - int SM_CYSMICON = 50; - int SM_CYSMCAPTION = 51; - int SM_CXSMSIZE = 52; - int SM_CYSMSIZE = 53; - int SM_CXMENUSIZE = 54; - int SM_CYMENUSIZE = 55; - int SM_ARRANGE = 56; - int SM_CXMINIMIZED = 57; - int SM_CYMINIMIZED = 58; - int SM_CXMAXTRACK = 59; - int SM_CYMAXTRACK = 60; - int SM_CXMAXIMIZED = 61; - int SM_CYMAXIMIZED = 62; - int SM_NETWORK = 63; - int SM_CLEANBOOT = 67; - int SM_CXDRAG = 68; - int SM_CYDRAG = 69; - int SM_SHOWSOUNDS = 70; - int SM_CXMENUCHECK = 71; - int SM_CYMENUCHECK = 72; - int SM_SLOWMACHINE = 73; - int SM_MIDEASTENABLED = 74; - int SM_MOUSEWHEELPRESENT = 75; - int SM_XVIRTUALSCREEN = 76; - int SM_YVIRTUALSCREEN = 77; - int SM_CXVIRTUALSCREEN = 78; - int SM_CYVIRTUALSCREEN = 79; - int SM_CMONITORS = 80; - int SM_SAMEDISPLAYFORMAT = 81; - int SM_IMMENABLED = 82; - int SM_CXFOCUSBORDER = 83; - int SM_CYFOCUSBORDER = 84; - int SM_TABLETPC = 86; - int SM_MEDIACENTER = 87; - int SM_STARTER = 88; - int SM_SERVERR2 = 89; - int SM_MOUSEHORIZONTALWHEELPRESENT = 91; - int SM_CXPADDEDBORDER = 92; - int SM_REMOTESESSION = 0x1000; - int SM_SHUTTINGDOWN = 0x2000; - int SM_REMOTECONTROL = 0x2001; - int SM_CARETBLINKINGENABLED = 0x2002; - - int SW_HIDE = 0; - int SW_SHOWNORMAL = 1; - int SW_NORMAL = 1; - int SW_SHOWMINIMIZED = 2; - int SW_SHOWMAXIMIZED = 3; - int SW_MAXIMIZE = 3; - int SW_SHOWNOACTIVATE = 4; - int SW_SHOW = 5; - int SW_MINIMIZE = 6; - int SW_SHOWMINNOACTIVE = 7; - int SW_SHOWNA = 8; - int SW_RESTORE = 9; - int SW_SHOWDEFAULT = 10; - int SW_FORCEMINIMIZE = 11; - int SW_MAX = 11; - - int RDW_INVALIDATE = 0x0001; - int RDW_INTERNALPAINT = 0x0002; - int RDW_ERASE = 0x0004; - int RDW_VALIDATE = 0x0008; - int RDW_NOINTERNALPAINT = 0x0010; - int RDW_NOERASE = 0x0020; - int RDW_NOCHILDREN = 0x0040; - int RDW_ALLCHILDREN = 0x0080; - int RDW_UPDATENOW = 0x0100; - int RDW_ERASENOW = 0x0200; - int RDW_FRAME = 0x0400; - int RDW_NOFRAME = 0x0800; - - /** - * The retrieved handle identifies the window of the same type that is highest in the Z order. - * - * If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a - * top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle - * identifies a sibling window. - */ - int GW_HWNDFIRST = 0; - - /** - * The retrieved handle identifies the window of the same type that is lowest in the Z order. - * - * If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a - * top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle - * identifies a sibling window. - */ - int GW_HWNDLAST = 1; - - /** - * The retrieved handle identifies the window below the specified window in the Z order. - * - * If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a - * top-level window, the handle identifies a top-level window. If the specified window is a child window, the handle - * identifies a sibling window. - */ - int GW_HWNDNEXT = 2; - - /** - * The retrieved handle identifies the window above the specified window in the Z order. - * - * If the specified window is a topmost window, the handle identifies a topmost window. If the specified window is a - * top-level window, the handle identifies a top-level window. If the specified window is a child window, the - * handle identifies a sibling window. - */ - int GW_HWNDPREV = 3; - - /** - * The retrieved handle identifies the specified window's owner window, if any. For more information, see Owned - * Windows. - */ - int GW_OWNER = 4; - - /** - * The retrieved handle identifies the child window at the top of the Z order, if the specified window is a parent - * window; otherwise, the retrieved handle is NULL. The function examines only child windows of the specified - * window. It does not examine descendant windows. - */ - int GW_CHILD = 5; - - /** - * The retrieved handle identifies the enabled popup window owned by the specified window (the search uses the first - * such window found using GW_HWNDNEXT); otherwise, if there are no enabled popup windows, the retrieved handle is - * that of the specified window. - */ - int GW_ENABLEDPOPUP = 6; - - /** - * Retains the current Z order (ignores the hWndInsertAfter parameter). - */ - int SWP_NOZORDER = 0x0004; - - /** - * Minimizes the window. - */ - int SC_MINIMIZE = 0xF020; - - /** - * Maximizes the window. - */ - int SC_MAXIMIZE = 0xF030; - - /** - * Contains information about a simulated message generated by an input device other than a keyboard or mouse. - */ - public static class HARDWAREINPUT extends Structure { - - public static class ByReference extends HARDWAREINPUT implements Structure.ByReference { - public ByReference() { - } - - public ByReference(Pointer memory) { - super(memory); - } - } - - public HARDWAREINPUT() { - } - - public HARDWAREINPUT(Pointer memory) { - super(memory); - read(); - } - - public WinDef.DWORD uMsg; - public WinDef.WORD wParamL; - public WinDef.WORD wParamH; - protected List getFieldOrder() { - return Arrays.asList(new String[] { "uMsg", "wParamL", "wParamH" }); - } - } - - /** - * Used by SendInput to store information for synthesizing input events such as keystrokes, mouse movement, and mouse - * clicks. - */ - public static class INPUT extends Structure { - - public static final int INPUT_MOUSE = 0; - public static final int INPUT_KEYBOARD = 1; - public static final int INPUT_HARDWARE = 2; - - public static class ByReference extends INPUT implements Structure.ByReference { - public ByReference() { - } - - public ByReference(Pointer memory) { - super(memory); - } - } - - public INPUT() { - } - - public INPUT(Pointer memory) { - super(memory); - read(); - } - - public WinDef.DWORD type; - public INPUT_UNION input = new INPUT_UNION(); - protected List getFieldOrder() { - return Arrays.asList(new String[] { "type", "input" }); - } - - public static class INPUT_UNION extends Union { - - public INPUT_UNION() { - } - - public INPUT_UNION(Pointer memory) { - super(memory); - read(); - } - - public MOUSEINPUT mi; - public KEYBDINPUT ki; - public HARDWAREINPUT hi; - } - } - - /** - * Contains information about a simulated keyboard event. - */ - public static class KEYBDINPUT extends Structure { - - /** - * If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224). - */ - public static final int KEYEVENTF_EXTENDEDKEY = 0x0001; - - /** - * If specified, the key is being released. If not specified, the key is being pressed. - */ - public static final int KEYEVENTF_KEYUP = 0x0002; - - /** - * If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero. This flag can only be - * combined with the KEYEVENTF_KEYUP flag. For more information, see the Remarks section. - */ - public static final int KEYEVENTF_UNICODE = 0x0004; - - /** - * If specified, wScan identifies the key and wVk is ignored. - */ - public static final int KEYEVENTF_SCANCODE = 0x0008; - - public static class ByReference extends KEYBDINPUT implements Structure.ByReference { - public ByReference() { - } - - public ByReference(Pointer memory) { - super(memory); - } - } - - public KEYBDINPUT() { - } - - public KEYBDINPUT(Pointer memory) { - super(memory); - read(); - } - - /** - * A virtual-key code. The code must be a value in the range 1 to 254. If the dwFlags member specifies - * KEYEVENTF_UNICODE, wVk must be 0. - */ - public WinDef.WORD wVk; - - /** - * A hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, wScan specifies a Unicode character - * which is to be sent to the foreground application. - */ - public WinDef.WORD wScan; - - /** - * Specifies various aspects of a keystroke. This member can be certain combinations of the following values. - */ - public WinDef.DWORD dwFlags; - - /** - * The time stamp for the event, in milliseconds. If this parameter is zero, the system will provide its own time - * stamp. - */ - public WinDef.DWORD time; - - /** - * An additional value associated with the keystroke. Use the GetMessageExtraInfo function to obtain this - * information. - */ - public BaseTSD.ULONG_PTR dwExtraInfo; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "wVk", "wScan", "dwFlags", "time", "dwExtraInfo" }); - } - } - - /** - * Contains information about a simulated mouse event. - */ - public static class MOUSEINPUT extends Structure { - - public static class ByReference extends MOUSEINPUT implements Structure.ByReference { - public ByReference() { - } - - public ByReference(Pointer memory) { - super(memory); - } - } - - public MOUSEINPUT() { - } - - public MOUSEINPUT(Pointer memory) { - super(memory); - read(); - } - - public WinDef.LONG dx; - public WinDef.LONG dy; - public WinDef.DWORD mouseData; - public WinDef.DWORD dwFlags; - public WinDef.DWORD time; - public BaseTSD.ULONG_PTR dwExtraInfo; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "dx", "dy", "mouseData", "dwFlags", "time", "dwExtraInfo" }); - } - } - - /** - * Contains the time of the last input. - */ - public static class LASTINPUTINFO extends Structure { - public int cbSize = size(); - - // Tick count of when the last input event was received. - public int dwTime; - - protected List getFieldOrder() { - return Arrays.asList(new String[] { "cbSize", "dwTime" }); - } - } } diff --git a/contrib/platform/src/com/sun/jna/platform/win32/Wtsapi32.java b/contrib/platform/src/com/sun/jna/platform/win32/Wtsapi32.java new file mode 100644 index 0000000000..7b405b2276 --- /dev/null +++ b/contrib/platform/src/com/sun/jna/platform/win32/Wtsapi32.java @@ -0,0 +1,95 @@ +package com.sun.jna.platform.win32; + +import com.sun.jna.Native; +import com.sun.jna.platform.win32.WinDef.HWND; +import com.sun.jna.win32.StdCallLibrary; +import com.sun.jna.win32.W32APIOptions; + +public interface Wtsapi32 extends StdCallLibrary { + + Wtsapi32 INSTANCE = (Wtsapi32) Native.loadLibrary("Wtsapi32", + Wtsapi32.class, W32APIOptions.DEFAULT_OPTIONS); + + int NOTIFY_FOR_ALL_SESSIONS = 1; + + int NOTIFY_FOR_THIS_SESSION = 0; + + /** + * The session identified by lParam was connected to the console terminal or + * RemoteFX session. + */ + public static final int WTS_CONSOLE_CONNECT = 0x1; + + /** + * The session identified by lParam was disconnected from the console + * terminal or RemoteFX session. + */ + public static final int WTS_CONSOLE_DISCONNECT = 0x2; + + /** + * The session identified by lParam was connected to the remote terminal. + */ + public static final int WTS_REMOTE_CONNECT = 0x3; + + /** + * The session identified by lParam was disconnected from the remote + * terminal. + */ + public static final int WTS_REMOTE_DISCONNECT = 0x4; + + /** + * A user has logged on to the session identified by lParam. + */ + public static final int WTS_SESSION_LOGON = 0x5; + + /** + * A user has logged off the session identified by lParam. + */ + public static final int WTS_SESSION_LOGOFF = 0x6; + + /** + * The session identified by lParam has been locked. + */ + public static final int WTS_SESSION_LOCK = 0x7; + + /** + * The session identified by lParam has been unlocked. + */ + public static final int WTS_SESSION_UNLOCK = 0x8; + + /** + * The session identified by lParam has changed its remote controlled + * status. To determine the status, call GetSystemMetrics and check the + * SM_REMOTECONTROL metric. + */ + public static final int WTS_SESSION_REMOTE_CONTROL = 0x9; + + /** + * Registers the specified window to receive session change notifications. + * + * @param hWnd + * [in] Handle of the window to receive session change + * notifications. + * + * @param dwFlags + * [in] Specifies which session notifications are to be received. + * This parameter can be one of the following values. + * + * @return If the function succeeds, the return value is TRUE. Otherwise, it + * is FALSE. To get extended error information, call GetLastError. + */ + public boolean WTSRegisterSessionNotification(HWND hWnd, int dwFlags); + + /** + * Unregisters the specified window so that it receives no further session + * change notifications. + * + * @param hWnd + * [in] Handle of the window to be unregistered from receiving + * session notifications. + * + * @return If the function succeeds, the return value is TRUE. Otherwise, it + * is FALSE. To get extended error information, call GetLastError. + */ + public boolean WTSUnRegisterSessionNotification(HWND hWnd); +} diff --git a/contrib/platform/test/com/sun/jna/platform/win32/GuidTest.java b/contrib/platform/test/com/sun/jna/platform/win32/GuidTest.java new file mode 100644 index 0000000000..0699a5d2c7 --- /dev/null +++ b/contrib/platform/test/com/sun/jna/platform/win32/GuidTest.java @@ -0,0 +1,129 @@ +package com.sun.jna.platform.win32; + +import junit.framework.TestCase; + +import com.sun.jna.platform.win32.Guid.GUID; + +// TODO: Auto-generated Javadoc +/** + * The Class GuidTest. + */ +public class GuidTest extends TestCase { + + /** + * The main method. + * + * @param args + * the arguments + */ + public static void main(String[] args) { + junit.textui.TestRunner.run(GuidTest.class); + } + + /** + * Instantiates a new guid test. + */ + public GuidTest() { + } + + /** + * Loads a GUID from string and verify that the guid returned has the + * expected values in each byte. + */ + public void testGUIDFromString() { + String sourceGuidStr = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"; + // test loading via static method + GUID targetGuid = GUID.fromString(sourceGuidStr); + + assertEquals(targetGuid.toGuidString(), sourceGuidStr); + } + + /** + * Loads a GUID from string via the constructor and verify that the guid + * returned has the expected values in each byte. + */ + public void testGUIDFromString2() { + String sourceGuidStr = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"; + // test loading via constructor + GUID targetGuid = new GUID(sourceGuidStr); + + assertEquals(targetGuid.toGuidString(), sourceGuidStr); + } + + /** + * Loads a GUID from a byte array and verify that the guid returned has the + * expected values in each byte. + */ + public void testGUIDFromBinary() { + byte[] sourceGuidBArr = new byte[] { (byte) 0xA5, (byte) 0xDC, + (byte) 0xBF, (byte) 0x10, (byte) 0x65, (byte) 0x30, + (byte) 0x11, (byte) 0xD2, (byte) 0x90, (byte) 0x1F, + (byte) 0x00, (byte) 0xC0, (byte) 0x4F, (byte) 0xB9, + (byte) 0x51, (byte) 0xED }; + + // test loading via static method + GUID targetGuid = GUID.fromBinary(sourceGuidBArr); + byte[] targetGuidBArr = targetGuid.toByteArray(); + + for (int i = 0; i < sourceGuidBArr.length; i++) { + assertEquals(targetGuidBArr[i], sourceGuidBArr[i]); + } + } + + /** + * Loads a GUID from a byte array via the constructor and verify that the + * guid returned has the expected values in each byte. + */ + public void testGUIDFromBinary2() { + byte[] sourceGuidBArr = new byte[] { (byte) 0xA5, (byte) 0xDC, + (byte) 0xBF, (byte) 0x10, (byte) 0x65, (byte) 0x30, + (byte) 0x11, (byte) 0xD2, (byte) 0x90, (byte) 0x1F, + (byte) 0x00, (byte) 0xC0, (byte) 0x4F, (byte) 0xB9, + (byte) 0x51, (byte) 0xED }; + + // test loading via constructor + GUID targetGuid = new GUID(sourceGuidBArr); + byte[] targetGuidBArr = targetGuid.toByteArray(); + + for (int i = 0; i < sourceGuidBArr.length; i++) { + assertEquals(targetGuidBArr[i], sourceGuidBArr[i]); + } + } + + /** + * Instantiates two guids, one with windows build-in function and one via + * jna and compares it. + */ + public void testBehaviourWithOle32() { + GUID ole32Guid = Ole32Util.getGUIDFromString("{A5DCBF10-6530-11D2-901F-00C04FB951ED}"); + GUID jnaGuid = new GUID("{A5DCBF10-6530-11D2-901F-00C04FB951ED}"); + + assertEquals(ole32Guid, jnaGuid); + } + + /** + * Test with the windows build-in function, compares the result of the + * methods. + */ + public void testBehaviourWithOle32_2() { + GUID ole32Guid = Ole32Util + .getGUIDFromString("{A5DCBF10-6530-11D2-901F-00C04FB951ED}"); + GUID jnaGuid = new GUID("{A5DCBF10-6530-11D2-901F-00C04FB951ED}"); + + String ole32Guidstr = Ole32Util.getStringFromGUID(ole32Guid); + String jnaGuidStr = jnaGuid.toGuidString(); + + assertEquals(ole32Guidstr, jnaGuidStr); + } + + /** + * Tests the new guid with the build-in function coming with windows. + */ + public void testNewGuid() { + GUID newGuid = GUID.newGuid(); + String guidString = newGuid.toGuidString(); + GUID guidFromString = Ole32Util.getGUIDFromString(guidString); + + assertEquals(guidFromString.toGuidString(), guidString); + } +} diff --git a/contrib/platform/test/com/sun/jna/platform/win32/Wtsapi32Test.java b/contrib/platform/test/com/sun/jna/platform/win32/Wtsapi32Test.java new file mode 100644 index 0000000000..e42ff1ea26 --- /dev/null +++ b/contrib/platform/test/com/sun/jna/platform/win32/Wtsapi32Test.java @@ -0,0 +1,42 @@ +package com.sun.jna.platform.win32; + +import java.awt.Frame; + +import junit.framework.TestCase; +import sun.awt.windows.WComponentPeer; + +import com.sun.jna.Pointer; +import com.sun.jna.platform.win32.WinDef.HWND; + +public class Wtsapi32Test extends TestCase { + + private long peer = 0; + + private HWND hwnd; + + public static void main(String[] args) { + junit.textui.TestRunner.run(Wtsapi32Test.class); + } + + public Wtsapi32Test() { + Frame frame = new Frame(); + frame.setVisible(true); + this.peer = ((WComponentPeer) frame.getPeer()).getHWnd(); + this.hwnd = new HWND(new Pointer(peer)); + } + + public void testWTSRegisterSessionNotification() { + boolean result = Wtsapi32.INSTANCE.WTSRegisterSessionNotification(hwnd, + Wtsapi32.NOTIFY_FOR_ALL_SESSIONS); + assertEquals(true, result); + } + + public void testWTSUnRegisterSessionNotification() { + // needed to register before you can unregister! + testWTSRegisterSessionNotification(); + boolean result = Wtsapi32.INSTANCE + .WTSUnRegisterSessionNotification(hwnd); + + assertEquals(true, result); + } +} diff --git a/pom-jna.xml b/pom-jna.xml index 373524b634..e1bdebbc0c 100644 --- a/pom-jna.xml +++ b/pom-jna.xml @@ -1,40 +1,40 @@ - - 4.0.0 - - net.java.dev.jna - jna - 3.5.1 - jar - - Java Native Access - Java Native Access - https://github.com/twall/jna - - - - LGPL, version 2.1 - http://creativecommons.org/licenses/LGPL/2.1/ - repo - - - - - scm:git:https://github.com/twall/jna - scm:git:ssh://git@github.com/twall/jna.git - https://github.com/twall/jna - - - - - twall - Timothy Wall - - Owner - - - - + + 4.0.0 + + net.java.dev.jna + jna + 3.5.2-SNAPSHOT + jar + + Java Native Access + Java Native Access + https://github.com/twall/jna + + + + LGPL, version 2.1 + http://creativecommons.org/licenses/LGPL/2.1/ + repo + + + + + scm:git:https://github.com/twall/jna + scm:git:ssh://git@github.com/twall/jna.git + https://github.com/twall/jna + + + + + twall + Timothy Wall + + Owner + + + + \ No newline at end of file diff --git a/pom-platform.xml b/pom-platform.xml index 1ff22b3580..f6c7c6e670 100644 --- a/pom-platform.xml +++ b/pom-platform.xml @@ -1,48 +1,48 @@ - - 4.0.0 - - net.java.dev.jna - platform - 3.5.1 - jar - - Java Native Access Platform - Java Native Access Platform - https://github.com/twall/jna - - - - LGPL, version 2.1 - http://creativecommons.org/licenses/LGPL/2.1/ - repo - - - - - scm:git:https://github.com/twall/jna - scm:git:ssh://git@github.com/twall/jna.git - https://github.com/twall/jna - - - - - twall - Timothy Wall - - Owner - - - - - - - net.java.dev.jna - jna - 3.5.1 - - - - + + 4.0.0 + + net.java.dev.jna + platform + 3.5.2-SNAPSHOT + jar + + Java Native Access Platform + Java Native Access Platform + https://github.com/twall/jna + + + + LGPL, version 2.1 + http://creativecommons.org/licenses/LGPL/2.1/ + repo + + + + + scm:git:https://github.com/twall/jna + scm:git:ssh://git@github.com/twall/jna.git + https://github.com/twall/jna + + + + + twall + Timothy Wall + + Owner + + + + + + + net.java.dev.jna + jna + 3.5.2-SNAPSHOT + + + + diff --git a/src/com/sun/jna/Native.java b/src/com/sun/jna/Native.java index 44bd64b8f9..fef3bdb7a0 100644 --- a/src/com/sun/jna/Native.java +++ b/src/com/sun/jna/Native.java @@ -1,1816 +1,1816 @@ -/* Copyright (c) 2007-2012 Timothy Wall, All Rights Reserved - * - * 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. - */ -package com.sun.jna; - -import java.awt.Component; -import java.awt.GraphicsEnvironment; -import java.awt.HeadlessException; -import java.awt.Window; - -import java.nio.Buffer; -import java.nio.ByteBuffer; - -import java.io.File; -import java.io.FilenameFilter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.ref.WeakReference; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.Proxy; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import java.util.WeakHashMap; - -import com.sun.jna.Callback.UncaughtExceptionHandler; -import com.sun.jna.Structure.FFIType; - -/** Provides generation of invocation plumbing for a defined native - * library interface. Also provides various utilities for native operations. - *

- * {@link #getTypeMapper} and {@link #getStructureAlignment} are provided - * to avoid having to explicitly pass these parameters to {@link Structure}s, - * which would require every {@link Structure} which requires custom mapping - * or alignment to define a constructor and pass parameters to the superclass. - * To avoid lots of boilerplate, the base {@link Structure} constructor - * figures out these properties based on its enclosing interface.

- * - *

Library Loading

- * When JNA classes are loaded, the native shared library (jnidispatch) is - * loaded as well. An attempt is made to load it from the any paths defined - * in jna.boot.library.path (if defined), then the system library - * path using {@link System#loadLibrary}, unless jna.nosys=true. - * If not found, the appropriate library will be extracted from the class path - * into a temporary directory and loaded from there. If your system has - * additional security constraints regarding execution or load of files - * (SELinux, for example), you should probably install the native library in - * an accessible location and configure your system accordingly, rather than - * relying on JNA to extract the library from its own jar file.

- * To avoid the automatic unpacking (in situations where you want to force a - * failure if the JNA native library is not properly installed on the system), - * set the system property jna.nounpack=true. - * NOTE: all native functions are provided within this class to ensure that - * all other JNA-provided classes and objects are GC'd and/or - * finalized/disposed before this class is disposed and/or removed from - * memory (most notably Memory and any other class which by default frees its - * resources in a finalizer).

- * @see Library - * @author Todd Fast, todd.fast@sun.com - * @author twall@users.sf.net - */ -public final class Native { - - private static final String VERSION = "3.5.1"; - private static final String VERSION_NATIVE = "3.5.0"; - - // Used by tests, do not remove - private static String nativeLibraryPath = null; - private static Map typeMappers = new WeakHashMap(); - private static Map alignments = new WeakHashMap(); - private static Map options = new WeakHashMap(); - private static Map libraries = new WeakHashMap(); - private static final UncaughtExceptionHandler DEFAULT_HANDLER = - new UncaughtExceptionHandler() { - public void uncaughtException(Callback c, Throwable e) { - System.err.println("JNA: Callback " + c + " threw the following exception:"); - e.printStackTrace(); - } - }; - private static UncaughtExceptionHandler callbackExceptionHandler = DEFAULT_HANDLER; - - /** The size of a native pointer (void*) on the current - * platform, in bytes. - */ - public static final int POINTER_SIZE; - /** Size of a native long type, in bytes. */ - public static final int LONG_SIZE; - /** Size of a native wchar_t type, in bytes. */ - public static final int WCHAR_SIZE; - /** Size of a native size_t type, in bytes. */ - public static final int SIZE_T_SIZE; - - private static final int TYPE_VOIDP = 0; - private static final int TYPE_LONG = 1; - private static final int TYPE_WCHAR_T = 2; - private static final int TYPE_SIZE_T = 3; - - private static final int THREAD_NOCHANGE = 0; - private static final int THREAD_DETACH = -1; - private static final int THREAD_LEAVE_ATTACHED = -2; - - static { - loadNativeLibrary(); - POINTER_SIZE = sizeof(TYPE_VOIDP); - LONG_SIZE = sizeof(TYPE_LONG); - WCHAR_SIZE = sizeof(TYPE_WCHAR_T); - SIZE_T_SIZE = sizeof(TYPE_SIZE_T); - - // Perform initialization of other JNA classes until *after* - // initializing the above final fields - initIDs(); - if (Boolean.getBoolean("jna.protected")) { - setProtected(true); - } - String version = getNativeVersion(); - if (!VERSION_NATIVE.equals(version)) { - String LS = System.getProperty("line.separator"); - throw new Error(LS + LS - + "There is an incompatible JNA native library installed on this system." + LS - + "To resolve this issue you may do one of the following:" + LS - + " - remove or uninstall the offending library" + LS - + " - set the system property jna.nosys=true" + LS - + " - set jna.boot.library.path to include the path to the version of the " + LS + " jnidispatch library included with the JNA jar file you are using" + LS); - } - setPreserveLastError("true".equalsIgnoreCase(System.getProperty("jna.preserve_last_error", "true"))); - } - - /** Force a dispose when this class is GC'd. */ - private static final Object finalizer = new Object() { - protected void finalize() { - dispose(); - } - }; - - /** Properly dispose of JNA functionality. */ - private static void dispose() { - NativeLibrary.disposeAll(); - nativeLibraryPath = null; - } - - /** Remove any automatically unpacked native library. - - This will fail on windows, which disallows removal of any file that is - still in use, so an alternative is required in that case. Mark - the file that could not be deleted, and attempt to delete any - temporaries on next startup. - - Do NOT force the class loader to unload the native library, since - that introduces issues with cleaning up any extant JNA bits - (e.g. Memory) which may still need use of the library before shutdown. - */ - private static boolean deleteNativeLibrary(String path) { - File flib = new File(path); - if (flib.delete()) { - return true; - } - - // Couldn't delete it, mark for later deletion - markTemporaryFile(flib); - - return false; - } - - private Native() { } - - private static native void initIDs(); - - /** Set whether native memory accesses are protected from invalid - * accesses. This should only be set true when testing or debugging, - * and should not be considered reliable or robust for applications - * where JNA native calls are occurring on multiple threads. - * Protected mode will be automatically set if the - * system property jna.protected has a value of "true" - * when the JNA library is first loaded.

- * If not supported by the underlying platform, this setting will - * have no effect.

- * NOTE: On platforms which support signals (non-Windows), JNA uses - * signals to trap errors. This may interfere with the JVM's own use of - * signals. When protected mode is enabled, you should make use of the - * jsig library, if available (see Signal Chaining). - * In short, set the environment variable LD_PRELOAD to the - * path to libjsig.so in your JRE lib directory - * (usually ${java.home}/lib/${os.arch}/libjsig.so) before launching your - * Java application. - */ - public static synchronized native void setProtected(boolean enable); - - /** Returns whether protection is enabled. Check the result of this method - * after calling {@link #setProtected setProtected(true)} to determine - * if this platform supports protecting memory accesses. - */ - public static synchronized native boolean isProtected(); - - /** Set whether the system last error result is captured after every - * native invocation. Defaults to true (false - * for direct-mapped calls).

- * @deprecated The preferred method of obtaining the last error result is - * to declare your mapped method to throw {@link LastErrorException} - * instead. - */ - public static synchronized native void setPreserveLastError(boolean enable); - - /** Indicates whether the system last error result is preserved - * after every invocation.

- * @deprecated The preferred method of obtaining the last error result is - * to declare your mapped method to throw {@link LastErrorException} - * instead. - */ - public static synchronized native boolean getPreserveLastError(); - - /** Utility method to get the native window ID for a Java {@link Window} - * as a long value. - * This method is primarily for X11-based systems, which use an opaque - * XID (usually long int) to identify windows. - * @throws HeadlessException if the current VM is running headless - */ - public static long getWindowID(Window w) throws HeadlessException { - return AWT.getWindowID(w); - } - - /** Utility method to get the native window ID for a heavyweight Java - * {@link Component} as a long value. - * This method is primarily for X11-based systems, which use an opaque - * XID (usually long int) to identify windows. - * @throws HeadlessException if the current VM is running headless - */ - public static long getComponentID(Component c) throws HeadlessException { - return AWT.getComponentID(c); - } - - /** Utility method to get the native window pointer for a Java - * {@link Window} as a {@link Pointer} value. This method is primarily for - * w32, which uses the HANDLE type (actually - * void *) to identify windows. - * @throws HeadlessException if the current VM is running headless - */ - public static Pointer getWindowPointer(Window w) throws HeadlessException { - return new Pointer(AWT.getWindowID(w)); - } - - /** Utility method to get the native window pointer for a heavyweight Java - * {@link Component} as a {@link Pointer} value. This method is primarily - * for w32, which uses the HWND type (actually - * void *) to identify windows. - * @throws HeadlessException if the current VM is running headless - */ - public static Pointer getComponentPointer(Component c) throws HeadlessException { - return new Pointer(AWT.getComponentID(c)); - } - - static native long getWindowHandle0(Component c); - - /** Convert a direct {@link Buffer} into a {@link Pointer}. - * @throws IllegalArgumentException if the buffer is not direct. - */ - public static Pointer getDirectBufferPointer(Buffer b) { - long peer = _getDirectBufferPointer(b); - return peer == 0 ? null : new Pointer(peer); - } - - private static native long _getDirectBufferPointer(Buffer b); - - /** Obtain a Java String from the given native byte array. If there is - * no NUL terminator, the String will comprise the entire array. If the - * system property jna.encoding is set, its value will - * override the platform default encoding (if supported). - */ - public static String toString(byte[] buf) { - return toString(buf, System.getProperty("jna.encoding")); - } - - /** Obtain a Java String from the given native byte array, using the given - * encoding. If there is no NUL terminator, the String will comprise the - * entire array. If the encoding parameter is null, - * the platform default encoding will be used. - */ - public static String toString(byte[] buf, String encoding) { - String s = null; - if (encoding != null) { - try { - s = new String(buf, encoding); - } - catch(UnsupportedEncodingException e) { } - } - if (s == null) { - s = new String(buf); - } - int term = s.indexOf(0); - if (term != -1) - s = s.substring(0, term); - return s; - } - - /** Obtain a Java String from the given native wchar_t array. If there is - * no NUL terminator, the String will comprise the entire array. - */ - public static String toString(char[] buf) { - String s = new String(buf); - int term = s.indexOf(0); - if (term != -1) - s = s.substring(0, term); - return s; - } - - /** Map a library interface to the current process, providing - * the explicit interface class. - * @param interfaceClass - */ - public static Object loadLibrary(Class interfaceClass) { - return loadLibrary(null, interfaceClass); - } - - /** Map a library interface to the current process, providing - * the explicit interface class. - * @param interfaceClass - * @param options Map of library options - */ - public static Object loadLibrary(Class interfaceClass, Map options) { - return loadLibrary(null, interfaceClass, options); - } - - /** Map a library interface to the given shared library, providing - * the explicit interface class. - * If name is null, attempts to map onto the current process. - * @param name - * @param interfaceClass - */ - public static Object loadLibrary(String name, Class interfaceClass) { - return loadLibrary(name, interfaceClass, Collections.EMPTY_MAP); - } - - /** Load a library interface from the given shared library, providing - * the explicit interface class and a map of options for the library. - * If no library options are detected the map is interpreted as a map - * of Java method names to native function names.

- * If name is null, attempts to map onto the current process. - * @param name - * @param interfaceClass - * @param options Map of library options - */ - public static Object loadLibrary(String name, - Class interfaceClass, - Map options) { - Library.Handler handler = - new Library.Handler(name, interfaceClass, options); - ClassLoader loader = interfaceClass.getClassLoader(); - Library proxy = (Library) - Proxy.newProxyInstance(loader, new Class[] {interfaceClass}, - handler); - cacheOptions(interfaceClass, options, proxy); - return proxy; - } - - /** Attempts to force initialization of an instance of the library interface - * by loading a public static field of the requisite type. - * Returns whether an instance variable was instantiated. - * Expects that lock on libraries is already held - */ - private static void loadLibraryInstance(Class cls) { - if (cls != null && !libraries.containsKey(cls)) { - try { - Field[] fields = cls.getFields(); - for (int i=0;i < fields.length;i++) { - Field field = fields[i]; - if (field.getType() == cls - && Modifier.isStatic(field.getModifiers())) { - // Ensure the field gets initialized by reading it - libraries.put(cls, new WeakReference(field.get(null))); - break; - } - } - } - catch (Exception e) { - throw new IllegalArgumentException("Could not access instance of " - + cls + " (" + e + ")"); - } - } - } - - /** Find the library interface corresponding to the given class. Checks - * all ancestor classes and interfaces for a declaring class which - * implements {@link Library}. - */ - static Class findEnclosingLibraryClass(Class cls) { - if (cls == null) { - return null; - } - synchronized(libraries) { - if (options.containsKey(cls)) { - return cls; - } - } - if (Library.class.isAssignableFrom(cls)) { - return cls; - } - if (Callback.class.isAssignableFrom(cls)) { - cls = CallbackReference.findCallbackClass(cls); - } - Class declaring = cls.getDeclaringClass(); - Class fromDeclaring = findEnclosingLibraryClass(declaring); - if (fromDeclaring != null) { - return fromDeclaring; - } - return findEnclosingLibraryClass(cls.getSuperclass()); - } - - - /** Return the preferred native library configuration options for the given - * class. - * @see Library - */ - public static Map getLibraryOptions(Class type) { - synchronized(libraries) { - Class interfaceClass = findEnclosingLibraryClass(type); - if (interfaceClass != null) - loadLibraryInstance(interfaceClass); - else - interfaceClass = type; - if (!options.containsKey(interfaceClass)) { - try { - Field field = interfaceClass.getField("OPTIONS"); - field.setAccessible(true); - options.put(interfaceClass, field.get(null)); - } - catch (NoSuchFieldException e) { - } - catch (Exception e) { - throw new IllegalArgumentException("OPTIONS must be a public field of type java.util.Map (" - + e + "): " + interfaceClass); - } - } - return (Map)options.get(interfaceClass); - } - } - - /** Return the preferred {@link TypeMapper} for the given native interface. - * See {@link com.sun.jna.Library#OPTION_TYPE_MAPPER}. - */ - public static TypeMapper getTypeMapper(Class cls) { - synchronized(libraries) { - Class interfaceClass = findEnclosingLibraryClass(cls); - if (interfaceClass != null) - loadLibraryInstance(interfaceClass); - else - interfaceClass = cls; - - if (!typeMappers.containsKey(interfaceClass)) { - try { - Field field = interfaceClass.getField("TYPE_MAPPER"); - field.setAccessible(true); - typeMappers.put(interfaceClass, field.get(null)); - } - catch (NoSuchFieldException e) { - Map options = getLibraryOptions(cls); - if (options != null - && options.containsKey(Library.OPTION_TYPE_MAPPER)) { - typeMappers.put(interfaceClass, options.get(Library.OPTION_TYPE_MAPPER)); - } - } - catch (Exception e) { - throw new IllegalArgumentException("TYPE_MAPPER must be a public field of type " - + TypeMapper.class.getName() + " (" - + e + "): " + interfaceClass); - } - } - return (TypeMapper)typeMappers.get(interfaceClass); - } - } - - /** Return the preferred structure alignment for the given native interface. - * See {@link com.sun.jna.Library#OPTION_STRUCTURE_ALIGNMENT}. - */ - public static int getStructureAlignment(Class cls) { - synchronized(libraries) { - Class interfaceClass = findEnclosingLibraryClass(cls); - if (interfaceClass != null) - loadLibraryInstance(interfaceClass); - else - interfaceClass = cls; - if (!alignments.containsKey(interfaceClass)) { - try { - Field field = interfaceClass.getField("STRUCTURE_ALIGNMENT"); - field.setAccessible(true); - alignments.put(interfaceClass, field.get(null)); - } - catch(NoSuchFieldException e) { - Map options = getLibraryOptions(interfaceClass); - if (options != null - && options.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) { - alignments.put(interfaceClass, options.get(Library.OPTION_STRUCTURE_ALIGNMENT)); - } - } - catch(Exception e) { - throw new IllegalArgumentException("STRUCTURE_ALIGNMENT must be a public field of type int (" - + e + "): " + interfaceClass); - } - } - Integer value = (Integer)alignments.get(interfaceClass); - return value != null ? value.intValue() : Structure.ALIGN_DEFAULT; - } - } - - /** Return a byte array corresponding to the given String. If the - * system property jna.encoding is set, its value will override - * the default platform encoding (if supported). - */ - static byte[] getBytes(String s) { - try { - return getBytes(s, System.getProperty("jna.encoding")); - } - catch (UnsupportedEncodingException e) { - return s.getBytes(); - } - } - - /** Return a byte array corresponding to the given String, using the given - encoding. - */ - static byte[] getBytes(String s, String encoding) throws UnsupportedEncodingException { - if (encoding != null) { - return s.getBytes(encoding); - } - return s.getBytes(); - } - - /** Obtain a NUL-terminated byte buffer equivalent to the given String, - using jna.encoding or the default platform encoding if - that property is not set. - */ - public static byte[] toByteArray(String s) { - byte[] bytes = getBytes(s); - byte[] buf = new byte[bytes.length+1]; - System.arraycopy(bytes, 0, buf, 0, bytes.length); - return buf; - } - - /** Obtain a NUL-terminated byte buffer equivalent to the given String, - using the given encoding. - */ - public static byte[] toByteArray(String s, String encoding) throws UnsupportedEncodingException { - byte[] bytes = getBytes(s, encoding); - byte[] buf = new byte[bytes.length+1]; - System.arraycopy(bytes, 0, buf, 0, bytes.length); - return buf; - } - - /** Obtain a NUL-terminated wide character buffer equivalent to the given - String. - */ - public static char[] toCharArray(String s) { - char[] chars = s.toCharArray(); - char[] buf = new char[chars.length+1]; - System.arraycopy(chars, 0, buf, 0, chars.length); - return buf; - } - - /** Generate a canonical String prefix based on the given OS - type/arch/name. - */ - static String getNativeLibraryResourcePath(int osType, String arch, String name) { - String osPrefix; - arch = arch.toLowerCase(); - if ("powerpc".equals(arch)) { - arch = "ppc"; - } - else if ("powerpc64".equals(arch)) { - arch = "ppc64"; - } - switch(osType) { - case Platform.ANDROID: - if (arch.startsWith("arm")) { - arch = "arm"; - } - osPrefix = "android-" + arch; - break; - case Platform.WINDOWS: - if ("i386".equals(arch)) { - arch = "x86"; - } - osPrefix = "win32-" + arch; - break; - case Platform.WINDOWSCE: - osPrefix = "w32ce-" + arch; - break; - case Platform.MAC: - osPrefix = "darwin"; - break; - case Platform.LINUX: - if ("x86".equals(arch)) { - arch = "i386"; - } - else if ("x86_64".equals(arch)) { - arch = "amd64"; - } - osPrefix = "linux-" + arch; - break; - case Platform.SOLARIS: - osPrefix = "sunos-" + arch; - break; - default: - osPrefix = name.toLowerCase(); - if ("x86".equals(arch)) { - arch = "i386"; - } - if ("x86_64".equals(arch)) { - arch = "amd64"; - } - int space = osPrefix.indexOf(" "); - if (space != -1) { - osPrefix = osPrefix.substring(0, space); - } - osPrefix += "-" + arch; - break; - } - return "/com/sun/jna/" + osPrefix; - } - - /** - * Loads the JNA stub library. - * First tries jna.boot.library.path, then the system path, then from the - * jar file. - */ - private static void loadNativeLibrary() { - removeTemporaryFiles(); - - String libName = System.getProperty("jna.boot.library.name", "jnidispatch"); - String bootPath = System.getProperty("jna.boot.library.path"); - if (bootPath != null) { - // String.split not available in 1.4 - StringTokenizer dirs = new StringTokenizer(bootPath, File.pathSeparator); - while (dirs.hasMoreTokens()) { - String dir = dirs.nextToken(); - File file = new File(new File(dir), System.mapLibraryName(libName)); - String path = file.getAbsolutePath(); - if (file.exists()) { - try { - System.load(path); - nativeLibraryPath = path; - return; - } catch (UnsatisfiedLinkError ex) { - // Not a problem if already loaded in anoteher class loader - // Unfortunately we can't distinguish the difference... - //System.out.println("File found at " + file + " but not loadable: " + ex.getMessage()); - } - } - if (Platform.isMac()) { - String orig, ext; - if (path.endsWith("dylib")) { - orig = "dylib"; - ext = "jnilib"; - } else { - orig = "jnilib"; - ext = "dylib"; - } - path = path.substring(0, path.lastIndexOf(orig)) + ext; - if (new File(path).exists()) { - try { - System.load(path); - nativeLibraryPath = path; - return; - } catch (UnsatisfiedLinkError ex) { - System.err.println("File found at " + path + " but not loadable: " + ex.getMessage()); - } - } - } - } - } - if (Platform.isAndroid()) { - // Native libraries on android must be bundled with the APK - System.setProperty("jna.nounpack", "true"); - } - try { - if (!Boolean.getBoolean("jna.nosys")) { - System.loadLibrary(libName); - return; - } - } - catch(UnsatisfiedLinkError e) { - if (Boolean.getBoolean("jna.nounpack")) { - throw e; - } - } - if (!Boolean.getBoolean("jna.nounpack")) { - loadNativeLibraryFromJar(); - return; - } - throw new UnsatisfiedLinkError("Native jnidispatch library not found"); - } - - /** - * Attempts to load the native library resource from the filesystem, - * extracting the JNA stub library from jna.jar if not already available. - */ - private static void loadNativeLibraryFromJar() { - String libname = System.mapLibraryName("jnidispatch"); - String arch = System.getProperty("os.arch"); - String name = System.getProperty("os.name"); - String resourceName = getNativeLibraryResourcePath(Platform.getOSType(), arch, name) + "/" + libname; - URL url = Native.class.getResource(resourceName); - boolean unpacked = false; - - // Add an ugly hack for OpenJDK (soylatte) - JNI libs use the usual - // .dylib extension - if (url == null && Platform.isMac() - && resourceName.endsWith(".dylib")) { - resourceName = resourceName.substring(0, resourceName.lastIndexOf(".dylib")) + ".jnilib"; - url = Native.class.getResource(resourceName); - } - if (url == null) { - throw new UnsatisfiedLinkError("JNA native support (" + resourceName - + ") not found in resource path"); - } - - File lib = null; - if (url.getProtocol().toLowerCase().equals("file")) { - try { - lib = new File(new URI(url.toString())); - } - catch(URISyntaxException e) { - lib = new File(url.getPath()); - } - if (!lib.exists()) { - throw new Error("File URL " + url + " could not be properly decoded"); - } - } - else { - InputStream is = Native.class.getResourceAsStream(resourceName); - if (is == null) { - throw new Error("Can't obtain jnidispatch InputStream"); - } - - FileOutputStream fos = null; - try { - // Suffix is required on windows, or library fails to load - // Let Java pick the suffix, except on windows, to avoid - // problems with Web Start. - File dir = getTempDir(); - lib = File.createTempFile("jna", Platform.isWindows()?".dll":null, dir); - lib.deleteOnExit(); - fos = new FileOutputStream(lib); - int count; - byte[] buf = new byte[1024]; - while ((count = is.read(buf, 0, buf.length)) > 0) { - fos.write(buf, 0, count); - } - unpacked = true; - } - catch(IOException e) { - throw new Error("Failed to create temporary file for jnidispatch library", e); - } - finally { - try { is.close(); } catch(IOException e) { } - if (fos != null) { - try { fos.close(); } catch(IOException e) { } - } - } - } - System.load(lib.getAbsolutePath()); - nativeLibraryPath = lib.getAbsolutePath(); - // Attempt to delete immediately once jnidispatch is successfully - // loaded. This avoids the complexity of trying to do so on "exit", - // which point can vary under different circumstances (native - // compilation, dynamically loaded modules, normal application, etc). - if (unpacked) { - deleteNativeLibrary(lib.getAbsolutePath()); - } - } - - /** - * Initialize field and method IDs for native methods of this class. - * Returns the size of a native pointer. - **/ - private static native int sizeof(int type); - - private static native String getNativeVersion(); - private static native String getAPIChecksum(); - - private static final ThreadLocal lastError = new ThreadLocal() { - protected synchronized Object initialValue() { - return new Integer(0); - } - }; - - /** Retrieve the last error set by the OS. This corresponds to - * GetLastError() on Windows, and errno on - * most other platforms. The value is preserved per-thread, but whether - * the original value is per-thread depends on the underlying OS. The - * result is undefined if {@link #getPreserveLastError} is - * false.

- * The preferred method of obtaining the last error result is - * to declare your mapped method to throw {@link LastErrorException} - * instead. - */ - public static int getLastError() { - return ((Integer)lastError.get()).intValue(); - } - - /** Set the OS last error code. Whether the setting is per-thread - * or global depends on the underlying OS. - */ - public static native void setLastError(int code); - - /** Update the last error value (called from native code). */ - // This has to be called immediately after a native call to ensure that - // subsequent VM operations don't overwrite the last error value - static void updateLastError(int e) { - lastError.set(new Integer(e)); - } - - /** - * Returns a synchronized (thread-safe) library backed by the specified - * library. This wrapping will prevent simultaneous invocations of any - * functions mapped to a given {@link NativeLibrary}. Note that the - * native library may still be sensitive to being called from different - * threads. - *

- * @param library the library to be "wrapped" in a synchronized library. - * @return a synchronized view of the specified library. - */ - public static Library synchronizedLibrary(final Library library) { - Class cls = library.getClass(); - if (!Proxy.isProxyClass(cls)) { - throw new IllegalArgumentException("Library must be a proxy class"); - } - InvocationHandler ih = Proxy.getInvocationHandler(library); - if (!(ih instanceof Library.Handler)) { - throw new IllegalArgumentException("Unrecognized proxy handler: " + ih); - } - final Library.Handler handler = (Library.Handler)ih; - InvocationHandler newHandler = new InvocationHandler() { - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - synchronized(handler.getNativeLibrary()) { - return handler.invoke(library, method, args); - } - } - }; - return (Library)Proxy.newProxyInstance(cls.getClassLoader(), - cls.getInterfaces(), - newHandler); - } - - /** If running web start, determine the location of a given native - * library. This value may be used to properly set - * jna.library.path so that JNA can load libraries identified - * by the <nativelib> tag in the JNLP configuration file. Returns - * null if the Web Start native library cache location can not - * be determined. Note that the path returned may be different for any - * given library name. - *

- * Use System.getProperty("javawebstart.version") to detect - * whether your code is running under Web Start. - * @throws UnsatisfiedLinkError if the library can't be found by the - * Web Start class loader, which usually means it wasn't included as - * a <nativelib> resource in the JNLP file. - * @return null if unable to query the web start loader. - */ - public static String getWebStartLibraryPath(final String libName) { - if (System.getProperty("javawebstart.version") == null) - return null; - try { - - final ClassLoader cl = Native.class.getClassLoader(); - Method m = (Method)AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - try { - Method m = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[] { String.class }); - m.setAccessible(true); - return m; - } - catch(Exception e) { - return null; - } - } - }); - String libpath = (String)m.invoke(cl, new Object[] { libName }); - if (libpath != null) { - return new File(libpath).getParent(); - } - return null; - } - catch (Exception e) { - return null; - } - } - - /** Perform cleanup of automatically unpacked native shared library. - */ - static void markTemporaryFile(File file) { - // If we can't force an unload/delete, flag the file for later - // deletion - try { - File marker = new File(file.getParentFile(), file.getName() + ".x"); - marker.createNewFile(); - } - catch(IOException e) { e.printStackTrace(); } - } - - /** Obtain a directory suitable for writing JNA-specific temporary files. - Override with jna.tmpdir - */ - static File getTempDir() { - File jnatmp; - String prop = System.getProperty("jna.tmpdir"); - if (prop != null) { - jnatmp = new File(prop); - } - else { - File tmp = new File(System.getProperty("java.io.tmpdir")); - jnatmp = new File(tmp, "jna-" + System.getProperty("user.name")); - jnatmp.mkdirs(); - if (!jnatmp.exists() || !jnatmp.canWrite()) { - jnatmp = tmp; - } - } - if (!jnatmp.exists()) { - throw new Error("JNA temporary directory " + jnatmp + " does not exist"); - } - if (!jnatmp.canWrite()) { - throw new Error("JNA temporary directory " + jnatmp + " is not writable"); - } - return jnatmp; - } - - /** Remove all marked temporary files in the given directory. */ - static void removeTemporaryFiles() { - File dir = getTempDir(); - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.endsWith(".x") && name.indexOf("jna") != -1; - } - }; - File[] files = dir.listFiles(filter); - for (int i=0;files != null && i < files.length;i++) { - File marker = files[i]; - String name = marker.getName(); - name = name.substring(0, name.length()-2); - File target = new File(marker.getParentFile(), name); - if (!target.exists() || target.delete()) { - marker.delete(); - } - } - } - - /** Returns the native size of the given class, in bytes. - * For use with arrays. - */ - public static int getNativeSize(Class type, Object value) { - if (type.isArray()) { - int len = Array.getLength(value); - if (len > 0) { - Object o = Array.get(value, 0); - return len * getNativeSize(type.getComponentType(), o); - } - // Don't process zero-length arrays - throw new IllegalArgumentException("Arrays of length zero not allowed: " + type); - } - if (Structure.class.isAssignableFrom(type) - && !Structure.ByReference.class.isAssignableFrom(type)) { - if (value == null) - value = Structure.newInstance(type); - return ((Structure)value).size(); - } - try { - return getNativeSize(type); - } - catch(IllegalArgumentException e) { - throw new IllegalArgumentException("The type \"" + type.getName() - + "\" is not supported: " - + e.getMessage()); - } - } - - /** Returns the native size for a given Java class. Structures are - * assumed to be struct pointers unless they implement - * {@link Structure.ByValue}. - */ - public static int getNativeSize(Class cls) { - if (NativeMapped.class.isAssignableFrom(cls)) { - cls = NativeMappedConverter.getInstance(cls).nativeType(); - } - // boolean defaults to 32 bit integer if not otherwise mapped - if (cls == boolean.class || cls == Boolean.class) return 4; - if (cls == byte.class || cls == Byte.class) return 1; - if (cls == short.class || cls == Short.class) return 2; - if (cls == char.class || cls == Character.class) return WCHAR_SIZE; - if (cls == int.class || cls == Integer.class) return 4; - if (cls == long.class || cls == Long.class) return 8; - if (cls == float.class || cls == Float.class) return 4; - if (cls == double.class || cls == Double.class) return 8; - if (Structure.class.isAssignableFrom(cls)) { - if (Structure.ByValue.class.isAssignableFrom(cls)) { - return Structure.newInstance(cls).size(); - } - return POINTER_SIZE; - } - if (Pointer.class.isAssignableFrom(cls) - || (Platform.HAS_BUFFERS && Buffers.isBuffer(cls)) - || Callback.class.isAssignableFrom(cls) - || String.class == cls - || WString.class == cls) { - return POINTER_SIZE; - } - throw new IllegalArgumentException("Native size for type \"" + cls.getName() - + "\" is unknown"); - } - - /** Indicate whether the given class is supported as a native argument - * type. - */ - public static boolean isSupportedNativeType(Class cls) { - if (Structure.class.isAssignableFrom(cls)) { - return true; - } - try { - return getNativeSize(cls) != 0; - } - catch(IllegalArgumentException e) { - return false; - } - } - - /** Set the default handler invoked when a callback throws an uncaught - * exception. If the given handler is null, the default - * handler will be reinstated. - */ - public static void setCallbackExceptionHandler(UncaughtExceptionHandler eh) { - callbackExceptionHandler = eh == null ? DEFAULT_HANDLER : eh; - } - - /** Returns the current handler for callback uncaught exceptions. */ - public static UncaughtExceptionHandler getCallbackExceptionHandler() { - return callbackExceptionHandler; - } - - /** When called from a class static initializer, maps all native methods - * found within that class to native libraries via the JNA raw calling - * interface. - * @param libName library name to which functions should be bound - */ - public static void register(String libName) { - register(getNativeClass(getCallingClass()), - NativeLibrary.getInstance(libName)); - } - - /** When called from a class static initializer, maps all native methods - * found within that class to native libraries via the JNA raw calling - * interface. - * @param lib native library to which functions should be bound - */ - public static void register(NativeLibrary lib) { - register(getNativeClass(getCallingClass()), lib); - } - - static Class getNativeClass(Class cls) { - Method[] methods = cls.getDeclaredMethods(); - for (int i=0;i < methods.length;i++) { - if ((methods[i].getModifiers() & Modifier.NATIVE) != 0) { - return cls; - } - } - int idx = cls.getName().lastIndexOf("$"); - if (idx != -1) { - String name = cls.getName().substring(0, idx); - try { - return getNativeClass(Class.forName(name, true, cls.getClassLoader())); - } - catch(ClassNotFoundException e) { - } - } - throw new IllegalArgumentException("Can't determine class with native methods from the current context (" + cls + ")"); - } - - static Class getCallingClass() { - Class[] context = new SecurityManager() { - public Class[] getClassContext() { - return super.getClassContext(); - } - }.getClassContext(); - if (context.length < 4) { - throw new IllegalStateException("This method must be called from the static initializer of a class"); - } - return context[3]; - } - - /** Set a thread initializer for the given callback. - The thread initializer indicates desired thread configuration when the - given Callback is invoked on a native thread not yet attached to the - VM. - */ - public static void setCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer) { - CallbackReference.setCallbackThreadInitializer(cb, initializer); - } - - - private static Map registeredClasses = new HashMap(); - private static Map registeredLibraries = new HashMap(); - private static Object unloader = new Object() { - protected void finalize() { - synchronized(registeredClasses) { - for (Iterator i=registeredClasses.entrySet().iterator();i.hasNext();) { - Map.Entry e = (Map.Entry)i.next(); - unregister((Class)e.getKey(), (long[])e.getValue()); - i.remove(); - } - } - } - }; - - /** Remove all native mappings for the calling class. - Should only be called if the class is no longer referenced and about - to be garbage collected. - */ - public static void unregister() { - unregister(getNativeClass(getCallingClass())); - } - - /** Remove all native mappings for the given class. - Should only be called if the class is no longer referenced and about - to be garbage collected. - */ - public static void unregister(Class cls) { - synchronized(registeredClasses) { - if (registeredClasses.containsKey(cls)) { - unregister(cls, (long[])registeredClasses.get(cls)); - registeredClasses.remove(cls); - registeredLibraries.remove(cls); - } - } - } - - /** Unregister the native methods for the given class. */ - private static native void unregister(Class cls, long[] handles); - - private static String getSignature(Class cls) { - if (cls.isArray()) { - return "[" + getSignature(cls.getComponentType()); - } - if (cls.isPrimitive()) { - if (cls == void.class) return "V"; - if (cls == boolean.class) return "Z"; - if (cls == byte.class) return "B"; - if (cls == short.class) return "S"; - if (cls == char.class) return "C"; - if (cls == int.class) return "I"; - if (cls == long.class) return "J"; - if (cls == float.class) return "F"; - if (cls == double.class) return "D"; - } - return "L" + replace(".", "/", cls.getName()) + ";"; - } - - // No String.replace available in 1.4 - static String replace(String s1, String s2, String str) { - StringBuffer buf = new StringBuffer(); - while (true) { - int idx = str.indexOf(s1); - if (idx == -1) { - buf.append(str); - break; - } - else { - buf.append(str.substring(0, idx)); - buf.append(s2); - str = str.substring(idx + s1.length()); - } - } - return buf.toString(); - } - - /** Indicates whether the callback has an initializer. */ - static final int CB_HAS_INITIALIZER = 1; - - private static final int CVT_UNSUPPORTED = -1; - private static final int CVT_DEFAULT = 0; - private static final int CVT_POINTER = 1; - private static final int CVT_STRING = 2; - private static final int CVT_STRUCTURE = 3; - private static final int CVT_STRUCTURE_BYVAL = 4; - private static final int CVT_BUFFER = 5; - private static final int CVT_ARRAY_BYTE = 6; - private static final int CVT_ARRAY_SHORT = 7; - private static final int CVT_ARRAY_CHAR = 8; - private static final int CVT_ARRAY_INT = 9; - private static final int CVT_ARRAY_LONG = 10; - private static final int CVT_ARRAY_FLOAT = 11; - private static final int CVT_ARRAY_DOUBLE = 12; - private static final int CVT_ARRAY_BOOLEAN = 13; - private static final int CVT_BOOLEAN = 14; - private static final int CVT_CALLBACK = 15; - private static final int CVT_FLOAT = 16; - private static final int CVT_NATIVE_MAPPED = 17; - private static final int CVT_WSTRING = 18; - private static final int CVT_INTEGER_TYPE = 19; - private static final int CVT_POINTER_TYPE = 20; - private static final int CVT_TYPE_MAPPER = 21; - - private static int getConversion(Class type, TypeMapper mapper) { - if (type == Boolean.class) type = boolean.class; - else if (type == Byte.class) type = byte.class; - else if (type == Short.class) type = short.class; - else if (type == Character.class) type = char.class; - else if (type == Integer.class) type = int.class; - else if (type == Long.class) type = long.class; - else if (type == Float.class) type = float.class; - else if (type == Double.class) type = double.class; - else if (type == Void.class) type = void.class; - - if (mapper != null - && (mapper.getFromNativeConverter(type) != null - || mapper.getToNativeConverter(type) != null)) { - return CVT_TYPE_MAPPER; - } - - if (Pointer.class.isAssignableFrom(type)) { - return CVT_POINTER; - } - if (String.class == type) { - return CVT_STRING; - } - if (WString.class.isAssignableFrom(type)) { - return CVT_WSTRING; - } - if (Platform.HAS_BUFFERS && Buffers.isBuffer(type)) { - return CVT_BUFFER; - } - if (Structure.class.isAssignableFrom(type)) { - if (Structure.ByValue.class.isAssignableFrom(type)) { - return CVT_STRUCTURE_BYVAL; - } - return CVT_STRUCTURE; - } - if (type.isArray()) { - switch(type.getName().charAt(1)) { - case 'Z': return CVT_ARRAY_BOOLEAN; - case 'B': return CVT_ARRAY_BYTE; - case 'S': return CVT_ARRAY_SHORT; - case 'C': return CVT_ARRAY_CHAR; - case 'I': return CVT_ARRAY_INT; - case 'J': return CVT_ARRAY_LONG; - case 'F': return CVT_ARRAY_FLOAT; - case 'D': return CVT_ARRAY_DOUBLE; - default: break; - } - } - if (type.isPrimitive()) { - return type == boolean.class ? CVT_BOOLEAN : CVT_DEFAULT; - } - if (Callback.class.isAssignableFrom(type)) { - return CVT_CALLBACK; - } - if (IntegerType.class.isAssignableFrom(type)) { - return CVT_INTEGER_TYPE; - } - if (PointerType.class.isAssignableFrom(type)) { - return CVT_POINTER_TYPE; - } - if (NativeMapped.class.isAssignableFrom(type)) { - return CVT_NATIVE_MAPPED; - } - return CVT_UNSUPPORTED; - } - - /** When called from a class static initializer, maps all native methods - * found within that class to native libraries via the JNA raw calling - * interface. - * @param lib library to which functions should be bound - */ - // TODO: derive options from annotations (per-class or per-method) - // options: read parameter type mapping (long/native long), - // method name, library name, call conv - public static void register(Class cls, NativeLibrary lib) { - Method[] methods = cls.getDeclaredMethods(); - List mlist = new ArrayList(); - TypeMapper mapper = (TypeMapper) - lib.getOptions().get(Library.OPTION_TYPE_MAPPER); - - for (int i=0;i < methods.length;i++) { - if ((methods[i].getModifiers() & Modifier.NATIVE) != 0) { - mlist.add(methods[i]); - } - } - long[] handles = new long[mlist.size()]; - for (int i=0;i < handles.length;i++) { - Method method = (Method)mlist.get(i); - String sig = "("; - Class rclass = method.getReturnType(); - long rtype, closure_rtype; - Class[] ptypes = method.getParameterTypes(); - long[] atypes = new long[ptypes.length]; - long[] closure_atypes = new long[ptypes.length]; - int[] cvt = new int[ptypes.length]; - ToNativeConverter[] toNative = new ToNativeConverter[ptypes.length]; - FromNativeConverter fromNative = null; - int rcvt = getConversion(rclass, mapper); - boolean throwLastError = false; - switch (rcvt) { - case CVT_UNSUPPORTED: - throw new IllegalArgumentException(rclass + " is not a supported return type (in method " + method.getName() + " in " + cls + ")"); - case CVT_TYPE_MAPPER: - fromNative = mapper.getFromNativeConverter(rclass); - closure_rtype = FFIType.get(rclass).peer; - rtype = FFIType.get(fromNative.nativeType()).peer; - break; - case CVT_NATIVE_MAPPED: - case CVT_INTEGER_TYPE: - case CVT_POINTER_TYPE: - closure_rtype = FFIType.get(Pointer.class).peer; - rtype = FFIType.get(NativeMappedConverter.getInstance(rclass).nativeType()).peer; - break; - case CVT_STRUCTURE: - closure_rtype = rtype = FFIType.get(Pointer.class).peer; - break; - case CVT_STRUCTURE_BYVAL: - closure_rtype = FFIType.get(Pointer.class).peer; - rtype = FFIType.get(rclass).peer; - break; - default: - closure_rtype = rtype = FFIType.get(rclass).peer; - break; - } - for (int t=0;t < ptypes.length;t++) { - Class type = ptypes[t]; - sig += getSignature(type); - cvt[t] = getConversion(type, mapper); - if (cvt[t] == CVT_UNSUPPORTED) { - throw new IllegalArgumentException(type + " is not a supported argument type (in method " + method.getName() + " in " + cls + ")"); - } - if (cvt[t] == CVT_NATIVE_MAPPED - || cvt[t] == CVT_INTEGER_TYPE) { - type = NativeMappedConverter.getInstance(type).nativeType(); - } - else if (cvt[t] == CVT_TYPE_MAPPER) { - toNative[t] = mapper.getToNativeConverter(type); - } - // Determine the type that will be passed to the native - // function, as well as the type to be passed - // from Java initially - switch(cvt[t]) { - case CVT_STRUCTURE_BYVAL: - case CVT_INTEGER_TYPE: - case CVT_POINTER_TYPE: - case CVT_NATIVE_MAPPED: - atypes[t] = FFIType.get(type).peer; - closure_atypes[t] = FFIType.get(Pointer.class).peer; - break; - case CVT_TYPE_MAPPER: - if (type.isPrimitive()) - closure_atypes[t] = FFIType.get(type).peer; - else - closure_atypes[t] = FFIType.get(Pointer.class).peer; - atypes[t] = FFIType.get(toNative[t].nativeType()).peer; - break; - case CVT_DEFAULT: - closure_atypes[t] = atypes[t] = FFIType.get(type).peer; - break; - default: - closure_atypes[t] = atypes[t] = FFIType.get(Pointer.class).peer; - break; - } - } - sig += ")"; - sig += getSignature(rclass); - - Class[] etypes = method.getExceptionTypes(); - for (int e=0;e < etypes.length;e++) { - if (LastErrorException.class.isAssignableFrom(etypes[e])) { - throwLastError = true; - break; - } - } - - String name = method.getName(); - FunctionMapper fmapper = (FunctionMapper)lib.getOptions().get(Library.OPTION_FUNCTION_MAPPER); - if (fmapper != null) { - name = fmapper.getFunctionName(lib, method); - } - Function f = lib.getFunction(name, method); - try { - handles[i] = registerMethod(cls, method.getName(), - sig, cvt, - closure_atypes, atypes, rcvt, - closure_rtype, rtype, - rclass, - f.peer, f.getCallingConvention(), - throwLastError, - toNative, fromNative); - } - catch(NoSuchMethodError e) { - throw new UnsatisfiedLinkError("No method " + method.getName() + " with signature " + sig + " in " + cls); - } - } - synchronized(registeredClasses) { - registeredClasses.put(cls, handles); - registeredLibraries.put(cls, lib); - } - cacheOptions(cls, lib.getOptions(), null); - } - - /** Take note of options used for a given library mapping, to facilitate - looking them up later. - */ - private static void cacheOptions(Class cls, Map libOptions, Object proxy) { - synchronized(libraries) { - if (!libOptions.isEmpty()) - options.put(cls, libOptions); - if (libOptions.containsKey(Library.OPTION_TYPE_MAPPER)) - typeMappers.put(cls, libOptions.get(Library.OPTION_TYPE_MAPPER)); - if (libOptions.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) - alignments.put(cls, libOptions.get(Library.OPTION_STRUCTURE_ALIGNMENT)); - if (proxy != null) { - libraries.put(cls, new WeakReference(proxy)); - } - - // If it's a direct mapping, AND implements a Library interface, - // cache the library interface as well, so that any nested - // classes get the appropriate associated options - if (!cls.isInterface() - && Library.class.isAssignableFrom(cls)) { - Class ifaces[] = cls.getInterfaces(); - for (int i=0;i < ifaces.length;i++) { - if (Library.class.isAssignableFrom(ifaces[i])) { - cacheOptions(ifaces[i], libOptions, proxy); - break; - } - } - } - } - } - - private static native long registerMethod(Class cls, - String name, - String signature, - int[] conversions, - long[] closure_arg_types, - long[] arg_types, - int rconversion, - long closure_rtype, - long rtype, - Class rclass, - long fptr, - int callingConvention, - boolean throwLastError, - ToNativeConverter[] toNative, - FromNativeConverter fromNative); - - - // Called from native code - private static NativeMapped fromNative(Class cls, Object value) { - // NOTE: technically should be either CallbackParameterContext or - // FunctionResultContext - return (NativeMapped)NativeMappedConverter.getInstance(cls).fromNative(value, new FromNativeContext(cls)); - } - // Called from native code - private static Class nativeType(Class cls) { - return NativeMappedConverter.getInstance(cls).nativeType(); - } - // Called from native code - private static Object toNative(ToNativeConverter cvt, Object o) { - // NOTE: technically should be either CallbackResultContext or - // FunctionParameterContext - return cvt.toNative(o, new ToNativeContext()); - } - // Called from native code - private static Object fromNative(FromNativeConverter cvt, Object o, Class cls) { - // NOTE: technically should be FunctionResultContext - return cvt.fromNative(o, new FromNativeContext(cls)); - } - - /** Create a new cif structure. */ - public static native long ffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types); - /** Make an FFI function call. */ - public static native void ffi_call(long cif, long fptr, long resp, long args); - public static native long ffi_prep_closure(long cif, ffi_callback cb); - public static native void ffi_free_closure(long closure); - - /** Returns the size (calculated by libffi) of the given type. */ - static native int initialize_ffi_type(long type_info); - - public interface ffi_callback { - void invoke(long cif, long resp, long argp); - } - - /** Prints JNA library details to the console. */ - public static void main(String[] args) { - final String DEFAULT_TITLE = "Java Native Access (JNA)"; - final String DEFAULT_VERSION = VERSION; - final String DEFAULT_BUILD = VERSION + " (package information missing)"; - Package pkg = Native.class.getPackage(); - String title = pkg != null - ? pkg.getSpecificationTitle() : DEFAULT_TITLE; - if (title == null) title = DEFAULT_TITLE; - String version = pkg != null - ? pkg.getSpecificationVersion() : DEFAULT_VERSION; - if (version == null) version = DEFAULT_VERSION; - title += " API Version " + version; - System.out.println(title); - version = pkg != null - ? pkg.getImplementationVersion() : DEFAULT_BUILD; - if (version == null) version = DEFAULT_BUILD; - System.out.println("Version: " + version); - System.out.println(" Native: " + getNativeVersion() + " (" - + getAPIChecksum() + ")"); - System.exit(0); - } - - /** Free the given callback trampoline. */ - static synchronized native void freeNativeCallback(long ptr); - - /** Use direct mapping for callback. */ - static final int CB_OPTION_DIRECT = 1; - /** Return a DLL-resident fucntion pointer. */ - static final int CB_OPTION_IN_DLL = 2; - - /** Create a native trampoline to delegate execution to the Java callback. - */ - static synchronized native long createNativeCallback(Callback callback, - Method method, - Class[] parameterTypes, - Class returnType, - int callingConvention, - int flags); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - * - * @return The value returned by the target native function - */ - static native int invokeInt(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - * - * @return The value returned by the target native function - */ - static native long invokeLong(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - */ - static native void invokeVoid(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - * - * @return The value returned by the target native function - */ - static native float invokeFloat(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - * - * @return The value returned by the target native function - */ - static native double invokeDouble(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args - * Arguments to pass to the native function - * - * @return The native pointer returned by the target native function - */ - static native long invokePointer(long fp, int callFlags, Object[] args); - - /** - * Call the native function being represented by this object, returning - * a struct by value. - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args Arguments to pass to the native function - * @param memory Memory for pre-allocated structure to hold the result - * @param typeInfo Native type information for the Structure - */ - private static native void invokeStructure(long fp, int callFlags, - Object[] args, long memory, - long type_info); - - /** - * Call the native function being represented by this object, returning - * a struct by value. - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args Arguments to pass to the native function - * @return the passed-in Structure - */ - static Structure invokeStructure(long fp, int callFlags, Object[] args, - Structure s) { - invokeStructure(fp, callFlags, args, s.getPointer().peer, - s.getTypeInfo().peer); - return s; - } - - /** - * Call the native function being represented by this object, returning - * a Java Object. - * @param fp function pointer - * @param callFlags calling convention to be used - * @param args Arguments to pass to the native function - * - * @return The returned Java Object - */ - static native Object invokeObject(long fp, int callFlags, Object[] args); - - /** Open the requested native library with default options. */ - static long open(String name) { - return open(name, -1); - } - - /** Open the requested native library with the specified platform-specific - * otions. - */ - static native long open(String name, int flags); - - /** Close the given native library. */ - static native void close(long handle); - - static native long findSymbol(long handle, String name); - - static native long indexOf(long addr, byte value); - - static native void read(long addr, byte[] buf, int index, int length); - - static native void read(long addr, short[] buf, int index, int length); - - static native void read(long addr, char[] buf, int index, int length); - - static native void read(long addr, int[] buf, int index, int length); - - static native void read(long addr, long[] buf, int index, int length); - - static native void read(long addr, float[] buf, int index, int length); - - static native void read(long addr, double[] buf, int index, int length); - - static native void write(long addr, byte[] buf, int index, int length); - - static native void write(long addr, short[] buf, int index, int length); - - static native void write(long addr, char[] buf, int index, int length); - - static native void write(long addr, int[] buf, int index, int length); - - static native void write(long addr, long[] buf, int index, int length); - - static native void write(long addr, float[] buf, int index, int length); - - static native void write(long addr, double[] buf, int index, int length); - - static native byte getByte(long addr); - - static native char getChar(long addr); - - static native short getShort(long addr); - - static native int getInt(long addr); - - static native long getLong(long addr); - - static native float getFloat(long addr); - - static native double getDouble(long addr); - - static Pointer getPointer(long addr) { - long peer = _getPointer(addr); - return peer == 0 ? null : new Pointer(peer); - } - - private static native long _getPointer(long addr); - - static native String getString(long addr, boolean wide); - - static native void setMemory(long addr, long length, byte value); - - static native void setByte(long addr, byte value); - - static native void setShort(long addr, short value); - - static native void setChar(long addr, char value); - - static native void setInt(long addr, int value); - - static native void setLong(long addr, long value); - - static native void setFloat(long addr, float value); - - static native void setDouble(long addr, double value); - - static native void setPointer(long addr, long value); - - static native void setString(long addr, String value, boolean wide); - - /** - * Call the real native malloc - * @param size size of the memory to be allocated - * @return native address of the allocated memory block; zero if the - * allocation failed. - */ - public static native long malloc(long size); - - /** - * Call the real native free - * @param ptr native address to be freed; a value of zero has no effect, - * passing an already-freed pointer will cause pain. - */ - public static native void free(long ptr); - - /** - * Get a direct ByteBuffer mapped to the memory pointed to by the pointer. - * This method calls through to the JNA NewDirectByteBuffer method. - * - * @param addr base address of the JNA-originated memory - * @param length Length of ByteBuffer - * @return a direct ByteBuffer that accesses the memory being pointed to, - */ - public static native ByteBuffer getDirectByteBuffer(long addr, long length); - - /** Indicate the desired attachment state for the current thread. - This method should only be called from a callback context, and then - only just prior to returning to native code. Executing Java or native - code after the invocation of this method may interfere with the - intended detach state.

- Note: errno/SetLastError is used to signal the desired state; this is - a hack to make use of built-in thread-local storage to avoid having to - re-implement it on certain platforms.

- Warning: avoid calling {@link #detach detach(true)} on threads - spawned by the JVM; the resulting behavior is not defined.

- */ - public static void detach(boolean detach) { - setLastError(detach ? THREAD_DETACH : THREAD_LEAVE_ATTACHED); - } - - private static class Buffers { - static boolean isBuffer(Class cls) { - return Buffer.class.isAssignableFrom(cls); - } - } - - /** Provides separation of JAWT functionality for the sake of J2ME - * ports which do not include AWT support. - */ - private static class AWT { - static long getWindowID(Window w) throws HeadlessException { - return getComponentID(w); - } - // Declaring the argument as Object rather than Component avoids class not - // found errors on phoneME foundation profile. - static long getComponentID(Object o) throws HeadlessException { - if (GraphicsEnvironment.isHeadless()) { - throw new HeadlessException("No native windows when headless"); - } - Component c = (Component)o; - if (c.isLightweight()) { - throw new IllegalArgumentException("Component must be heavyweight"); - } - if (!c.isDisplayable()) - throw new IllegalStateException("Component must be displayable"); - // On X11 VMs prior to 1.5, the window must be visible - if (Platform.isX11() - && System.getProperty("java.version").startsWith("1.4")) { - if (!c.isVisible()) { - throw new IllegalStateException("Component must be visible"); - } - } - // By this point, we're certain that Toolkit.loadLibraries() has - // been called, thus avoiding AWT/JAWT link errors - // (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6539705). - return Native.getWindowHandle0(c); - } - } -} +/* Copyright (c) 2007-2012 Timothy Wall, All Rights Reserved + * + * 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. + */ +package com.sun.jna; + +import java.awt.Component; +import java.awt.GraphicsEnvironment; +import java.awt.HeadlessException; +import java.awt.Window; + +import java.nio.Buffer; +import java.nio.ByteBuffer; + +import java.io.File; +import java.io.FilenameFilter; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.ref.WeakReference; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Proxy; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.WeakHashMap; + +import com.sun.jna.Callback.UncaughtExceptionHandler; +import com.sun.jna.Structure.FFIType; + +/** Provides generation of invocation plumbing for a defined native + * library interface. Also provides various utilities for native operations. + *

+ * {@link #getTypeMapper} and {@link #getStructureAlignment} are provided + * to avoid having to explicitly pass these parameters to {@link Structure}s, + * which would require every {@link Structure} which requires custom mapping + * or alignment to define a constructor and pass parameters to the superclass. + * To avoid lots of boilerplate, the base {@link Structure} constructor + * figures out these properties based on its enclosing interface.

+ * + *

Library Loading

+ * When JNA classes are loaded, the native shared library (jnidispatch) is + * loaded as well. An attempt is made to load it from the any paths defined + * in jna.boot.library.path (if defined), then the system library + * path using {@link System#loadLibrary}, unless jna.nosys=true. + * If not found, the appropriate library will be extracted from the class path + * into a temporary directory and loaded from there. If your system has + * additional security constraints regarding execution or load of files + * (SELinux, for example), you should probably install the native library in + * an accessible location and configure your system accordingly, rather than + * relying on JNA to extract the library from its own jar file.

+ * To avoid the automatic unpacking (in situations where you want to force a + * failure if the JNA native library is not properly installed on the system), + * set the system property jna.nounpack=true. + * NOTE: all native functions are provided within this class to ensure that + * all other JNA-provided classes and objects are GC'd and/or + * finalized/disposed before this class is disposed and/or removed from + * memory (most notably Memory and any other class which by default frees its + * resources in a finalizer).

+ * @see Library + * @author Todd Fast, todd.fast@sun.com + * @author twall@users.sf.net + */ +public final class Native { + + private static final String VERSION = "3.5.2-SNAPSHOT"; + private static final String VERSION_NATIVE = "3.5.0"; + + // Used by tests, do not remove + private static String nativeLibraryPath = null; + private static Map typeMappers = new WeakHashMap(); + private static Map alignments = new WeakHashMap(); + private static Map options = new WeakHashMap(); + private static Map libraries = new WeakHashMap(); + private static final UncaughtExceptionHandler DEFAULT_HANDLER = + new UncaughtExceptionHandler() { + public void uncaughtException(Callback c, Throwable e) { + System.err.println("JNA: Callback " + c + " threw the following exception:"); + e.printStackTrace(); + } + }; + private static UncaughtExceptionHandler callbackExceptionHandler = DEFAULT_HANDLER; + + /** The size of a native pointer (void*) on the current + * platform, in bytes. + */ + public static final int POINTER_SIZE; + /** Size of a native long type, in bytes. */ + public static final int LONG_SIZE; + /** Size of a native wchar_t type, in bytes. */ + public static final int WCHAR_SIZE; + /** Size of a native size_t type, in bytes. */ + public static final int SIZE_T_SIZE; + + private static final int TYPE_VOIDP = 0; + private static final int TYPE_LONG = 1; + private static final int TYPE_WCHAR_T = 2; + private static final int TYPE_SIZE_T = 3; + + private static final int THREAD_NOCHANGE = 0; + private static final int THREAD_DETACH = -1; + private static final int THREAD_LEAVE_ATTACHED = -2; + + static { + loadNativeLibrary(); + POINTER_SIZE = sizeof(TYPE_VOIDP); + LONG_SIZE = sizeof(TYPE_LONG); + WCHAR_SIZE = sizeof(TYPE_WCHAR_T); + SIZE_T_SIZE = sizeof(TYPE_SIZE_T); + + // Perform initialization of other JNA classes until *after* + // initializing the above final fields + initIDs(); + if (Boolean.getBoolean("jna.protected")) { + setProtected(true); + } + String version = getNativeVersion(); + if (!VERSION_NATIVE.equals(version)) { + String LS = System.getProperty("line.separator"); + throw new Error(LS + LS + + "There is an incompatible JNA native library installed on this system." + LS + + "To resolve this issue you may do one of the following:" + LS + + " - remove or uninstall the offending library" + LS + + " - set the system property jna.nosys=true" + LS + + " - set jna.boot.library.path to include the path to the version of the " + LS + " jnidispatch library included with the JNA jar file you are using" + LS); + } + setPreserveLastError("true".equalsIgnoreCase(System.getProperty("jna.preserve_last_error", "true"))); + } + + /** Force a dispose when this class is GC'd. */ + private static final Object finalizer = new Object() { + protected void finalize() { + dispose(); + } + }; + + /** Properly dispose of JNA functionality. */ + private static void dispose() { + NativeLibrary.disposeAll(); + nativeLibraryPath = null; + } + + /** Remove any automatically unpacked native library. + + This will fail on windows, which disallows removal of any file that is + still in use, so an alternative is required in that case. Mark + the file that could not be deleted, and attempt to delete any + temporaries on next startup. + + Do NOT force the class loader to unload the native library, since + that introduces issues with cleaning up any extant JNA bits + (e.g. Memory) which may still need use of the library before shutdown. + */ + private static boolean deleteNativeLibrary(String path) { + File flib = new File(path); + if (flib.delete()) { + return true; + } + + // Couldn't delete it, mark for later deletion + markTemporaryFile(flib); + + return false; + } + + private Native() { } + + private static native void initIDs(); + + /** Set whether native memory accesses are protected from invalid + * accesses. This should only be set true when testing or debugging, + * and should not be considered reliable or robust for applications + * where JNA native calls are occurring on multiple threads. + * Protected mode will be automatically set if the + * system property jna.protected has a value of "true" + * when the JNA library is first loaded.

+ * If not supported by the underlying platform, this setting will + * have no effect.

+ * NOTE: On platforms which support signals (non-Windows), JNA uses + * signals to trap errors. This may interfere with the JVM's own use of + * signals. When protected mode is enabled, you should make use of the + * jsig library, if available (see Signal Chaining). + * In short, set the environment variable LD_PRELOAD to the + * path to libjsig.so in your JRE lib directory + * (usually ${java.home}/lib/${os.arch}/libjsig.so) before launching your + * Java application. + */ + public static synchronized native void setProtected(boolean enable); + + /** Returns whether protection is enabled. Check the result of this method + * after calling {@link #setProtected setProtected(true)} to determine + * if this platform supports protecting memory accesses. + */ + public static synchronized native boolean isProtected(); + + /** Set whether the system last error result is captured after every + * native invocation. Defaults to true (false + * for direct-mapped calls).

+ * @deprecated The preferred method of obtaining the last error result is + * to declare your mapped method to throw {@link LastErrorException} + * instead. + */ + public static synchronized native void setPreserveLastError(boolean enable); + + /** Indicates whether the system last error result is preserved + * after every invocation.

+ * @deprecated The preferred method of obtaining the last error result is + * to declare your mapped method to throw {@link LastErrorException} + * instead. + */ + public static synchronized native boolean getPreserveLastError(); + + /** Utility method to get the native window ID for a Java {@link Window} + * as a long value. + * This method is primarily for X11-based systems, which use an opaque + * XID (usually long int) to identify windows. + * @throws HeadlessException if the current VM is running headless + */ + public static long getWindowID(Window w) throws HeadlessException { + return AWT.getWindowID(w); + } + + /** Utility method to get the native window ID for a heavyweight Java + * {@link Component} as a long value. + * This method is primarily for X11-based systems, which use an opaque + * XID (usually long int) to identify windows. + * @throws HeadlessException if the current VM is running headless + */ + public static long getComponentID(Component c) throws HeadlessException { + return AWT.getComponentID(c); + } + + /** Utility method to get the native window pointer for a Java + * {@link Window} as a {@link Pointer} value. This method is primarily for + * w32, which uses the HANDLE type (actually + * void *) to identify windows. + * @throws HeadlessException if the current VM is running headless + */ + public static Pointer getWindowPointer(Window w) throws HeadlessException { + return new Pointer(AWT.getWindowID(w)); + } + + /** Utility method to get the native window pointer for a heavyweight Java + * {@link Component} as a {@link Pointer} value. This method is primarily + * for w32, which uses the HWND type (actually + * void *) to identify windows. + * @throws HeadlessException if the current VM is running headless + */ + public static Pointer getComponentPointer(Component c) throws HeadlessException { + return new Pointer(AWT.getComponentID(c)); + } + + static native long getWindowHandle0(Component c); + + /** Convert a direct {@link Buffer} into a {@link Pointer}. + * @throws IllegalArgumentException if the buffer is not direct. + */ + public static Pointer getDirectBufferPointer(Buffer b) { + long peer = _getDirectBufferPointer(b); + return peer == 0 ? null : new Pointer(peer); + } + + private static native long _getDirectBufferPointer(Buffer b); + + /** Obtain a Java String from the given native byte array. If there is + * no NUL terminator, the String will comprise the entire array. If the + * system property jna.encoding is set, its value will + * override the platform default encoding (if supported). + */ + public static String toString(byte[] buf) { + return toString(buf, System.getProperty("jna.encoding")); + } + + /** Obtain a Java String from the given native byte array, using the given + * encoding. If there is no NUL terminator, the String will comprise the + * entire array. If the encoding parameter is null, + * the platform default encoding will be used. + */ + public static String toString(byte[] buf, String encoding) { + String s = null; + if (encoding != null) { + try { + s = new String(buf, encoding); + } + catch(UnsupportedEncodingException e) { } + } + if (s == null) { + s = new String(buf); + } + int term = s.indexOf(0); + if (term != -1) + s = s.substring(0, term); + return s; + } + + /** Obtain a Java String from the given native wchar_t array. If there is + * no NUL terminator, the String will comprise the entire array. + */ + public static String toString(char[] buf) { + String s = new String(buf); + int term = s.indexOf(0); + if (term != -1) + s = s.substring(0, term); + return s; + } + + /** Map a library interface to the current process, providing + * the explicit interface class. + * @param interfaceClass + */ + public static Object loadLibrary(Class interfaceClass) { + return loadLibrary(null, interfaceClass); + } + + /** Map a library interface to the current process, providing + * the explicit interface class. + * @param interfaceClass + * @param options Map of library options + */ + public static Object loadLibrary(Class interfaceClass, Map options) { + return loadLibrary(null, interfaceClass, options); + } + + /** Map a library interface to the given shared library, providing + * the explicit interface class. + * If name is null, attempts to map onto the current process. + * @param name + * @param interfaceClass + */ + public static Object loadLibrary(String name, Class interfaceClass) { + return loadLibrary(name, interfaceClass, Collections.EMPTY_MAP); + } + + /** Load a library interface from the given shared library, providing + * the explicit interface class and a map of options for the library. + * If no library options are detected the map is interpreted as a map + * of Java method names to native function names.

+ * If name is null, attempts to map onto the current process. + * @param name + * @param interfaceClass + * @param options Map of library options + */ + public static Object loadLibrary(String name, + Class interfaceClass, + Map options) { + Library.Handler handler = + new Library.Handler(name, interfaceClass, options); + ClassLoader loader = interfaceClass.getClassLoader(); + Library proxy = (Library) + Proxy.newProxyInstance(loader, new Class[] {interfaceClass}, + handler); + cacheOptions(interfaceClass, options, proxy); + return proxy; + } + + /** Attempts to force initialization of an instance of the library interface + * by loading a public static field of the requisite type. + * Returns whether an instance variable was instantiated. + * Expects that lock on libraries is already held + */ + private static void loadLibraryInstance(Class cls) { + if (cls != null && !libraries.containsKey(cls)) { + try { + Field[] fields = cls.getFields(); + for (int i=0;i < fields.length;i++) { + Field field = fields[i]; + if (field.getType() == cls + && Modifier.isStatic(field.getModifiers())) { + // Ensure the field gets initialized by reading it + libraries.put(cls, new WeakReference(field.get(null))); + break; + } + } + } + catch (Exception e) { + throw new IllegalArgumentException("Could not access instance of " + + cls + " (" + e + ")"); + } + } + } + + /** Find the library interface corresponding to the given class. Checks + * all ancestor classes and interfaces for a declaring class which + * implements {@link Library}. + */ + static Class findEnclosingLibraryClass(Class cls) { + if (cls == null) { + return null; + } + synchronized(libraries) { + if (options.containsKey(cls)) { + return cls; + } + } + if (Library.class.isAssignableFrom(cls)) { + return cls; + } + if (Callback.class.isAssignableFrom(cls)) { + cls = CallbackReference.findCallbackClass(cls); + } + Class declaring = cls.getDeclaringClass(); + Class fromDeclaring = findEnclosingLibraryClass(declaring); + if (fromDeclaring != null) { + return fromDeclaring; + } + return findEnclosingLibraryClass(cls.getSuperclass()); + } + + + /** Return the preferred native library configuration options for the given + * class. + * @see Library + */ + public static Map getLibraryOptions(Class type) { + synchronized(libraries) { + Class interfaceClass = findEnclosingLibraryClass(type); + if (interfaceClass != null) + loadLibraryInstance(interfaceClass); + else + interfaceClass = type; + if (!options.containsKey(interfaceClass)) { + try { + Field field = interfaceClass.getField("OPTIONS"); + field.setAccessible(true); + options.put(interfaceClass, field.get(null)); + } + catch (NoSuchFieldException e) { + } + catch (Exception e) { + throw new IllegalArgumentException("OPTIONS must be a public field of type java.util.Map (" + + e + "): " + interfaceClass); + } + } + return (Map)options.get(interfaceClass); + } + } + + /** Return the preferred {@link TypeMapper} for the given native interface. + * See {@link com.sun.jna.Library#OPTION_TYPE_MAPPER}. + */ + public static TypeMapper getTypeMapper(Class cls) { + synchronized(libraries) { + Class interfaceClass = findEnclosingLibraryClass(cls); + if (interfaceClass != null) + loadLibraryInstance(interfaceClass); + else + interfaceClass = cls; + + if (!typeMappers.containsKey(interfaceClass)) { + try { + Field field = interfaceClass.getField("TYPE_MAPPER"); + field.setAccessible(true); + typeMappers.put(interfaceClass, field.get(null)); + } + catch (NoSuchFieldException e) { + Map options = getLibraryOptions(cls); + if (options != null + && options.containsKey(Library.OPTION_TYPE_MAPPER)) { + typeMappers.put(interfaceClass, options.get(Library.OPTION_TYPE_MAPPER)); + } + } + catch (Exception e) { + throw new IllegalArgumentException("TYPE_MAPPER must be a public field of type " + + TypeMapper.class.getName() + " (" + + e + "): " + interfaceClass); + } + } + return (TypeMapper)typeMappers.get(interfaceClass); + } + } + + /** Return the preferred structure alignment for the given native interface. + * See {@link com.sun.jna.Library#OPTION_STRUCTURE_ALIGNMENT}. + */ + public static int getStructureAlignment(Class cls) { + synchronized(libraries) { + Class interfaceClass = findEnclosingLibraryClass(cls); + if (interfaceClass != null) + loadLibraryInstance(interfaceClass); + else + interfaceClass = cls; + if (!alignments.containsKey(interfaceClass)) { + try { + Field field = interfaceClass.getField("STRUCTURE_ALIGNMENT"); + field.setAccessible(true); + alignments.put(interfaceClass, field.get(null)); + } + catch(NoSuchFieldException e) { + Map options = getLibraryOptions(interfaceClass); + if (options != null + && options.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) { + alignments.put(interfaceClass, options.get(Library.OPTION_STRUCTURE_ALIGNMENT)); + } + } + catch(Exception e) { + throw new IllegalArgumentException("STRUCTURE_ALIGNMENT must be a public field of type int (" + + e + "): " + interfaceClass); + } + } + Integer value = (Integer)alignments.get(interfaceClass); + return value != null ? value.intValue() : Structure.ALIGN_DEFAULT; + } + } + + /** Return a byte array corresponding to the given String. If the + * system property jna.encoding is set, its value will override + * the default platform encoding (if supported). + */ + static byte[] getBytes(String s) { + try { + return getBytes(s, System.getProperty("jna.encoding")); + } + catch (UnsupportedEncodingException e) { + return s.getBytes(); + } + } + + /** Return a byte array corresponding to the given String, using the given + encoding. + */ + static byte[] getBytes(String s, String encoding) throws UnsupportedEncodingException { + if (encoding != null) { + return s.getBytes(encoding); + } + return s.getBytes(); + } + + /** Obtain a NUL-terminated byte buffer equivalent to the given String, + using jna.encoding or the default platform encoding if + that property is not set. + */ + public static byte[] toByteArray(String s) { + byte[] bytes = getBytes(s); + byte[] buf = new byte[bytes.length+1]; + System.arraycopy(bytes, 0, buf, 0, bytes.length); + return buf; + } + + /** Obtain a NUL-terminated byte buffer equivalent to the given String, + using the given encoding. + */ + public static byte[] toByteArray(String s, String encoding) throws UnsupportedEncodingException { + byte[] bytes = getBytes(s, encoding); + byte[] buf = new byte[bytes.length+1]; + System.arraycopy(bytes, 0, buf, 0, bytes.length); + return buf; + } + + /** Obtain a NUL-terminated wide character buffer equivalent to the given + String. + */ + public static char[] toCharArray(String s) { + char[] chars = s.toCharArray(); + char[] buf = new char[chars.length+1]; + System.arraycopy(chars, 0, buf, 0, chars.length); + return buf; + } + + /** Generate a canonical String prefix based on the given OS + type/arch/name. + */ + static String getNativeLibraryResourcePath(int osType, String arch, String name) { + String osPrefix; + arch = arch.toLowerCase(); + if ("powerpc".equals(arch)) { + arch = "ppc"; + } + else if ("powerpc64".equals(arch)) { + arch = "ppc64"; + } + switch(osType) { + case Platform.ANDROID: + if (arch.startsWith("arm")) { + arch = "arm"; + } + osPrefix = "android-" + arch; + break; + case Platform.WINDOWS: + if ("i386".equals(arch)) { + arch = "x86"; + } + osPrefix = "win32-" + arch; + break; + case Platform.WINDOWSCE: + osPrefix = "w32ce-" + arch; + break; + case Platform.MAC: + osPrefix = "darwin"; + break; + case Platform.LINUX: + if ("x86".equals(arch)) { + arch = "i386"; + } + else if ("x86_64".equals(arch)) { + arch = "amd64"; + } + osPrefix = "linux-" + arch; + break; + case Platform.SOLARIS: + osPrefix = "sunos-" + arch; + break; + default: + osPrefix = name.toLowerCase(); + if ("x86".equals(arch)) { + arch = "i386"; + } + if ("x86_64".equals(arch)) { + arch = "amd64"; + } + int space = osPrefix.indexOf(" "); + if (space != -1) { + osPrefix = osPrefix.substring(0, space); + } + osPrefix += "-" + arch; + break; + } + return "/com/sun/jna/" + osPrefix; + } + + /** + * Loads the JNA stub library. + * First tries jna.boot.library.path, then the system path, then from the + * jar file. + */ + private static void loadNativeLibrary() { + removeTemporaryFiles(); + + String libName = System.getProperty("jna.boot.library.name", "jnidispatch"); + String bootPath = System.getProperty("jna.boot.library.path"); + if (bootPath != null) { + // String.split not available in 1.4 + StringTokenizer dirs = new StringTokenizer(bootPath, File.pathSeparator); + while (dirs.hasMoreTokens()) { + String dir = dirs.nextToken(); + File file = new File(new File(dir), System.mapLibraryName(libName)); + String path = file.getAbsolutePath(); + if (file.exists()) { + try { + System.load(path); + nativeLibraryPath = path; + return; + } catch (UnsatisfiedLinkError ex) { + // Not a problem if already loaded in anoteher class loader + // Unfortunately we can't distinguish the difference... + //System.out.println("File found at " + file + " but not loadable: " + ex.getMessage()); + } + } + if (Platform.isMac()) { + String orig, ext; + if (path.endsWith("dylib")) { + orig = "dylib"; + ext = "jnilib"; + } else { + orig = "jnilib"; + ext = "dylib"; + } + path = path.substring(0, path.lastIndexOf(orig)) + ext; + if (new File(path).exists()) { + try { + System.load(path); + nativeLibraryPath = path; + return; + } catch (UnsatisfiedLinkError ex) { + System.err.println("File found at " + path + " but not loadable: " + ex.getMessage()); + } + } + } + } + } + if (Platform.isAndroid()) { + // Native libraries on android must be bundled with the APK + System.setProperty("jna.nounpack", "true"); + } + try { + if (!Boolean.getBoolean("jna.nosys")) { + System.loadLibrary(libName); + return; + } + } + catch(UnsatisfiedLinkError e) { + if (Boolean.getBoolean("jna.nounpack")) { + throw e; + } + } + if (!Boolean.getBoolean("jna.nounpack")) { + loadNativeLibraryFromJar(); + return; + } + throw new UnsatisfiedLinkError("Native jnidispatch library not found"); + } + + /** + * Attempts to load the native library resource from the filesystem, + * extracting the JNA stub library from jna.jar if not already available. + */ + private static void loadNativeLibraryFromJar() { + String libname = System.mapLibraryName("jnidispatch"); + String arch = System.getProperty("os.arch"); + String name = System.getProperty("os.name"); + String resourceName = getNativeLibraryResourcePath(Platform.getOSType(), arch, name) + "/" + libname; + URL url = Native.class.getResource(resourceName); + boolean unpacked = false; + + // Add an ugly hack for OpenJDK (soylatte) - JNI libs use the usual + // .dylib extension + if (url == null && Platform.isMac() + && resourceName.endsWith(".dylib")) { + resourceName = resourceName.substring(0, resourceName.lastIndexOf(".dylib")) + ".jnilib"; + url = Native.class.getResource(resourceName); + } + if (url == null) { + throw new UnsatisfiedLinkError("JNA native support (" + resourceName + + ") not found in resource path"); + } + + File lib = null; + if (url.getProtocol().toLowerCase().equals("file")) { + try { + lib = new File(new URI(url.toString())); + } + catch(URISyntaxException e) { + lib = new File(url.getPath()); + } + if (!lib.exists()) { + throw new Error("File URL " + url + " could not be properly decoded"); + } + } + else { + InputStream is = Native.class.getResourceAsStream(resourceName); + if (is == null) { + throw new Error("Can't obtain jnidispatch InputStream"); + } + + FileOutputStream fos = null; + try { + // Suffix is required on windows, or library fails to load + // Let Java pick the suffix, except on windows, to avoid + // problems with Web Start. + File dir = getTempDir(); + lib = File.createTempFile("jna", Platform.isWindows()?".dll":null, dir); + lib.deleteOnExit(); + fos = new FileOutputStream(lib); + int count; + byte[] buf = new byte[1024]; + while ((count = is.read(buf, 0, buf.length)) > 0) { + fos.write(buf, 0, count); + } + unpacked = true; + } + catch(IOException e) { + throw new Error("Failed to create temporary file for jnidispatch library", e); + } + finally { + try { is.close(); } catch(IOException e) { } + if (fos != null) { + try { fos.close(); } catch(IOException e) { } + } + } + } + System.load(lib.getAbsolutePath()); + nativeLibraryPath = lib.getAbsolutePath(); + // Attempt to delete immediately once jnidispatch is successfully + // loaded. This avoids the complexity of trying to do so on "exit", + // which point can vary under different circumstances (native + // compilation, dynamically loaded modules, normal application, etc). + if (unpacked) { + deleteNativeLibrary(lib.getAbsolutePath()); + } + } + + /** + * Initialize field and method IDs for native methods of this class. + * Returns the size of a native pointer. + **/ + private static native int sizeof(int type); + + private static native String getNativeVersion(); + private static native String getAPIChecksum(); + + private static final ThreadLocal lastError = new ThreadLocal() { + protected synchronized Object initialValue() { + return new Integer(0); + } + }; + + /** Retrieve the last error set by the OS. This corresponds to + * GetLastError() on Windows, and errno on + * most other platforms. The value is preserved per-thread, but whether + * the original value is per-thread depends on the underlying OS. The + * result is undefined if {@link #getPreserveLastError} is + * false.

+ * The preferred method of obtaining the last error result is + * to declare your mapped method to throw {@link LastErrorException} + * instead. + */ + public static int getLastError() { + return ((Integer)lastError.get()).intValue(); + } + + /** Set the OS last error code. Whether the setting is per-thread + * or global depends on the underlying OS. + */ + public static native void setLastError(int code); + + /** Update the last error value (called from native code). */ + // This has to be called immediately after a native call to ensure that + // subsequent VM operations don't overwrite the last error value + static void updateLastError(int e) { + lastError.set(new Integer(e)); + } + + /** + * Returns a synchronized (thread-safe) library backed by the specified + * library. This wrapping will prevent simultaneous invocations of any + * functions mapped to a given {@link NativeLibrary}. Note that the + * native library may still be sensitive to being called from different + * threads. + *

+ * @param library the library to be "wrapped" in a synchronized library. + * @return a synchronized view of the specified library. + */ + public static Library synchronizedLibrary(final Library library) { + Class cls = library.getClass(); + if (!Proxy.isProxyClass(cls)) { + throw new IllegalArgumentException("Library must be a proxy class"); + } + InvocationHandler ih = Proxy.getInvocationHandler(library); + if (!(ih instanceof Library.Handler)) { + throw new IllegalArgumentException("Unrecognized proxy handler: " + ih); + } + final Library.Handler handler = (Library.Handler)ih; + InvocationHandler newHandler = new InvocationHandler() { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + synchronized(handler.getNativeLibrary()) { + return handler.invoke(library, method, args); + } + } + }; + return (Library)Proxy.newProxyInstance(cls.getClassLoader(), + cls.getInterfaces(), + newHandler); + } + + /** If running web start, determine the location of a given native + * library. This value may be used to properly set + * jna.library.path so that JNA can load libraries identified + * by the <nativelib> tag in the JNLP configuration file. Returns + * null if the Web Start native library cache location can not + * be determined. Note that the path returned may be different for any + * given library name. + *

+ * Use System.getProperty("javawebstart.version") to detect + * whether your code is running under Web Start. + * @throws UnsatisfiedLinkError if the library can't be found by the + * Web Start class loader, which usually means it wasn't included as + * a <nativelib> resource in the JNLP file. + * @return null if unable to query the web start loader. + */ + public static String getWebStartLibraryPath(final String libName) { + if (System.getProperty("javawebstart.version") == null) + return null; + try { + + final ClassLoader cl = Native.class.getClassLoader(); + Method m = (Method)AccessController.doPrivileged(new PrivilegedAction() { + public Object run() { + try { + Method m = ClassLoader.class.getDeclaredMethod("findLibrary", new Class[] { String.class }); + m.setAccessible(true); + return m; + } + catch(Exception e) { + return null; + } + } + }); + String libpath = (String)m.invoke(cl, new Object[] { libName }); + if (libpath != null) { + return new File(libpath).getParent(); + } + return null; + } + catch (Exception e) { + return null; + } + } + + /** Perform cleanup of automatically unpacked native shared library. + */ + static void markTemporaryFile(File file) { + // If we can't force an unload/delete, flag the file for later + // deletion + try { + File marker = new File(file.getParentFile(), file.getName() + ".x"); + marker.createNewFile(); + } + catch(IOException e) { e.printStackTrace(); } + } + + /** Obtain a directory suitable for writing JNA-specific temporary files. + Override with jna.tmpdir + */ + static File getTempDir() { + File jnatmp; + String prop = System.getProperty("jna.tmpdir"); + if (prop != null) { + jnatmp = new File(prop); + } + else { + File tmp = new File(System.getProperty("java.io.tmpdir")); + jnatmp = new File(tmp, "jna-" + System.getProperty("user.name")); + jnatmp.mkdirs(); + if (!jnatmp.exists() || !jnatmp.canWrite()) { + jnatmp = tmp; + } + } + if (!jnatmp.exists()) { + throw new Error("JNA temporary directory " + jnatmp + " does not exist"); + } + if (!jnatmp.canWrite()) { + throw new Error("JNA temporary directory " + jnatmp + " is not writable"); + } + return jnatmp; + } + + /** Remove all marked temporary files in the given directory. */ + static void removeTemporaryFiles() { + File dir = getTempDir(); + FilenameFilter filter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(".x") && name.indexOf("jna") != -1; + } + }; + File[] files = dir.listFiles(filter); + for (int i=0;files != null && i < files.length;i++) { + File marker = files[i]; + String name = marker.getName(); + name = name.substring(0, name.length()-2); + File target = new File(marker.getParentFile(), name); + if (!target.exists() || target.delete()) { + marker.delete(); + } + } + } + + /** Returns the native size of the given class, in bytes. + * For use with arrays. + */ + public static int getNativeSize(Class type, Object value) { + if (type.isArray()) { + int len = Array.getLength(value); + if (len > 0) { + Object o = Array.get(value, 0); + return len * getNativeSize(type.getComponentType(), o); + } + // Don't process zero-length arrays + throw new IllegalArgumentException("Arrays of length zero not allowed: " + type); + } + if (Structure.class.isAssignableFrom(type) + && !Structure.ByReference.class.isAssignableFrom(type)) { + if (value == null) + value = Structure.newInstance(type); + return ((Structure)value).size(); + } + try { + return getNativeSize(type); + } + catch(IllegalArgumentException e) { + throw new IllegalArgumentException("The type \"" + type.getName() + + "\" is not supported: " + + e.getMessage()); + } + } + + /** Returns the native size for a given Java class. Structures are + * assumed to be struct pointers unless they implement + * {@link Structure.ByValue}. + */ + public static int getNativeSize(Class cls) { + if (NativeMapped.class.isAssignableFrom(cls)) { + cls = NativeMappedConverter.getInstance(cls).nativeType(); + } + // boolean defaults to 32 bit integer if not otherwise mapped + if (cls == boolean.class || cls == Boolean.class) return 4; + if (cls == byte.class || cls == Byte.class) return 1; + if (cls == short.class || cls == Short.class) return 2; + if (cls == char.class || cls == Character.class) return WCHAR_SIZE; + if (cls == int.class || cls == Integer.class) return 4; + if (cls == long.class || cls == Long.class) return 8; + if (cls == float.class || cls == Float.class) return 4; + if (cls == double.class || cls == Double.class) return 8; + if (Structure.class.isAssignableFrom(cls)) { + if (Structure.ByValue.class.isAssignableFrom(cls)) { + return Structure.newInstance(cls).size(); + } + return POINTER_SIZE; + } + if (Pointer.class.isAssignableFrom(cls) + || (Platform.HAS_BUFFERS && Buffers.isBuffer(cls)) + || Callback.class.isAssignableFrom(cls) + || String.class == cls + || WString.class == cls) { + return POINTER_SIZE; + } + throw new IllegalArgumentException("Native size for type \"" + cls.getName() + + "\" is unknown"); + } + + /** Indicate whether the given class is supported as a native argument + * type. + */ + public static boolean isSupportedNativeType(Class cls) { + if (Structure.class.isAssignableFrom(cls)) { + return true; + } + try { + return getNativeSize(cls) != 0; + } + catch(IllegalArgumentException e) { + return false; + } + } + + /** Set the default handler invoked when a callback throws an uncaught + * exception. If the given handler is null, the default + * handler will be reinstated. + */ + public static void setCallbackExceptionHandler(UncaughtExceptionHandler eh) { + callbackExceptionHandler = eh == null ? DEFAULT_HANDLER : eh; + } + + /** Returns the current handler for callback uncaught exceptions. */ + public static UncaughtExceptionHandler getCallbackExceptionHandler() { + return callbackExceptionHandler; + } + + /** When called from a class static initializer, maps all native methods + * found within that class to native libraries via the JNA raw calling + * interface. + * @param libName library name to which functions should be bound + */ + public static void register(String libName) { + register(getNativeClass(getCallingClass()), + NativeLibrary.getInstance(libName)); + } + + /** When called from a class static initializer, maps all native methods + * found within that class to native libraries via the JNA raw calling + * interface. + * @param lib native library to which functions should be bound + */ + public static void register(NativeLibrary lib) { + register(getNativeClass(getCallingClass()), lib); + } + + static Class getNativeClass(Class cls) { + Method[] methods = cls.getDeclaredMethods(); + for (int i=0;i < methods.length;i++) { + if ((methods[i].getModifiers() & Modifier.NATIVE) != 0) { + return cls; + } + } + int idx = cls.getName().lastIndexOf("$"); + if (idx != -1) { + String name = cls.getName().substring(0, idx); + try { + return getNativeClass(Class.forName(name, true, cls.getClassLoader())); + } + catch(ClassNotFoundException e) { + } + } + throw new IllegalArgumentException("Can't determine class with native methods from the current context (" + cls + ")"); + } + + static Class getCallingClass() { + Class[] context = new SecurityManager() { + public Class[] getClassContext() { + return super.getClassContext(); + } + }.getClassContext(); + if (context.length < 4) { + throw new IllegalStateException("This method must be called from the static initializer of a class"); + } + return context[3]; + } + + /** Set a thread initializer for the given callback. + The thread initializer indicates desired thread configuration when the + given Callback is invoked on a native thread not yet attached to the + VM. + */ + public static void setCallbackThreadInitializer(Callback cb, CallbackThreadInitializer initializer) { + CallbackReference.setCallbackThreadInitializer(cb, initializer); + } + + + private static Map registeredClasses = new HashMap(); + private static Map registeredLibraries = new HashMap(); + private static Object unloader = new Object() { + protected void finalize() { + synchronized(registeredClasses) { + for (Iterator i=registeredClasses.entrySet().iterator();i.hasNext();) { + Map.Entry e = (Map.Entry)i.next(); + unregister((Class)e.getKey(), (long[])e.getValue()); + i.remove(); + } + } + } + }; + + /** Remove all native mappings for the calling class. + Should only be called if the class is no longer referenced and about + to be garbage collected. + */ + public static void unregister() { + unregister(getNativeClass(getCallingClass())); + } + + /** Remove all native mappings for the given class. + Should only be called if the class is no longer referenced and about + to be garbage collected. + */ + public static void unregister(Class cls) { + synchronized(registeredClasses) { + if (registeredClasses.containsKey(cls)) { + unregister(cls, (long[])registeredClasses.get(cls)); + registeredClasses.remove(cls); + registeredLibraries.remove(cls); + } + } + } + + /** Unregister the native methods for the given class. */ + private static native void unregister(Class cls, long[] handles); + + private static String getSignature(Class cls) { + if (cls.isArray()) { + return "[" + getSignature(cls.getComponentType()); + } + if (cls.isPrimitive()) { + if (cls == void.class) return "V"; + if (cls == boolean.class) return "Z"; + if (cls == byte.class) return "B"; + if (cls == short.class) return "S"; + if (cls == char.class) return "C"; + if (cls == int.class) return "I"; + if (cls == long.class) return "J"; + if (cls == float.class) return "F"; + if (cls == double.class) return "D"; + } + return "L" + replace(".", "/", cls.getName()) + ";"; + } + + // No String.replace available in 1.4 + static String replace(String s1, String s2, String str) { + StringBuffer buf = new StringBuffer(); + while (true) { + int idx = str.indexOf(s1); + if (idx == -1) { + buf.append(str); + break; + } + else { + buf.append(str.substring(0, idx)); + buf.append(s2); + str = str.substring(idx + s1.length()); + } + } + return buf.toString(); + } + + /** Indicates whether the callback has an initializer. */ + static final int CB_HAS_INITIALIZER = 1; + + private static final int CVT_UNSUPPORTED = -1; + private static final int CVT_DEFAULT = 0; + private static final int CVT_POINTER = 1; + private static final int CVT_STRING = 2; + private static final int CVT_STRUCTURE = 3; + private static final int CVT_STRUCTURE_BYVAL = 4; + private static final int CVT_BUFFER = 5; + private static final int CVT_ARRAY_BYTE = 6; + private static final int CVT_ARRAY_SHORT = 7; + private static final int CVT_ARRAY_CHAR = 8; + private static final int CVT_ARRAY_INT = 9; + private static final int CVT_ARRAY_LONG = 10; + private static final int CVT_ARRAY_FLOAT = 11; + private static final int CVT_ARRAY_DOUBLE = 12; + private static final int CVT_ARRAY_BOOLEAN = 13; + private static final int CVT_BOOLEAN = 14; + private static final int CVT_CALLBACK = 15; + private static final int CVT_FLOAT = 16; + private static final int CVT_NATIVE_MAPPED = 17; + private static final int CVT_WSTRING = 18; + private static final int CVT_INTEGER_TYPE = 19; + private static final int CVT_POINTER_TYPE = 20; + private static final int CVT_TYPE_MAPPER = 21; + + private static int getConversion(Class type, TypeMapper mapper) { + if (type == Boolean.class) type = boolean.class; + else if (type == Byte.class) type = byte.class; + else if (type == Short.class) type = short.class; + else if (type == Character.class) type = char.class; + else if (type == Integer.class) type = int.class; + else if (type == Long.class) type = long.class; + else if (type == Float.class) type = float.class; + else if (type == Double.class) type = double.class; + else if (type == Void.class) type = void.class; + + if (mapper != null + && (mapper.getFromNativeConverter(type) != null + || mapper.getToNativeConverter(type) != null)) { + return CVT_TYPE_MAPPER; + } + + if (Pointer.class.isAssignableFrom(type)) { + return CVT_POINTER; + } + if (String.class == type) { + return CVT_STRING; + } + if (WString.class.isAssignableFrom(type)) { + return CVT_WSTRING; + } + if (Platform.HAS_BUFFERS && Buffers.isBuffer(type)) { + return CVT_BUFFER; + } + if (Structure.class.isAssignableFrom(type)) { + if (Structure.ByValue.class.isAssignableFrom(type)) { + return CVT_STRUCTURE_BYVAL; + } + return CVT_STRUCTURE; + } + if (type.isArray()) { + switch(type.getName().charAt(1)) { + case 'Z': return CVT_ARRAY_BOOLEAN; + case 'B': return CVT_ARRAY_BYTE; + case 'S': return CVT_ARRAY_SHORT; + case 'C': return CVT_ARRAY_CHAR; + case 'I': return CVT_ARRAY_INT; + case 'J': return CVT_ARRAY_LONG; + case 'F': return CVT_ARRAY_FLOAT; + case 'D': return CVT_ARRAY_DOUBLE; + default: break; + } + } + if (type.isPrimitive()) { + return type == boolean.class ? CVT_BOOLEAN : CVT_DEFAULT; + } + if (Callback.class.isAssignableFrom(type)) { + return CVT_CALLBACK; + } + if (IntegerType.class.isAssignableFrom(type)) { + return CVT_INTEGER_TYPE; + } + if (PointerType.class.isAssignableFrom(type)) { + return CVT_POINTER_TYPE; + } + if (NativeMapped.class.isAssignableFrom(type)) { + return CVT_NATIVE_MAPPED; + } + return CVT_UNSUPPORTED; + } + + /** When called from a class static initializer, maps all native methods + * found within that class to native libraries via the JNA raw calling + * interface. + * @param lib library to which functions should be bound + */ + // TODO: derive options from annotations (per-class or per-method) + // options: read parameter type mapping (long/native long), + // method name, library name, call conv + public static void register(Class cls, NativeLibrary lib) { + Method[] methods = cls.getDeclaredMethods(); + List mlist = new ArrayList(); + TypeMapper mapper = (TypeMapper) + lib.getOptions().get(Library.OPTION_TYPE_MAPPER); + + for (int i=0;i < methods.length;i++) { + if ((methods[i].getModifiers() & Modifier.NATIVE) != 0) { + mlist.add(methods[i]); + } + } + long[] handles = new long[mlist.size()]; + for (int i=0;i < handles.length;i++) { + Method method = (Method)mlist.get(i); + String sig = "("; + Class rclass = method.getReturnType(); + long rtype, closure_rtype; + Class[] ptypes = method.getParameterTypes(); + long[] atypes = new long[ptypes.length]; + long[] closure_atypes = new long[ptypes.length]; + int[] cvt = new int[ptypes.length]; + ToNativeConverter[] toNative = new ToNativeConverter[ptypes.length]; + FromNativeConverter fromNative = null; + int rcvt = getConversion(rclass, mapper); + boolean throwLastError = false; + switch (rcvt) { + case CVT_UNSUPPORTED: + throw new IllegalArgumentException(rclass + " is not a supported return type (in method " + method.getName() + " in " + cls + ")"); + case CVT_TYPE_MAPPER: + fromNative = mapper.getFromNativeConverter(rclass); + closure_rtype = FFIType.get(rclass).peer; + rtype = FFIType.get(fromNative.nativeType()).peer; + break; + case CVT_NATIVE_MAPPED: + case CVT_INTEGER_TYPE: + case CVT_POINTER_TYPE: + closure_rtype = FFIType.get(Pointer.class).peer; + rtype = FFIType.get(NativeMappedConverter.getInstance(rclass).nativeType()).peer; + break; + case CVT_STRUCTURE: + closure_rtype = rtype = FFIType.get(Pointer.class).peer; + break; + case CVT_STRUCTURE_BYVAL: + closure_rtype = FFIType.get(Pointer.class).peer; + rtype = FFIType.get(rclass).peer; + break; + default: + closure_rtype = rtype = FFIType.get(rclass).peer; + break; + } + for (int t=0;t < ptypes.length;t++) { + Class type = ptypes[t]; + sig += getSignature(type); + cvt[t] = getConversion(type, mapper); + if (cvt[t] == CVT_UNSUPPORTED) { + throw new IllegalArgumentException(type + " is not a supported argument type (in method " + method.getName() + " in " + cls + ")"); + } + if (cvt[t] == CVT_NATIVE_MAPPED + || cvt[t] == CVT_INTEGER_TYPE) { + type = NativeMappedConverter.getInstance(type).nativeType(); + } + else if (cvt[t] == CVT_TYPE_MAPPER) { + toNative[t] = mapper.getToNativeConverter(type); + } + // Determine the type that will be passed to the native + // function, as well as the type to be passed + // from Java initially + switch(cvt[t]) { + case CVT_STRUCTURE_BYVAL: + case CVT_INTEGER_TYPE: + case CVT_POINTER_TYPE: + case CVT_NATIVE_MAPPED: + atypes[t] = FFIType.get(type).peer; + closure_atypes[t] = FFIType.get(Pointer.class).peer; + break; + case CVT_TYPE_MAPPER: + if (type.isPrimitive()) + closure_atypes[t] = FFIType.get(type).peer; + else + closure_atypes[t] = FFIType.get(Pointer.class).peer; + atypes[t] = FFIType.get(toNative[t].nativeType()).peer; + break; + case CVT_DEFAULT: + closure_atypes[t] = atypes[t] = FFIType.get(type).peer; + break; + default: + closure_atypes[t] = atypes[t] = FFIType.get(Pointer.class).peer; + break; + } + } + sig += ")"; + sig += getSignature(rclass); + + Class[] etypes = method.getExceptionTypes(); + for (int e=0;e < etypes.length;e++) { + if (LastErrorException.class.isAssignableFrom(etypes[e])) { + throwLastError = true; + break; + } + } + + String name = method.getName(); + FunctionMapper fmapper = (FunctionMapper)lib.getOptions().get(Library.OPTION_FUNCTION_MAPPER); + if (fmapper != null) { + name = fmapper.getFunctionName(lib, method); + } + Function f = lib.getFunction(name, method); + try { + handles[i] = registerMethod(cls, method.getName(), + sig, cvt, + closure_atypes, atypes, rcvt, + closure_rtype, rtype, + rclass, + f.peer, f.getCallingConvention(), + throwLastError, + toNative, fromNative); + } + catch(NoSuchMethodError e) { + throw new UnsatisfiedLinkError("No method " + method.getName() + " with signature " + sig + " in " + cls); + } + } + synchronized(registeredClasses) { + registeredClasses.put(cls, handles); + registeredLibraries.put(cls, lib); + } + cacheOptions(cls, lib.getOptions(), null); + } + + /** Take note of options used for a given library mapping, to facilitate + looking them up later. + */ + private static void cacheOptions(Class cls, Map libOptions, Object proxy) { + synchronized(libraries) { + if (!libOptions.isEmpty()) + options.put(cls, libOptions); + if (libOptions.containsKey(Library.OPTION_TYPE_MAPPER)) + typeMappers.put(cls, libOptions.get(Library.OPTION_TYPE_MAPPER)); + if (libOptions.containsKey(Library.OPTION_STRUCTURE_ALIGNMENT)) + alignments.put(cls, libOptions.get(Library.OPTION_STRUCTURE_ALIGNMENT)); + if (proxy != null) { + libraries.put(cls, new WeakReference(proxy)); + } + + // If it's a direct mapping, AND implements a Library interface, + // cache the library interface as well, so that any nested + // classes get the appropriate associated options + if (!cls.isInterface() + && Library.class.isAssignableFrom(cls)) { + Class ifaces[] = cls.getInterfaces(); + for (int i=0;i < ifaces.length;i++) { + if (Library.class.isAssignableFrom(ifaces[i])) { + cacheOptions(ifaces[i], libOptions, proxy); + break; + } + } + } + } + } + + private static native long registerMethod(Class cls, + String name, + String signature, + int[] conversions, + long[] closure_arg_types, + long[] arg_types, + int rconversion, + long closure_rtype, + long rtype, + Class rclass, + long fptr, + int callingConvention, + boolean throwLastError, + ToNativeConverter[] toNative, + FromNativeConverter fromNative); + + + // Called from native code + private static NativeMapped fromNative(Class cls, Object value) { + // NOTE: technically should be either CallbackParameterContext or + // FunctionResultContext + return (NativeMapped)NativeMappedConverter.getInstance(cls).fromNative(value, new FromNativeContext(cls)); + } + // Called from native code + private static Class nativeType(Class cls) { + return NativeMappedConverter.getInstance(cls).nativeType(); + } + // Called from native code + private static Object toNative(ToNativeConverter cvt, Object o) { + // NOTE: technically should be either CallbackResultContext or + // FunctionParameterContext + return cvt.toNative(o, new ToNativeContext()); + } + // Called from native code + private static Object fromNative(FromNativeConverter cvt, Object o, Class cls) { + // NOTE: technically should be FunctionResultContext + return cvt.fromNative(o, new FromNativeContext(cls)); + } + + /** Create a new cif structure. */ + public static native long ffi_prep_cif(int abi, int nargs, long ffi_return_type, long ffi_types); + /** Make an FFI function call. */ + public static native void ffi_call(long cif, long fptr, long resp, long args); + public static native long ffi_prep_closure(long cif, ffi_callback cb); + public static native void ffi_free_closure(long closure); + + /** Returns the size (calculated by libffi) of the given type. */ + static native int initialize_ffi_type(long type_info); + + public interface ffi_callback { + void invoke(long cif, long resp, long argp); + } + + /** Prints JNA library details to the console. */ + public static void main(String[] args) { + final String DEFAULT_TITLE = "Java Native Access (JNA)"; + final String DEFAULT_VERSION = VERSION; + final String DEFAULT_BUILD = VERSION + " (package information missing)"; + Package pkg = Native.class.getPackage(); + String title = pkg != null + ? pkg.getSpecificationTitle() : DEFAULT_TITLE; + if (title == null) title = DEFAULT_TITLE; + String version = pkg != null + ? pkg.getSpecificationVersion() : DEFAULT_VERSION; + if (version == null) version = DEFAULT_VERSION; + title += " API Version " + version; + System.out.println(title); + version = pkg != null + ? pkg.getImplementationVersion() : DEFAULT_BUILD; + if (version == null) version = DEFAULT_BUILD; + System.out.println("Version: " + version); + System.out.println(" Native: " + getNativeVersion() + " (" + + getAPIChecksum() + ")"); + System.exit(0); + } + + /** Free the given callback trampoline. */ + static synchronized native void freeNativeCallback(long ptr); + + /** Use direct mapping for callback. */ + static final int CB_OPTION_DIRECT = 1; + /** Return a DLL-resident fucntion pointer. */ + static final int CB_OPTION_IN_DLL = 2; + + /** Create a native trampoline to delegate execution to the Java callback. + */ + static synchronized native long createNativeCallback(Callback callback, + Method method, + Class[] parameterTypes, + Class returnType, + int callingConvention, + int flags); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + * + * @return The value returned by the target native function + */ + static native int invokeInt(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + * + * @return The value returned by the target native function + */ + static native long invokeLong(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + */ + static native void invokeVoid(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + * + * @return The value returned by the target native function + */ + static native float invokeFloat(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + * + * @return The value returned by the target native function + */ + static native double invokeDouble(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args + * Arguments to pass to the native function + * + * @return The native pointer returned by the target native function + */ + static native long invokePointer(long fp, int callFlags, Object[] args); + + /** + * Call the native function being represented by this object, returning + * a struct by value. + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args Arguments to pass to the native function + * @param memory Memory for pre-allocated structure to hold the result + * @param typeInfo Native type information for the Structure + */ + private static native void invokeStructure(long fp, int callFlags, + Object[] args, long memory, + long type_info); + + /** + * Call the native function being represented by this object, returning + * a struct by value. + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args Arguments to pass to the native function + * @return the passed-in Structure + */ + static Structure invokeStructure(long fp, int callFlags, Object[] args, + Structure s) { + invokeStructure(fp, callFlags, args, s.getPointer().peer, + s.getTypeInfo().peer); + return s; + } + + /** + * Call the native function being represented by this object, returning + * a Java Object. + * @param fp function pointer + * @param callFlags calling convention to be used + * @param args Arguments to pass to the native function + * + * @return The returned Java Object + */ + static native Object invokeObject(long fp, int callFlags, Object[] args); + + /** Open the requested native library with default options. */ + static long open(String name) { + return open(name, -1); + } + + /** Open the requested native library with the specified platform-specific + * otions. + */ + static native long open(String name, int flags); + + /** Close the given native library. */ + static native void close(long handle); + + static native long findSymbol(long handle, String name); + + static native long indexOf(long addr, byte value); + + static native void read(long addr, byte[] buf, int index, int length); + + static native void read(long addr, short[] buf, int index, int length); + + static native void read(long addr, char[] buf, int index, int length); + + static native void read(long addr, int[] buf, int index, int length); + + static native void read(long addr, long[] buf, int index, int length); + + static native void read(long addr, float[] buf, int index, int length); + + static native void read(long addr, double[] buf, int index, int length); + + static native void write(long addr, byte[] buf, int index, int length); + + static native void write(long addr, short[] buf, int index, int length); + + static native void write(long addr, char[] buf, int index, int length); + + static native void write(long addr, int[] buf, int index, int length); + + static native void write(long addr, long[] buf, int index, int length); + + static native void write(long addr, float[] buf, int index, int length); + + static native void write(long addr, double[] buf, int index, int length); + + static native byte getByte(long addr); + + static native char getChar(long addr); + + static native short getShort(long addr); + + static native int getInt(long addr); + + static native long getLong(long addr); + + static native float getFloat(long addr); + + static native double getDouble(long addr); + + static Pointer getPointer(long addr) { + long peer = _getPointer(addr); + return peer == 0 ? null : new Pointer(peer); + } + + private static native long _getPointer(long addr); + + static native String getString(long addr, boolean wide); + + static native void setMemory(long addr, long length, byte value); + + static native void setByte(long addr, byte value); + + static native void setShort(long addr, short value); + + static native void setChar(long addr, char value); + + static native void setInt(long addr, int value); + + static native void setLong(long addr, long value); + + static native void setFloat(long addr, float value); + + static native void setDouble(long addr, double value); + + static native void setPointer(long addr, long value); + + static native void setString(long addr, String value, boolean wide); + + /** + * Call the real native malloc + * @param size size of the memory to be allocated + * @return native address of the allocated memory block; zero if the + * allocation failed. + */ + public static native long malloc(long size); + + /** + * Call the real native free + * @param ptr native address to be freed; a value of zero has no effect, + * passing an already-freed pointer will cause pain. + */ + public static native void free(long ptr); + + /** + * Get a direct ByteBuffer mapped to the memory pointed to by the pointer. + * This method calls through to the JNA NewDirectByteBuffer method. + * + * @param addr base address of the JNA-originated memory + * @param length Length of ByteBuffer + * @return a direct ByteBuffer that accesses the memory being pointed to, + */ + public static native ByteBuffer getDirectByteBuffer(long addr, long length); + + /** Indicate the desired attachment state for the current thread. + This method should only be called from a callback context, and then + only just prior to returning to native code. Executing Java or native + code after the invocation of this method may interfere with the + intended detach state.

+ Note: errno/SetLastError is used to signal the desired state; this is + a hack to make use of built-in thread-local storage to avoid having to + re-implement it on certain platforms.

+ Warning: avoid calling {@link #detach detach(true)} on threads + spawned by the JVM; the resulting behavior is not defined.

+ */ + public static void detach(boolean detach) { + setLastError(detach ? THREAD_DETACH : THREAD_LEAVE_ATTACHED); + } + + private static class Buffers { + static boolean isBuffer(Class cls) { + return Buffer.class.isAssignableFrom(cls); + } + } + + /** Provides separation of JAWT functionality for the sake of J2ME + * ports which do not include AWT support. + */ + private static class AWT { + static long getWindowID(Window w) throws HeadlessException { + return getComponentID(w); + } + // Declaring the argument as Object rather than Component avoids class not + // found errors on phoneME foundation profile. + static long getComponentID(Object o) throws HeadlessException { + if (GraphicsEnvironment.isHeadless()) { + throw new HeadlessException("No native windows when headless"); + } + Component c = (Component)o; + if (c.isLightweight()) { + throw new IllegalArgumentException("Component must be heavyweight"); + } + if (!c.isDisplayable()) + throw new IllegalStateException("Component must be displayable"); + // On X11 VMs prior to 1.5, the window must be visible + if (Platform.isX11() + && System.getProperty("java.version").startsWith("1.4")) { + if (!c.isVisible()) { + throw new IllegalStateException("Component must be visible"); + } + } + // By this point, we're certain that Toolkit.loadLibraries() has + // been called, thus avoiding AWT/JAWT link errors + // (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6539705). + return Native.getWindowHandle0(c); + } + } +}