Embed pywin32, new version of package control broke the plugin
35
Pywin32/.gitignore
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
*.py[co]
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Packages
|
||||
*.egg
|
||||
*.egg-info
|
||||
dist
|
||||
build
|
||||
eggs
|
||||
parts
|
||||
bin
|
||||
var
|
||||
sdist
|
||||
develop-eggs
|
||||
.installed.cfg
|
||||
lib64
|
||||
__pycache__
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
.coverage
|
||||
.tox
|
||||
nosetests.xml
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
|
||||
# Mr Developer
|
||||
.mr.developer.cfg
|
||||
.project
|
||||
.pydevproject
|
||||
1
Pywin32/.no-sublime-package
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
30
Pywin32/License.txt
Normal file
@@ -0,0 +1,30 @@
|
||||
Unless stated in the specfic source file, this work is
|
||||
Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither names of Greg Stein, Mark Hammond nor the name of contributors may be used
|
||||
to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
|
||||
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
23
Pywin32/README.md
Normal file
@@ -0,0 +1,23 @@
|
||||
Pywin32
|
||||
=======
|
||||
|
||||
Pywin32 support for sublime (win32api etc)
|
||||
|
||||
Still evaluating what needs to be included and what doesn't, so if it is missing something important, please let me know.
|
||||
|
||||
# Using Pywin32
|
||||
Pywin32 modules should be accessible as soon as Sublime loads up the Pywin32 plugin...but since there is no guarunteed way to ensure all plugins are loaded after Pywin32 gets loaded, you should include `Pywin32.setup` before including any pywin32 modules. You can include it once in the top most level file, and all subsequent includes from that file should be guarunteed access. It does not have to be included in all files that call pywin32 modules, just once in the top level file that is the entry point. If I could guaruntee pywin32 to get loaded before all plugins, then even this requriement would not be necessary.
|
||||
|
||||
Example (show url path of all open explorer windows):
|
||||
|
||||
```python
|
||||
import Pywin32.setup
|
||||
from win32com.client.gencache import EnsureDispatch
|
||||
|
||||
|
||||
def run():
|
||||
for w in EnsureDispatch("Shell.Application").Windows():
|
||||
print(w.LocationName + "=" + w.LocationURL)
|
||||
|
||||
run()
|
||||
```
|
||||
3
Pywin32/lib/x32/pythoncom.py
Normal file
@@ -0,0 +1,3 @@
|
||||
# Magic utility that "redirects" to pythoncomxx.dll
|
||||
import pywintypes
|
||||
pywintypes.__import_pywin32_system_module__("pythoncom", globals())
|
||||
BIN
Pywin32/lib/x32/win32/_win32sysloader.pyd
Normal file
BIN
Pywin32/lib/x32/win32/_winxptheme.pyd
Normal file
934
Pywin32/lib/x32/win32/include/PyWinTypes.h
Normal file
@@ -0,0 +1,934 @@
|
||||
|
||||
#ifndef __PYWINTYPES_H__
|
||||
#define __PYWINTYPES_H__
|
||||
|
||||
// If building under a GCC, tweak what we need.
|
||||
#if defined(__GNUC__) && defined(_POSIX_C_SOURCE)
|
||||
// python.h complains if _POSIX_C_SOURCE is already defined
|
||||
# undef _POSIX_C_SOURCE
|
||||
#endif
|
||||
|
||||
// early msvc versions complain about pragma #s it doesn't understand
|
||||
// C:\mssdk\VC\INCLUDE\string.h(142) : warning C4616: #pragma warning : warning number '6059' out of range, must be between '4001' and '4999'
|
||||
// and:
|
||||
// C:\mssdk\include\wingdi.h(4340) : warning C4068: unknown pragma
|
||||
// I doubt we ever care about that warning, so unconditionally nuke em!
|
||||
#pragma warning( disable:4616 4068 )
|
||||
// Python.h and Windows.h both protect themselves from multiple
|
||||
// includes - so it is safe to do here (and provides a handy
|
||||
// choke point for #include vagaries
|
||||
|
||||
// Some other warnings generated by MSVC6 which we don't care about
|
||||
#if (PY_VERSION_HEX < 0x02060000)
|
||||
#pragma warning( disable:4035 )
|
||||
#endif
|
||||
|
||||
// windows rpc.h defines "small" as "char" which breaks Python's accu.h,
|
||||
// so we undefine it before including python.
|
||||
#ifdef small
|
||||
#undef small
|
||||
#endif
|
||||
|
||||
#include "Python.h"
|
||||
// many many files need python's structmember.h, and its possible people
|
||||
// #included windows.h before including us...
|
||||
#ifdef WRITE_RESTRICTED
|
||||
#undef WRITE_RESTRICTED
|
||||
#endif
|
||||
#include "structmember.h"
|
||||
// and python's structmember.h #defines this, conflicting with windows.h
|
||||
#ifdef WRITE_RESTRICTED
|
||||
#undef WRITE_RESTRICTED
|
||||
#endif
|
||||
#include "windows.h"
|
||||
#undef WRITE_RESTRICTED // stop anyone using the wrong one accidently...
|
||||
|
||||
// Python 2.3 doesn't have Py_CLEAR...
|
||||
#if (PY_VERSION_HEX < 0x02040000)
|
||||
#ifndef Py_CLEAR
|
||||
#define Py_CLEAR(op) \
|
||||
do { \
|
||||
if (op) { \
|
||||
PyObject *_py_tmp = (PyObject *)(op); \
|
||||
(op) = NULL; \
|
||||
Py_DECREF(_py_tmp); \
|
||||
} \
|
||||
} while (0)
|
||||
#endif
|
||||
// or Py_RETURN_NONE
|
||||
#ifndef Py_RETURN_NONE
|
||||
/* Macro for returning Py_None from a function */
|
||||
#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
|
||||
#endif
|
||||
|
||||
#endif // (PY_VERSION_HEX < 0x02040000)
|
||||
|
||||
|
||||
// Helpers for our modules.
|
||||
// Some macros to help the pywin32 modules co-exist in py2x and py3k.
|
||||
// Creates and initializes local variables called 'module' and 'dict'.
|
||||
|
||||
#if (PY_VERSION_HEX < 0x03000000)
|
||||
|
||||
// Use to define the function itself (ie, its name, linkage, params)
|
||||
#define PYWIN_MODULE_INIT_FUNC(module_name) \
|
||||
extern "C" __declspec(dllexport) void init##module_name(void)
|
||||
|
||||
// If the module needs to early-exit on an error condition.
|
||||
#define PYWIN_MODULE_INIT_RETURN_ERROR return;
|
||||
|
||||
// When the module has successfully initialized.
|
||||
#define PYWIN_MODULE_INIT_RETURN_SUCCESS return;
|
||||
|
||||
// To setup the module object itself and the module's dictionary.
|
||||
#define PYWIN_MODULE_INIT_PREPARE(module_name, functions, docstring) \
|
||||
PyObject *dict, *module; \
|
||||
if (PyWinGlobals_Ensure()==-1) \
|
||||
return; \
|
||||
if (!(module = Py_InitModule(#module_name, functions))) \
|
||||
return; \
|
||||
if (!(dict = PyModule_GetDict(module))) \
|
||||
return;
|
||||
|
||||
#else
|
||||
// py3k module helpers.
|
||||
// Use to define the function itself (ie, its name, linkage, params)
|
||||
#define PYWIN_MODULE_INIT_FUNC(module_name) \
|
||||
extern "C" __declspec(dllexport) PyObject *PyInit_##module_name(void)
|
||||
|
||||
// If the module needs to early-exit on an error condition.
|
||||
#define PYWIN_MODULE_INIT_RETURN_ERROR return NULL;
|
||||
|
||||
// When the module has successfully initialized.
|
||||
#define PYWIN_MODULE_INIT_RETURN_SUCCESS return module;
|
||||
|
||||
// To setup the module object itself and the module's dictionary.
|
||||
#define PYWIN_MODULE_INIT_PREPARE(module_name, functions, docstring) \
|
||||
PyObject *dict, *module; \
|
||||
static PyModuleDef module_name##_def = { \
|
||||
PyModuleDef_HEAD_INIT, \
|
||||
#module_name, \
|
||||
docstring , \
|
||||
-1, \
|
||||
functions }; \
|
||||
if (PyWinGlobals_Ensure()==-1) \
|
||||
return NULL; \
|
||||
if (!(module = PyModule_Create(&module_name##_def))) \
|
||||
return NULL; \
|
||||
if (!(dict = PyModule_GetDict(module))) \
|
||||
return NULL;
|
||||
#endif // PY_VERSION_HEX
|
||||
|
||||
|
||||
// Helpers for our types.
|
||||
#if (PY_VERSION_HEX < 0x03000000)
|
||||
#define PYWIN_OBJECT_HEAD PyObject_HEAD_INIT(&PyType_Type) 0,
|
||||
#define PYWIN_ATTR_CONVERT PyString_AsString
|
||||
|
||||
#else // Py3k definitions
|
||||
// Macro to handle PyObject layout changes in Py3k
|
||||
#define PYWIN_OBJECT_HEAD PyVarObject_HEAD_INIT(NULL, 0)
|
||||
|
||||
/* Attribute names are passed as Unicode in Py3k, so use a macro to
|
||||
switch between string and unicode conversion. This function is not
|
||||
documented, but is used extensively in the Python codebase itself,
|
||||
so it's reasonable to assume it won't disappear anytime soon.
|
||||
*/
|
||||
#define PYWIN_ATTR_CONVERT _PyUnicode_AsString
|
||||
|
||||
/* Some API functions changed/removed in python 3.0
|
||||
Definitions for the string functions are in stringobject.h,
|
||||
but comments indicate that this header is likely to go away in 3.1.
|
||||
*/
|
||||
#define PyString_Check PyBytes_Check
|
||||
#define PyString_Size PyBytes_Size
|
||||
#define PyString_AsString PyBytes_AsString
|
||||
#define PyString_AsStringAndSize PyBytes_AsStringAndSize
|
||||
#define PyString_FromString PyBytes_FromString
|
||||
#define PyString_FromStringAndSize PyBytes_FromStringAndSize
|
||||
#define _PyString_Resize _PyBytes_Resize
|
||||
#define PyString_AS_STRING PyBytes_AS_STRING
|
||||
#define PyString_GET_SIZE PyBytes_GET_SIZE
|
||||
#define PyString_Concat PyBytes_Concat
|
||||
#define PyInt_Check PyLong_Check
|
||||
#define PyInt_FromLong PyLong_FromLong
|
||||
#define PyInt_AsLong PyLong_AsLong
|
||||
#define PyInt_AS_LONG PyLong_AS_LONG
|
||||
#define PyInt_FromSsize_t PyLong_FromSsize_t
|
||||
#define PyInt_AsSsize_t PyLong_AsSsize_t
|
||||
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
|
||||
#define PyNumber_Int PyNumber_Long
|
||||
#endif // (PY_VERSION_HEX < 0x03000000)
|
||||
|
||||
// See PEP-353 - this is the "official" test...
|
||||
#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
|
||||
// 2.3 and before have no Py_ssize_t
|
||||
typedef int Py_ssize_t;
|
||||
#define PyInt_FromSsize_t PyInt_FromLong
|
||||
#define PyInt_AsSsize_t PyInt_AsLong
|
||||
#define PY_SSIZE_T_MAX INT_MAX
|
||||
#define PY_SSIZE_T_MIN INT_MIN
|
||||
#endif
|
||||
|
||||
// Py_hash_t was introduced as the size of a pointer in python 3.2 - it
|
||||
// was a simple long before that.
|
||||
#if PY_VERSION_HEX < 0x03020000
|
||||
typedef long Py_hash_t;
|
||||
#else
|
||||
typedef Py_ssize_t Py_hash_t;
|
||||
#endif
|
||||
|
||||
#if PY_VERSION_HEX < 0x02030000
|
||||
#define PyLong_AsUnsignedLongMask PyLong_AsUnsignedLong
|
||||
#endif
|
||||
|
||||
// This only enables runtime checks in debug builds - so we use
|
||||
// our own so we can enable it always should we desire...
|
||||
#define PyWin_SAFE_DOWNCAST Py_SAFE_DOWNCAST
|
||||
|
||||
// Lars: for WAVEFORMATEX
|
||||
#include "mmsystem.h"
|
||||
|
||||
|
||||
// *** NOTE *** FREEZE_PYWINTYPES is deprecated. It used to be used
|
||||
// by the 'freeze' tool, but now py2exe etc do a far better job, and
|
||||
// don't require a custom built pywintypes DLL.
|
||||
#ifdef FREEZE_PYWINTYPES
|
||||
/* The pywintypes module is being included in a frozen .EXE/.DLL */
|
||||
# define PYWINTYPES_EXPORT
|
||||
#else
|
||||
# ifdef BUILD_PYWINTYPES
|
||||
/* We are building pywintypesxx.dll */
|
||||
# define PYWINTYPES_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
/* This module uses pywintypesxx.dll */
|
||||
# define PYWINTYPES_EXPORT __declspec(dllimport)
|
||||
# if defined(_MSC_VER)
|
||||
# if defined(DEBUG) || defined(_DEBUG)
|
||||
# pragma comment(lib,"pywintypes_d.lib")
|
||||
# else
|
||||
# pragma comment(lib,"pywintypes.lib")
|
||||
# endif // DEBUG/_DEBUG
|
||||
# endif // _MSC_VER
|
||||
# endif // BUILD_PYWINTYPES
|
||||
#endif // FREEZE_PYWINTYPES
|
||||
|
||||
#if (PY_VERSION_HEX >= 0x03000000)
|
||||
// Py3k uses memoryview object in place of buffer
|
||||
extern PYWINTYPES_EXPORT PyObject *PyBuffer_New(Py_ssize_t size);
|
||||
extern PYWINTYPES_EXPORT PyObject *PyBuffer_FromMemory(void *buf, Py_ssize_t size);
|
||||
#endif
|
||||
|
||||
// Formats a python traceback into a character string - result must be free()ed
|
||||
PYWINTYPES_EXPORT char *GetPythonTraceback(PyObject *exc_type, PyObject *exc_value, PyObject *exc_tb);
|
||||
|
||||
#include <tchar.h>
|
||||
/*
|
||||
** Error/Exception handling
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyObject *PyWinExc_ApiError;
|
||||
// Register a Windows DLL that contains the messages in the specified range.
|
||||
extern PYWINTYPES_EXPORT BOOL PyWin_RegisterErrorMessageModule(DWORD first, DWORD last, HINSTANCE hmod);
|
||||
// Get the previously registered hmodule for an error code.
|
||||
extern PYWINTYPES_EXPORT HINSTANCE PyWin_GetErrorMessageModule(DWORD err);
|
||||
|
||||
|
||||
/* A global function that sets an API style error (ie, (code, fn, errTest)) */
|
||||
PYWINTYPES_EXPORT PyObject *PyWin_SetAPIError(char *fnName, long err = 0);
|
||||
|
||||
/* Basic COM Exception handling. The main COM exception object
|
||||
is actually defined here. However, the most useful functions
|
||||
for raising the exception are still in the COM package. Therefore,
|
||||
you can use the fn below to raise a basic COM exception - no fancy error
|
||||
messages available, just the HRESULT. It will, however, _be_ a COM
|
||||
exception, and therefore trappable like any other COM exception
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyObject *PyWinExc_COMError;
|
||||
PYWINTYPES_EXPORT PyObject *PyWin_SetBasicCOMError(HRESULT hr);
|
||||
|
||||
// Given a PyObject (string, Unicode, etc) create a "BSTR" with the value
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsBstr(PyObject *stringObject, BSTR *pResult, BOOL bNoneOK = FALSE, DWORD *pResultLen = NULL);
|
||||
// And free it when finished.
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeBstr(BSTR pResult);
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromBstr(const BSTR bstr, BOOL takeOwnership=FALSE);
|
||||
|
||||
// Given a string or Unicode object, get WCHAR characters.
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsWCHAR(PyObject *stringObject, WCHAR **pResult, BOOL bNoneOK = FALSE, DWORD *pResultLen = NULL);
|
||||
// And free it when finished.
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeWCHAR(WCHAR *pResult);
|
||||
|
||||
// As of Python 2.6, Python switched to 'wchar_t' for unicode, so old
|
||||
// win32 structures that still use 'unsigned short' now fail from C++ with
|
||||
// VS8 so we provide a couple of helpers.
|
||||
// XXX - but, when trying to use VC2003 with x64, the SDK x64 compiler
|
||||
// reports itself as 14.00.40310.41 - so this breaks under that compiler
|
||||
// Its not clear how to resolve this, but while VS2003 is the default
|
||||
// compiler, that is what must work.
|
||||
// py2.5 on x64 also needs it, and that is min x64 we support
|
||||
// The main difference seems to be whether the compiler has /Zc:wchar_t (Treat wchar_t as a builtin type)
|
||||
// on by default, and according to MSDN, _NATIVE_WCHAR_T_DEFINED is the way to check for it
|
||||
#ifdef _NATIVE_WCHAR_T_DEFINED
|
||||
inline BOOL PyWinObject_AsWCHAR(PyObject *stringObject, unsigned short **pResult, BOOL bNoneOK = FALSE, DWORD *pResultLen = NULL)
|
||||
{
|
||||
return PyWinObject_AsWCHAR(stringObject, (WCHAR **)pResult, bNoneOK, pResultLen);
|
||||
}
|
||||
inline void PyWinObject_FreeWCHAR(unsigned short *pResult)
|
||||
{
|
||||
PyWinObject_FreeWCHAR((WCHAR *)pResult);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Given a PyObject (string, Unicode, etc) create a "char *" with the value
|
||||
// if pResultLen != NULL, it will be set to the result size NOT INCLUDING
|
||||
// TERMINATOR (to be in line with SysStringLen, PyString_*, etc)
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsString(PyObject *stringObject, char **pResult, BOOL bNoneOK = FALSE, DWORD *pResultLen = NULL);
|
||||
// And free it when finished.
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeString(char *pResult);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeString(WCHAR *pResult);
|
||||
|
||||
// Automatically freed WCHAR that can be used anywhere WCHAR * is required
|
||||
class TmpWCHAR
|
||||
{
|
||||
public:
|
||||
WCHAR *tmp;
|
||||
TmpWCHAR() { tmp=NULL; }
|
||||
TmpWCHAR(WCHAR *t) { tmp=t; }
|
||||
WCHAR * operator= (WCHAR *t){
|
||||
PyWinObject_FreeWCHAR(tmp);
|
||||
tmp=t;
|
||||
return t;
|
||||
}
|
||||
WCHAR ** operator& () {return &tmp;}
|
||||
boolean operator== (WCHAR *t) { return tmp==t; }
|
||||
operator WCHAR *() { return tmp; }
|
||||
~TmpWCHAR() { PyWinObject_FreeWCHAR(tmp); }
|
||||
};
|
||||
|
||||
|
||||
// Buffer functions that can be used in place of 's#' input format or PyString_AsStringAndSize
|
||||
// for 64-bit compatibility and API consistency
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsReadBuffer(PyObject *ob, void **buf, DWORD *buf_len, BOOL bNoneOk=FALSE);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsWriteBuffer(PyObject *ob, void **buf, DWORD *buf_len, BOOL bNoneOk=FALSE);
|
||||
|
||||
// For 64-bit python compatibility, convert sequence to tuple and check length fits in a DWORD
|
||||
PYWINTYPES_EXPORT PyObject *PyWinSequence_Tuple(PyObject *obseq, DWORD *len);
|
||||
|
||||
|
||||
// an 'int' version (but aren't 'int' and 'DWORD' the same size?
|
||||
// Maybe a signed-ness issue?
|
||||
inline BOOL PyWinObject_AsReadBuffer(PyObject *ob, void **buf, int *buf_len, BOOL bNoneOk=FALSE)
|
||||
{
|
||||
return PyWinObject_AsReadBuffer(ob, buf, (DWORD *)buf_len, bNoneOk);
|
||||
}
|
||||
|
||||
/* ANSI/Unicode Support */
|
||||
/* If UNICODE defined, will be a BSTR - otherwise a char *
|
||||
Either way - PyWinObject_FreeTCHAR() must be called
|
||||
*/
|
||||
|
||||
// Helpers with py3k in mind: the result object is always a "core string"
|
||||
// object; ie, a string in py2k and unicode in py3k. Mainly to be used for
|
||||
// objects that *must* be that type - tp_str slots, __dict__ items, etc. If
|
||||
// Python doesn't *insist* the result be this type, consider using a function
|
||||
// that always returns a unicode object (ie, most of the "PyWinObject_From*CHAR"
|
||||
// functions)
|
||||
PYWINTYPES_EXPORT PyObject *PyWinCoreString_FromString(const char *str, Py_ssize_t len=(Py_ssize_t)-1);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinCoreString_FromString(const WCHAR *str, Py_ssize_t len=(Py_ssize_t)-1);
|
||||
|
||||
#define PyWinObject_FromWCHAR PyWinObject_FromOLECHAR
|
||||
|
||||
// Converts a series of consecutive null terminated strings into a list
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromMultipleString(WCHAR *multistring);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromMultipleString(char *multistring);
|
||||
// Converts a sequence of str/unicode objects into a series of consecutive null-terminated
|
||||
// wide character strings with extra terminating null
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsMultipleString(PyObject *ob, WCHAR **pmultistring, BOOL bNoneOK=TRUE, DWORD *chars_returned=NULL);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeMultipleString(WCHAR *pmultistring);
|
||||
|
||||
// Converts a sequence of str/unicode objects into a series of consecutive character strings
|
||||
// terminated by double null
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsMultipleString(PyObject *ob, char **pmultistring, BOOL bNoneOK=TRUE, DWORD *chars_returned=NULL);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeMultipleString(char *pmultistring);
|
||||
|
||||
// Convert a sequence of strings to an array of WCHAR pointers
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeWCHARArray(LPWSTR *wchars, DWORD str_cnt);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsWCHARArray(PyObject *str_seq, LPWSTR **wchars, DWORD *str_cnt, BOOL bNoneOK = FALSE);
|
||||
|
||||
// Convert a sequence of string or unicode objects to an array of char *
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeCharArray(char **pchars, DWORD str_cnt);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsCharArray(PyObject *str_seq, char ***pchars, DWORD *str_cnt, BOOL bNoneOK = FALSE);
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromOLECHAR(const OLECHAR * str);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromOLECHAR(const OLECHAR * str, int numChars);
|
||||
|
||||
// String support for buffers allocated via a function of your choice.
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsPfnAllocatedWCHAR(PyObject *stringObject,
|
||||
void *(*pfnAllocator)(ULONG),
|
||||
WCHAR **ppResult,
|
||||
BOOL bNoneOK = FALSE,
|
||||
DWORD *pResultLen = NULL);
|
||||
|
||||
#ifdef UNICODE
|
||||
// XXX - "AsTCHAR" functions should all die - the type of the Python object
|
||||
// being returned should not depend on UNICODE or not.
|
||||
#define PyWinObject_AsTCHAR PyWinObject_AsWCHAR
|
||||
#define PyWinObject_FreeTCHAR PyWinObject_FreeWCHAR
|
||||
#define PyWinObject_FromTCHAR PyWinObject_FromOLECHAR
|
||||
#else /* not UNICODE */
|
||||
#define PyWinObject_AsTCHAR PyWinObject_AsString
|
||||
#define PyWinObject_FreeTCHAR PyWinObject_FreeString
|
||||
|
||||
// PyWinObject_FromTCHAR in a non-unicode build still depends on py3k or not:
|
||||
// py2x a string object is returned (no conversions). py3x a unicode object
|
||||
// is returned (ie, the string is decoded)
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromTCHAR(const char *str, Py_ssize_t len=(Py_ssize_t)-1);
|
||||
|
||||
#endif // UNICODE
|
||||
|
||||
// String support for buffers allocated via CoTaskMemAlloc and CoTaskMemFree
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsTaskAllocatedWCHAR(PyObject *stringObject, WCHAR **ppResult, BOOL bNoneOK = FALSE, DWORD *pResultLen = NULL);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeTaskAllocatedWCHAR(WCHAR * str);
|
||||
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeString(char *str);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeString(WCHAR *str);
|
||||
|
||||
// Copy null terminated string with same allocator as PyWinObject_AsWCHAR, etc
|
||||
PYWINTYPES_EXPORT WCHAR *PyWin_CopyString(const WCHAR *input);
|
||||
PYWINTYPES_EXPORT char *PyWin_CopyString(const char *input);
|
||||
|
||||
|
||||
// Pointers.
|
||||
// Substitute for Python's inconsistent PyLong_AsVoidPtr
|
||||
PYWINTYPES_EXPORT BOOL PyWinLong_AsVoidPtr(PyObject *ob, void **pptr);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinLong_FromVoidPtr(const void *ptr);
|
||||
|
||||
/*
|
||||
** LARGE_INTEGER objects
|
||||
*/
|
||||
//AsLARGE_INTEGER takes either int or long
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsLARGE_INTEGER(PyObject *ob, LARGE_INTEGER *pResult);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsULARGE_INTEGER(PyObject *ob, ULARGE_INTEGER *pResult);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromLARGE_INTEGER(LARGE_INTEGER &val);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromULARGE_INTEGER(ULARGE_INTEGER &val);
|
||||
// Helpers that take a Py_LONG_LONG, but (a) have pywin32 consistent signatures
|
||||
// and (b) handle int *and* long (where Python only starts doing that in the
|
||||
// PyLong_* APIs post 2.4)
|
||||
// We also happen to know a LARGE_INTEGER is an __int64, so do it the easy way
|
||||
#define PyWinObject_AsPY_LONG_LONG(ob, pResult) PyWinObject_AsLARGE_INTEGER((ob), (LARGE_INTEGER *)(pResult))
|
||||
#define PyWinObject_AsUPY_LONG_LONG(ob, pResult) PyWinObject_AsULARGE_INTEGER((ob), (ULARGE_INTEGER *)(pResult))
|
||||
#define PyWinObject_FromPY_LONG_LONG(val) PyWinObject_FromLARGE_INTEGER((LARGE_INTEGER)val)
|
||||
#define PyWinObject_FromUPY_LONG_LONG(val) PyWinObject_FromULARGE_INTEGER((ULARGE_INTEGER)val)
|
||||
|
||||
// A DWORD_PTR and ULONG_PTR appear to mean "integer long enough to hold a pointer"
|
||||
// It is *not* actually a pointer (but is the same size as a pointer)
|
||||
inline PyObject *PyWinObject_FromULONG_PTR(ULONG_PTR v) {
|
||||
return PyWinLong_FromVoidPtr((void *)v);
|
||||
}
|
||||
inline BOOL PyWinLong_AsULONG_PTR(PyObject *ob, ULONG_PTR *r) {
|
||||
return PyWinLong_AsVoidPtr(ob, (void **)r);
|
||||
}
|
||||
|
||||
inline PyObject *PyWinObject_FromDWORD_PTR(DWORD_PTR v) {
|
||||
return PyLong_FromVoidPtr((void *)v);
|
||||
}
|
||||
inline BOOL PyWinLong_AsDWORD_PTR(PyObject *ob, DWORD_PTR *r) {
|
||||
return PyWinLong_AsVoidPtr(ob, (void **)r);
|
||||
}
|
||||
|
||||
// Some boolean helpers for Python 2.2 and earlier
|
||||
#if (PY_VERSION_HEX < 0x02030000 && !defined(PYWIN_NO_BOOL_FROM_LONG))
|
||||
// PyBool_FromLong only in 2.3 and later
|
||||
inline PyObject *PyBool_FromLong(long v)
|
||||
{
|
||||
PyObject *ret= v ? Py_True : Py_False;
|
||||
Py_INCREF(ret);
|
||||
return ret;
|
||||
}
|
||||
#endif
|
||||
|
||||
/*
|
||||
** OVERLAPPED Object and API
|
||||
*/
|
||||
class PyOVERLAPPED; // forward declare
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyOVERLAPPEDType; // the Type for PyOVERLAPPED
|
||||
#define PyOVERLAPPED_Check(ob) ((ob)->ob_type == &PyOVERLAPPEDType)
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsOVERLAPPED(PyObject *ob, OVERLAPPED **ppOverlapped, BOOL bNoneOK = TRUE);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsPyOVERLAPPED(PyObject *ob, PyOVERLAPPED **ppOverlapped, BOOL bNoneOK = TRUE);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromOVERLAPPED(const OVERLAPPED *pOverlapped);
|
||||
|
||||
// A global function that can work as a module method for making an OVERLAPPED object.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewOVERLAPPED(PyObject *self, PyObject *args);
|
||||
|
||||
#ifndef NO_PYWINTYPES_IID
|
||||
/*
|
||||
** IID/GUID support
|
||||
*/
|
||||
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyIIDType; // the Type for PyIID
|
||||
#define PyIID_Check(ob) ((ob)->ob_type == &PyIIDType)
|
||||
|
||||
// Given an object repring a CLSID (either PyIID or string), fill the CLSID.
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsIID(PyObject *obCLSID, CLSID *clsid);
|
||||
|
||||
// return a native PyIID object representing an IID
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromIID(const IID &riid);
|
||||
|
||||
// return a string/Unicode object representing an IID
|
||||
PYWINTYPES_EXPORT PyObject *PyWinCoreString_FromIID(const IID &riid);
|
||||
|
||||
// A global function that can work as a module method for making an IID object.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewIID( PyObject *self, PyObject *args);
|
||||
#endif /*NO_PYWINTYPES_IID */
|
||||
|
||||
/*
|
||||
** TIME support
|
||||
*/
|
||||
// The NO_PYWINTYPES_TIME define was initially used for CE builds. We now
|
||||
// use that symbol to mean "do we include our old, crap, custom time object?"
|
||||
// If not defined, we exclusively support datetime objects via the C API.
|
||||
// (Note py2.3 doesn't have a C API, so will not currently build with
|
||||
// NO_PYWINTYPES_TIME defined.)
|
||||
// TODO: If both builtin and datetime objects are enabled, we will enable
|
||||
// some transitional period using something like
|
||||
// pywintypes.__future_datatime__, but for now this is defined purely at build
|
||||
// time.
|
||||
#if (PY_VERSION_HEX >= 0x03000000)
|
||||
# define NO_PYWINTYPES_TIME
|
||||
#endif
|
||||
|
||||
// Python 2.3 doesn't have C Api for datetime, so can't have our new funky
|
||||
// support.
|
||||
#if (PY_VERSION_HEX >= 0x02040000)
|
||||
# define PYWIN_HAVE_DATETIME_CAPI
|
||||
#endif
|
||||
|
||||
// XXX - fixme - ack - we don't yet like *both* defines existing - and for now
|
||||
// its only enabled in py3k
|
||||
#if (PY_VERSION_HEX < 0x03000000)
|
||||
# undef PYWIN_HAVE_DATETIME_CAPI
|
||||
#endif
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromSYSTEMTIME(const SYSTEMTIME &t);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromFILETIME(const FILETIME &t);
|
||||
|
||||
// Converts a TimeStamp, which is in 100 nanosecond units like a FILETIME
|
||||
// TimeStamp is actually defined as a LARGE_INTEGER, so this function will also
|
||||
// accept Windows security "TimeStamp" objects directly - however, we use a
|
||||
// LARGE_INTEGER prototype to avoid pulling in the windows security headers.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromTimeStamp(const LARGE_INTEGER &t);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinTimeObject_Fromtime_t(time_t t);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromDATE(DATE t);
|
||||
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsDATE(PyObject *ob, DATE *pDate);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsFILETIME(PyObject *ob, FILETIME *pDate);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsSYSTEMTIME(PyObject *ob, SYSTEMTIME *pDate);
|
||||
|
||||
// A global function that can work as a module method for making a time object.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewTime( PyObject *self, PyObject *args);
|
||||
|
||||
PYWINTYPES_EXPORT BOOL PyWinTime_Check(PyObject *ob);
|
||||
|
||||
|
||||
#ifndef NO_PYWINTYPES_TIME
|
||||
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyTimeType; // the Type for PyTime
|
||||
#define PyWinTime_CHECK(ob) ((ob)->ob_type == &PyTimeType)
|
||||
|
||||
#endif // NO_PYWINTYPES_TIME
|
||||
|
||||
// functions to return WIN32_FIND_DATA tuples, used in shell, win32api, and win32file
|
||||
PYWINTYPES_EXPORT PyObject *PyObject_FromWIN32_FIND_DATAA(WIN32_FIND_DATAA *pData);
|
||||
PYWINTYPES_EXPORT PyObject *PyObject_FromWIN32_FIND_DATAW(WIN32_FIND_DATAW *pData);
|
||||
#ifdef UNICODE
|
||||
#define PyObject_FromWIN32_FIND_DATA PyObject_FromWIN32_FIND_DATAW
|
||||
#else
|
||||
#define PyObject_FromWIN32_FIND_DATA PyObject_FromWIN32_FIND_DATAA
|
||||
#endif
|
||||
|
||||
// POINT tuple, used in win32api_display.cpp and win32gui.i
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsPOINT(PyObject *obpoint, LPPOINT ppoint);
|
||||
|
||||
// IO_COUNTERS dict, used in win32process and win32job
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromIO_COUNTERS(PIO_COUNTERS pioc);
|
||||
|
||||
// Make an array of DWORD's from a sequence of Python ints
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsDWORDArray(PyObject *obdwords, DWORD **pdwords, DWORD *item_cnt, BOOL bNoneOk=TRUE);
|
||||
|
||||
// Conversion for resource id/name and class atom
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsResourceIdA(PyObject *ob, char **presource_id, BOOL bNoneOK = FALSE);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsResourceIdW(PyObject *ob, WCHAR **presource_id, BOOL bNoneOK = FALSE);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeResourceId(char *resource_id);
|
||||
PYWINTYPES_EXPORT void PyWinObject_FreeResourceId(WCHAR *resource_id);
|
||||
#ifdef UNICODE
|
||||
#define PyWinObject_AsResourceId PyWinObject_AsResourceIdW
|
||||
#else
|
||||
#define PyWinObject_AsResourceId PyWinObject_AsResourceIdA
|
||||
#endif
|
||||
|
||||
// WPARAM and LPARAM conversion
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsPARAM(PyObject *ob, WPARAM *pparam);
|
||||
inline PyObject *PyWinObject_FromPARAM(WPARAM param) {
|
||||
return PyWinObject_FromULONG_PTR(param);
|
||||
}
|
||||
inline BOOL PyWinObject_AsPARAM(PyObject *ob, LPARAM *pparam) {
|
||||
return PyWinObject_AsPARAM(ob, (WPARAM *)pparam);
|
||||
}
|
||||
inline PyObject *PyWinObject_FromPARAM(LPARAM param) {
|
||||
return PyWinObject_FromULONG_PTR(param);
|
||||
}
|
||||
|
||||
|
||||
// RECT conversions
|
||||
// @object PyRECT|Tuple of 4 ints defining a rectangle: (left, top, right, bottom)
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsRECT(PyObject *obrect, LPRECT prect);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromRECT(LPRECT prect);
|
||||
|
||||
/*
|
||||
** SECURITY_ATTRIBUTES support
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PySECURITY_ATTRIBUTESType;
|
||||
#define PySECURITY_ATTRIBUTES_Check(ob) ((ob)->ob_type == &PySECURITY_ATTRIBUTESType)
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyDEVMODEAType;
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyDEVMODEWType;
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewSECURITY_ATTRIBUTES(PyObject *self, PyObject *args);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsSECURITY_ATTRIBUTES(PyObject *ob, SECURITY_ATTRIBUTES **ppSECURITY_ATTRIBUTES, BOOL bNoneOK = TRUE);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromSECURITY_ATTRIBUTES(const SECURITY_ATTRIBUTES &sa);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsDEVMODE(PyObject *ob, PDEVMODEA * ppDEVMODE, BOOL bNoneOK = TRUE);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsDEVMODE(PyObject *ob, PDEVMODEW * ppDEVMODE, BOOL bNoneOK);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromDEVMODE(PDEVMODEA);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromDEVMODE(PDEVMODEW);
|
||||
|
||||
/*
|
||||
** WAVEFORMATEX support
|
||||
*/
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewWAVEFORMATEX(PyObject *self, PyObject *args);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromWAVEFROMATEX(const WAVEFORMATEX &wfx);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsWAVEFORMATEX(PyObject *ob, WAVEFORMATEX **ppWAVEFORMATEX, BOOL bNoneOK = TRUE);
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyWAVEFORMATEXType;
|
||||
#define PyWAVEFORMATEX_Check(ob) ((ob)->ob_type == &PyWAVEFORMATEXType)
|
||||
|
||||
|
||||
/*
|
||||
** SECURITY_DESCRIPTOR support
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PySECURITY_DESCRIPTORType;
|
||||
#define PySECURITY_DESCRIPTOR_Check(ob) ((ob)->ob_type == &PySECURITY_DESCRIPTORType)
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewSECURITY_DESCRIPTOR(PyObject *self, PyObject *args);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsSECURITY_DESCRIPTOR(PyObject *ob, PSECURITY_DESCRIPTOR *ppSECURITY_DESCRIPTOR, BOOL bNoneOK = TRUE);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromSECURITY_DESCRIPTOR(PSECURITY_DESCRIPTOR psd);
|
||||
|
||||
PYWINTYPES_EXPORT BOOL _MakeAbsoluteSD(PSECURITY_DESCRIPTOR psd_relative, PSECURITY_DESCRIPTOR *ppsd_absolute);
|
||||
PYWINTYPES_EXPORT void FreeAbsoluteSD(PSECURITY_DESCRIPTOR psd);
|
||||
|
||||
/*
|
||||
** SID support
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PySIDType;
|
||||
#define PySID_Check(ob) ((ob)->ob_type == &PySIDType)
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewSID(PyObject *self, PyObject *args);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsSID(PyObject *ob, PSID *ppSID, BOOL bNoneOK = FALSE);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromSID(PSID pSID);
|
||||
|
||||
/*
|
||||
** ACL support
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyACLType;
|
||||
#define PyACL_Check(ob) ((ob)->ob_type == &PyACLType)
|
||||
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewACL(PyObject *self, PyObject *args);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsACL(PyObject *ob, PACL *ppACL, BOOL bNoneOK = FALSE);
|
||||
|
||||
/*
|
||||
** Win32 HANDLE wrapper - any handle closable by "CloseHandle()"
|
||||
*/
|
||||
extern PYWINTYPES_EXPORT PyTypeObject PyHANDLEType; // the Type for PyHANDLE
|
||||
#define PyHANDLE_Check(ob) ((ob)->ob_type == &PyHANDLEType)
|
||||
|
||||
// Convert an object to a HANDLE - None is always OK, as are ints, etc.
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsHANDLE(PyObject *ob, HANDLE *pRes);
|
||||
// For handles that use PyHANDLE.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromHANDLE(HANDLE h);
|
||||
// For handles that aren't returned as PyHANDLE or a subclass thereof (HDC, HWND, etc).
|
||||
// Return as python ints or longs
|
||||
PYWINTYPES_EXPORT PyObject *PyWinLong_FromHANDLE(HANDLE h);
|
||||
|
||||
// A global function that can work as a module method for making a HANDLE object.
|
||||
PYWINTYPES_EXPORT PyObject *PyWinMethod_NewHANDLE( PyObject *self, PyObject *args);
|
||||
|
||||
// A global function that does the right thing wrt closing a "handle".
|
||||
// The object can be either a PyHANDLE or an integer.
|
||||
// If result is FALSE, a Python error is all setup (cf PyHANDLE::Close(), which doesnt set the Python error)
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_CloseHANDLE(PyObject *obHandle);
|
||||
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsHKEY(PyObject *ob, HKEY *pRes);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromHKEY(HKEY h);
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_CloseHKEY(PyObject *obHandle);
|
||||
|
||||
// MSG structure keeps coming up...
|
||||
PYWINTYPES_EXPORT BOOL PyWinObject_AsMSG(PyObject *ob, MSG *pMsg);
|
||||
PYWINTYPES_EXPORT PyObject *PyWinObject_FromMSG(const MSG *pMsg);
|
||||
|
||||
#include "winsock.h"
|
||||
/*
|
||||
** SOCKET support.
|
||||
*/
|
||||
PYWINTYPES_EXPORT
|
||||
BOOL PySocket_AsSOCKET
|
||||
//-------------------------------------------------------------------------
|
||||
// Helper function for dealing with socket arguments.
|
||||
(
|
||||
PyObject *obSocket,
|
||||
// [in] Python object being converted into a SOCKET handle.
|
||||
SOCKET *ps
|
||||
// [out] Returned socket handle
|
||||
);
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** Other Utilities
|
||||
*/
|
||||
// ----------------------------------------------------------------------
|
||||
// WARNING - NEVER EVER USE new() ON THIS CLASS
|
||||
// This class can be used as a local variable, typically in a Python/C
|
||||
// function, and can be passed whereever a TCHAR/WCHAR is expected.
|
||||
// Typical Usage:
|
||||
// PyWin_AutoFreeBstr arg;
|
||||
// PyArg_ParseTuple("O", &obStr);
|
||||
// PyWinObject_AsAutoFreeBstr(obStr, &arg);
|
||||
// CallTheFunction(arg); // Will correctly pass BSTR/OLECHAR
|
||||
// -- when the function goes out of scope, the string owned by "arg" will
|
||||
// -- automatically be freed.
|
||||
// ----------------------------------------------------------------------
|
||||
class PYWINTYPES_EXPORT PyWin_AutoFreeBstr {
|
||||
public:
|
||||
PyWin_AutoFreeBstr( BSTR bstr = NULL );
|
||||
~PyWin_AutoFreeBstr();
|
||||
void SetBstr( BSTR bstr );
|
||||
operator BSTR() {return m_bstr;}
|
||||
private:
|
||||
BSTR m_bstr;
|
||||
};
|
||||
|
||||
inline BOOL PyWinObject_AsAutoFreeBstr(PyObject *stringObject, PyWin_AutoFreeBstr *pResult, BOOL bNoneOK = FALSE)
|
||||
{
|
||||
if (bNoneOK && stringObject == Py_None) {
|
||||
pResult->SetBstr(NULL);
|
||||
return TRUE;
|
||||
}
|
||||
BSTR bs;
|
||||
if (!PyWinObject_AsBstr(stringObject, &bs, bNoneOK))
|
||||
return FALSE;
|
||||
pResult->SetBstr(bs);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// THREAD MANAGEMENT
|
||||
//
|
||||
|
||||
// ### need to rename the PYCOM_ stuff soon...
|
||||
|
||||
// We have 2 discrete locks in use (when no free-threaded is used, anyway).
|
||||
// The first type of lock is the global Python lock. This is the standard lock
|
||||
// in use by Python, and must be used as documented by Python. Specifically, no
|
||||
// 2 threads may _ever_ call _any_ Python code (including INCREF/DECREF) without
|
||||
// first having this thread lock.
|
||||
//
|
||||
// The second type of lock is a "global framework lock". This lock is simply a
|
||||
// critical section, and used whenever 2 threads of C code need access to global
|
||||
// data. This is different than the Python lock - this lock is used when no Python
|
||||
// code can ever be called by the threads, but the C code still needs thread-safety.
|
||||
|
||||
// We also supply helper classes which make the usage of these locks a one-liner.
|
||||
|
||||
// The "framework" lock, implemented as a critical section.
|
||||
PYWINTYPES_EXPORT void PyWin_AcquireGlobalLock(void);
|
||||
PYWINTYPES_EXPORT void PyWin_ReleaseGlobalLock(void);
|
||||
|
||||
// Helper class for the DLL global lock.
|
||||
//
|
||||
// This class magically waits for the Win32/COM framework global lock, and releases it
|
||||
// when finished.
|
||||
// NEVER new one of these objects - only use on the stack!
|
||||
class CEnterLeaveFramework {
|
||||
public:
|
||||
CEnterLeaveFramework() {PyWin_AcquireGlobalLock();}
|
||||
~CEnterLeaveFramework() {PyWin_ReleaseGlobalLock();}
|
||||
};
|
||||
|
||||
// Python thread-lock stuff. Free-threading patches use different semantics, but
|
||||
// these are abstracted away here...
|
||||
#ifndef FORCE_NO_FREE_THREAD
|
||||
# ifdef WITH_FREE_THREAD
|
||||
# define PYCOM_USE_FREE_THREAD
|
||||
# endif
|
||||
#endif
|
||||
#ifdef PYCOM_USE_FREE_THREAD
|
||||
# include <threadstate.h>
|
||||
#else
|
||||
# include <pystate.h>
|
||||
#endif
|
||||
|
||||
|
||||
// Helper class for Enter/Leave Python
|
||||
//
|
||||
// This class magically waits for the Python global lock, and releases it
|
||||
// when finished.
|
||||
|
||||
// Nested invocations will deadlock, so be careful.
|
||||
|
||||
// NEVER new one of these objects - only use on the stack!
|
||||
#ifndef PYCOM_USE_FREE_THREAD
|
||||
extern PYWINTYPES_EXPORT PyInterpreterState *PyWin_InterpreterState;
|
||||
extern PYWINTYPES_EXPORT BOOL PyWinThreadState_Ensure();
|
||||
extern PYWINTYPES_EXPORT void PyWinThreadState_Free();
|
||||
extern PYWINTYPES_EXPORT void PyWinThreadState_Clear();
|
||||
extern PYWINTYPES_EXPORT void PyWinInterpreterLock_Acquire();
|
||||
extern PYWINTYPES_EXPORT void PyWinInterpreterLock_Release();
|
||||
|
||||
extern PYWINTYPES_EXPORT int PyWinGlobals_Ensure();
|
||||
extern PYWINTYPES_EXPORT void PyWinGlobals_Free();
|
||||
#else
|
||||
#define PyWinThreadState_Ensure PyThreadState_Ensure
|
||||
#define PyWinThreadState_Free PyThreadState_Free
|
||||
#define PyWinThreadState_Clear PyThreadState_ClearExc
|
||||
|
||||
#endif
|
||||
|
||||
extern PYWINTYPES_EXPORT void PyWin_MakePendingCalls();
|
||||
|
||||
// For 2.3, use the PyGILState_ calls
|
||||
#if (PY_VERSION_HEX >= 0x02030000)
|
||||
#define PYWIN_USE_GILSTATE
|
||||
#endif
|
||||
|
||||
#ifndef PYWIN_USE_GILSTATE
|
||||
|
||||
class CEnterLeavePython {
|
||||
public:
|
||||
CEnterLeavePython() {
|
||||
acquired = FALSE;
|
||||
acquire();
|
||||
}
|
||||
void acquire() {
|
||||
if (acquired)
|
||||
return;
|
||||
created = PyWinThreadState_Ensure();
|
||||
#ifndef PYCOM_USE_FREE_THREAD
|
||||
PyWinInterpreterLock_Acquire();
|
||||
#endif
|
||||
if (created) {
|
||||
// If pending python calls are waiting as we enter Python,
|
||||
// it will generally mean an asynch signal handler, etc.
|
||||
// We can either call it here, or wait for Python to call it
|
||||
// as part of its "every 'n' opcodes" check. If we wait for
|
||||
// Python to check it and the pending call raises an exception,
|
||||
// then it is _our_ code that will fail - this is unfair,
|
||||
// as the signal was raised before we were entered - indeed,
|
||||
// we may be directly responding to the signal!
|
||||
// Thus, we flush all the pending calls here, and report any
|
||||
// exceptions via our normal exception reporting mechanism.
|
||||
// (of which we don't have, but not to worry... :)
|
||||
// We can then execute our code in the knowledge that only
|
||||
// signals raised _while_ we are executing will cause exceptions.
|
||||
PyWin_MakePendingCalls();
|
||||
}
|
||||
acquired = TRUE;
|
||||
}
|
||||
~CEnterLeavePython() {
|
||||
if (acquired)
|
||||
release();
|
||||
}
|
||||
void release() {
|
||||
// The interpreter state must be cleared
|
||||
// _before_ we release the lock, as some of
|
||||
// the sys. attributes cleared (eg, the current exception)
|
||||
// may need the lock to invoke their destructors -
|
||||
// specifically, when exc_value is a class instance, and
|
||||
// the exception holds the last reference!
|
||||
if ( !acquired )
|
||||
return;
|
||||
if ( created )
|
||||
PyWinThreadState_Clear();
|
||||
#ifndef PYCOM_USE_FREE_THREAD
|
||||
PyWinInterpreterLock_Release();
|
||||
#endif
|
||||
if ( created )
|
||||
PyWinThreadState_Free();
|
||||
acquired = FALSE;
|
||||
}
|
||||
private:
|
||||
BOOL created;
|
||||
BOOL acquired;
|
||||
};
|
||||
|
||||
#else // PYWIN_USE_GILSTATE
|
||||
|
||||
class CEnterLeavePython {
|
||||
public:
|
||||
CEnterLeavePython() {
|
||||
acquire();
|
||||
}
|
||||
void acquire(void) {
|
||||
state = PyGILState_Ensure();
|
||||
released = FALSE;
|
||||
}
|
||||
~CEnterLeavePython() {
|
||||
release();
|
||||
}
|
||||
void release(void) {
|
||||
if (!released) {
|
||||
PyGILState_Release(state);
|
||||
released = TRUE;
|
||||
}
|
||||
}
|
||||
private:
|
||||
PyGILState_STATE state;
|
||||
BOOL released;
|
||||
};
|
||||
#endif // PYWIN_USE_GILSTATE
|
||||
|
||||
// A helper for simple exception handling.
|
||||
// try/__try
|
||||
#ifdef MAINWIN
|
||||
#define PYWINTYPES_TRY try
|
||||
#else
|
||||
#define PYWINTYPES_TRY __try
|
||||
#endif /* MAINWIN */
|
||||
|
||||
// catch/__except
|
||||
#if defined(__MINGW32__) || defined(MAINWIN)
|
||||
#define PYWINTYPES_EXCEPT catch(...)
|
||||
#else
|
||||
#define PYWINTYPES_EXCEPT __except( EXCEPTION_EXECUTE_HANDLER )
|
||||
#endif
|
||||
// End of exception helper macros.
|
||||
|
||||
// Class to hold a temporary reference that decrements itself
|
||||
class TmpPyObject
|
||||
{
|
||||
public:
|
||||
PyObject *tmp;
|
||||
TmpPyObject() { tmp=NULL; }
|
||||
TmpPyObject(PyObject *ob) { tmp=ob; }
|
||||
PyObject * operator= (PyObject *ob){
|
||||
Py_XDECREF(tmp);
|
||||
tmp=ob;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
boolean operator== (PyObject *ob) { return tmp==ob; }
|
||||
operator PyObject *() { return tmp; }
|
||||
~TmpPyObject() { Py_XDECREF(tmp); }
|
||||
};
|
||||
|
||||
#endif // __PYWINTYPES_H__
|
||||
|
||||
|
||||
497
Pywin32/lib/x32/win32/lib/afxres.py
Normal file
@@ -0,0 +1,497 @@
|
||||
# Generated by h2py from stdin
|
||||
TCS_MULTILINE = 0x0200
|
||||
CBRS_ALIGN_LEFT = 0x1000
|
||||
CBRS_ALIGN_TOP = 0x2000
|
||||
CBRS_ALIGN_RIGHT = 0x4000
|
||||
CBRS_ALIGN_BOTTOM = 0x8000
|
||||
CBRS_ALIGN_ANY = 0xF000
|
||||
CBRS_BORDER_LEFT = 0x0100
|
||||
CBRS_BORDER_TOP = 0x0200
|
||||
CBRS_BORDER_RIGHT = 0x0400
|
||||
CBRS_BORDER_BOTTOM = 0x0800
|
||||
CBRS_BORDER_ANY = 0x0F00
|
||||
CBRS_TOOLTIPS = 0x0010
|
||||
CBRS_FLYBY = 0x0020
|
||||
CBRS_FLOAT_MULTI = 0x0040
|
||||
CBRS_BORDER_3D = 0x0080
|
||||
CBRS_HIDE_INPLACE = 0x0008
|
||||
CBRS_SIZE_DYNAMIC = 0x0004
|
||||
CBRS_SIZE_FIXED = 0x0002
|
||||
CBRS_FLOATING = 0x0001
|
||||
CBRS_GRIPPER = 0x00400000
|
||||
CBRS_ORIENT_HORZ = (CBRS_ALIGN_TOP|CBRS_ALIGN_BOTTOM)
|
||||
CBRS_ORIENT_VERT = (CBRS_ALIGN_LEFT|CBRS_ALIGN_RIGHT)
|
||||
CBRS_ORIENT_ANY = (CBRS_ORIENT_HORZ|CBRS_ORIENT_VERT)
|
||||
CBRS_ALL = 0xFFFF
|
||||
CBRS_NOALIGN = 0x00000000
|
||||
CBRS_LEFT = (CBRS_ALIGN_LEFT|CBRS_BORDER_RIGHT)
|
||||
CBRS_TOP = (CBRS_ALIGN_TOP|CBRS_BORDER_BOTTOM)
|
||||
CBRS_RIGHT = (CBRS_ALIGN_RIGHT|CBRS_BORDER_LEFT)
|
||||
CBRS_BOTTOM = (CBRS_ALIGN_BOTTOM|CBRS_BORDER_TOP)
|
||||
SBPS_NORMAL = 0x0000
|
||||
SBPS_NOBORDERS = 0x0100
|
||||
SBPS_POPOUT = 0x0200
|
||||
SBPS_OWNERDRAW = 0x1000
|
||||
SBPS_DISABLED = 0x04000000
|
||||
SBPS_STRETCH = 0x08000000
|
||||
ID_INDICATOR_EXT = 0xE700
|
||||
ID_INDICATOR_CAPS = 0xE701
|
||||
ID_INDICATOR_NUM = 0xE702
|
||||
ID_INDICATOR_SCRL = 0xE703
|
||||
ID_INDICATOR_OVR = 0xE704
|
||||
ID_INDICATOR_REC = 0xE705
|
||||
ID_INDICATOR_KANA = 0xE706
|
||||
ID_SEPARATOR = 0
|
||||
AFX_IDW_CONTROLBAR_FIRST = 0xE800
|
||||
AFX_IDW_CONTROLBAR_LAST = 0xE8FF
|
||||
AFX_IDW_TOOLBAR = 0xE800
|
||||
AFX_IDW_STATUS_BAR = 0xE801
|
||||
AFX_IDW_PREVIEW_BAR = 0xE802
|
||||
AFX_IDW_RESIZE_BAR = 0xE803
|
||||
AFX_IDW_DOCKBAR_TOP = 0xE81B
|
||||
AFX_IDW_DOCKBAR_LEFT = 0xE81C
|
||||
AFX_IDW_DOCKBAR_RIGHT = 0xE81D
|
||||
AFX_IDW_DOCKBAR_BOTTOM = 0xE81E
|
||||
AFX_IDW_DOCKBAR_FLOAT = 0xE81F
|
||||
def AFX_CONTROLBAR_MASK(nIDC): return (1 << (nIDC - AFX_IDW_CONTROLBAR_FIRST))
|
||||
|
||||
AFX_IDW_PANE_FIRST = 0xE900
|
||||
AFX_IDW_PANE_LAST = 0xE9ff
|
||||
AFX_IDW_HSCROLL_FIRST = 0xEA00
|
||||
AFX_IDW_VSCROLL_FIRST = 0xEA10
|
||||
AFX_IDW_SIZE_BOX = 0xEA20
|
||||
AFX_IDW_PANE_SAVE = 0xEA21
|
||||
AFX_IDS_APP_TITLE = 0xE000
|
||||
AFX_IDS_IDLEMESSAGE = 0xE001
|
||||
AFX_IDS_HELPMODEMESSAGE = 0xE002
|
||||
AFX_IDS_APP_TITLE_EMBEDDING = 0xE003
|
||||
AFX_IDS_COMPANY_NAME = 0xE004
|
||||
AFX_IDS_OBJ_TITLE_INPLACE = 0xE005
|
||||
ID_FILE_NEW = 0xE100
|
||||
ID_FILE_OPEN = 0xE101
|
||||
ID_FILE_CLOSE = 0xE102
|
||||
ID_FILE_SAVE = 0xE103
|
||||
ID_FILE_SAVE_AS = 0xE104
|
||||
ID_FILE_PAGE_SETUP = 0xE105
|
||||
ID_FILE_PRINT_SETUP = 0xE106
|
||||
ID_FILE_PRINT = 0xE107
|
||||
ID_FILE_PRINT_DIRECT = 0xE108
|
||||
ID_FILE_PRINT_PREVIEW = 0xE109
|
||||
ID_FILE_UPDATE = 0xE10A
|
||||
ID_FILE_SAVE_COPY_AS = 0xE10B
|
||||
ID_FILE_SEND_MAIL = 0xE10C
|
||||
ID_FILE_MRU_FIRST = 0xE110
|
||||
ID_FILE_MRU_FILE1 = 0xE110
|
||||
ID_FILE_MRU_FILE2 = 0xE111
|
||||
ID_FILE_MRU_FILE3 = 0xE112
|
||||
ID_FILE_MRU_FILE4 = 0xE113
|
||||
ID_FILE_MRU_FILE5 = 0xE114
|
||||
ID_FILE_MRU_FILE6 = 0xE115
|
||||
ID_FILE_MRU_FILE7 = 0xE116
|
||||
ID_FILE_MRU_FILE8 = 0xE117
|
||||
ID_FILE_MRU_FILE9 = 0xE118
|
||||
ID_FILE_MRU_FILE10 = 0xE119
|
||||
ID_FILE_MRU_FILE11 = 0xE11A
|
||||
ID_FILE_MRU_FILE12 = 0xE11B
|
||||
ID_FILE_MRU_FILE13 = 0xE11C
|
||||
ID_FILE_MRU_FILE14 = 0xE11D
|
||||
ID_FILE_MRU_FILE15 = 0xE11E
|
||||
ID_FILE_MRU_FILE16 = 0xE11F
|
||||
ID_FILE_MRU_LAST = 0xE11F
|
||||
ID_EDIT_CLEAR = 0xE120
|
||||
ID_EDIT_CLEAR_ALL = 0xE121
|
||||
ID_EDIT_COPY = 0xE122
|
||||
ID_EDIT_CUT = 0xE123
|
||||
ID_EDIT_FIND = 0xE124
|
||||
ID_EDIT_PASTE = 0xE125
|
||||
ID_EDIT_PASTE_LINK = 0xE126
|
||||
ID_EDIT_PASTE_SPECIAL = 0xE127
|
||||
ID_EDIT_REPEAT = 0xE128
|
||||
ID_EDIT_REPLACE = 0xE129
|
||||
ID_EDIT_SELECT_ALL = 0xE12A
|
||||
ID_EDIT_UNDO = 0xE12B
|
||||
ID_EDIT_REDO = 0xE12C
|
||||
ID_WINDOW_NEW = 0xE130
|
||||
ID_WINDOW_ARRANGE = 0xE131
|
||||
ID_WINDOW_CASCADE = 0xE132
|
||||
ID_WINDOW_TILE_HORZ = 0xE133
|
||||
ID_WINDOW_TILE_VERT = 0xE134
|
||||
ID_WINDOW_SPLIT = 0xE135
|
||||
AFX_IDM_WINDOW_FIRST = 0xE130
|
||||
AFX_IDM_WINDOW_LAST = 0xE13F
|
||||
AFX_IDM_FIRST_MDICHILD = 0xFF00
|
||||
ID_APP_ABOUT = 0xE140
|
||||
ID_APP_EXIT = 0xE141
|
||||
ID_HELP_INDEX = 0xE142
|
||||
ID_HELP_FINDER = 0xE143
|
||||
ID_HELP_USING = 0xE144
|
||||
ID_CONTEXT_HELP = 0xE145
|
||||
ID_HELP = 0xE146
|
||||
ID_DEFAULT_HELP = 0xE147
|
||||
ID_NEXT_PANE = 0xE150
|
||||
ID_PREV_PANE = 0xE151
|
||||
ID_FORMAT_FONT = 0xE160
|
||||
ID_OLE_INSERT_NEW = 0xE200
|
||||
ID_OLE_EDIT_LINKS = 0xE201
|
||||
ID_OLE_EDIT_CONVERT = 0xE202
|
||||
ID_OLE_EDIT_CHANGE_ICON = 0xE203
|
||||
ID_OLE_EDIT_PROPERTIES = 0xE204
|
||||
ID_OLE_VERB_FIRST = 0xE210
|
||||
ID_OLE_VERB_LAST = 0xE21F
|
||||
AFX_ID_PREVIEW_CLOSE = 0xE300
|
||||
AFX_ID_PREVIEW_NUMPAGE = 0xE301
|
||||
AFX_ID_PREVIEW_NEXT = 0xE302
|
||||
AFX_ID_PREVIEW_PREV = 0xE303
|
||||
AFX_ID_PREVIEW_PRINT = 0xE304
|
||||
AFX_ID_PREVIEW_ZOOMIN = 0xE305
|
||||
AFX_ID_PREVIEW_ZOOMOUT = 0xE306
|
||||
ID_VIEW_TOOLBAR = 0xE800
|
||||
ID_VIEW_STATUS_BAR = 0xE801
|
||||
ID_RECORD_FIRST = 0xE900
|
||||
ID_RECORD_LAST = 0xE901
|
||||
ID_RECORD_NEXT = 0xE902
|
||||
ID_RECORD_PREV = 0xE903
|
||||
IDC_STATIC = (-1)
|
||||
AFX_IDS_SCFIRST = 0xEF00
|
||||
AFX_IDS_SCSIZE = 0xEF00
|
||||
AFX_IDS_SCMOVE = 0xEF01
|
||||
AFX_IDS_SCMINIMIZE = 0xEF02
|
||||
AFX_IDS_SCMAXIMIZE = 0xEF03
|
||||
AFX_IDS_SCNEXTWINDOW = 0xEF04
|
||||
AFX_IDS_SCPREVWINDOW = 0xEF05
|
||||
AFX_IDS_SCCLOSE = 0xEF06
|
||||
AFX_IDS_SCRESTORE = 0xEF12
|
||||
AFX_IDS_SCTASKLIST = 0xEF13
|
||||
AFX_IDS_MDICHILD = 0xEF1F
|
||||
AFX_IDS_DESKACCESSORY = 0xEFDA
|
||||
AFX_IDS_OPENFILE = 0xF000
|
||||
AFX_IDS_SAVEFILE = 0xF001
|
||||
AFX_IDS_ALLFILTER = 0xF002
|
||||
AFX_IDS_UNTITLED = 0xF003
|
||||
AFX_IDS_SAVEFILECOPY = 0xF004
|
||||
AFX_IDS_PREVIEW_CLOSE = 0xF005
|
||||
AFX_IDS_UNNAMED_FILE = 0xF006
|
||||
AFX_IDS_ABOUT = 0xF010
|
||||
AFX_IDS_HIDE = 0xF011
|
||||
AFX_IDP_NO_ERROR_AVAILABLE = 0xF020
|
||||
AFX_IDS_NOT_SUPPORTED_EXCEPTION = 0xF021
|
||||
AFX_IDS_RESOURCE_EXCEPTION = 0xF022
|
||||
AFX_IDS_MEMORY_EXCEPTION = 0xF023
|
||||
AFX_IDS_USER_EXCEPTION = 0xF024
|
||||
AFX_IDS_PRINTONPORT = 0xF040
|
||||
AFX_IDS_ONEPAGE = 0xF041
|
||||
AFX_IDS_TWOPAGE = 0xF042
|
||||
AFX_IDS_PRINTPAGENUM = 0xF043
|
||||
AFX_IDS_PREVIEWPAGEDESC = 0xF044
|
||||
AFX_IDS_PRINTDEFAULTEXT = 0xF045
|
||||
AFX_IDS_PRINTDEFAULT = 0xF046
|
||||
AFX_IDS_PRINTFILTER = 0xF047
|
||||
AFX_IDS_PRINTCAPTION = 0xF048
|
||||
AFX_IDS_PRINTTOFILE = 0xF049
|
||||
AFX_IDS_OBJECT_MENUITEM = 0xF080
|
||||
AFX_IDS_EDIT_VERB = 0xF081
|
||||
AFX_IDS_ACTIVATE_VERB = 0xF082
|
||||
AFX_IDS_CHANGE_LINK = 0xF083
|
||||
AFX_IDS_AUTO = 0xF084
|
||||
AFX_IDS_MANUAL = 0xF085
|
||||
AFX_IDS_FROZEN = 0xF086
|
||||
AFX_IDS_ALL_FILES = 0xF087
|
||||
AFX_IDS_SAVE_MENU = 0xF088
|
||||
AFX_IDS_UPDATE_MENU = 0xF089
|
||||
AFX_IDS_SAVE_AS_MENU = 0xF08A
|
||||
AFX_IDS_SAVE_COPY_AS_MENU = 0xF08B
|
||||
AFX_IDS_EXIT_MENU = 0xF08C
|
||||
AFX_IDS_UPDATING_ITEMS = 0xF08D
|
||||
AFX_IDS_METAFILE_FORMAT = 0xF08E
|
||||
AFX_IDS_DIB_FORMAT = 0xF08F
|
||||
AFX_IDS_BITMAP_FORMAT = 0xF090
|
||||
AFX_IDS_LINKSOURCE_FORMAT = 0xF091
|
||||
AFX_IDS_EMBED_FORMAT = 0xF092
|
||||
AFX_IDS_PASTELINKEDTYPE = 0xF094
|
||||
AFX_IDS_UNKNOWNTYPE = 0xF095
|
||||
AFX_IDS_RTF_FORMAT = 0xF096
|
||||
AFX_IDS_TEXT_FORMAT = 0xF097
|
||||
AFX_IDS_INVALID_CURRENCY = 0xF098
|
||||
AFX_IDS_INVALID_DATETIME = 0xF099
|
||||
AFX_IDS_INVALID_DATETIMESPAN = 0xF09A
|
||||
AFX_IDP_INVALID_FILENAME = 0xF100
|
||||
AFX_IDP_FAILED_TO_OPEN_DOC = 0xF101
|
||||
AFX_IDP_FAILED_TO_SAVE_DOC = 0xF102
|
||||
AFX_IDP_ASK_TO_SAVE = 0xF103
|
||||
AFX_IDP_FAILED_TO_CREATE_DOC = 0xF104
|
||||
AFX_IDP_FILE_TOO_LARGE = 0xF105
|
||||
AFX_IDP_FAILED_TO_START_PRINT = 0xF106
|
||||
AFX_IDP_FAILED_TO_LAUNCH_HELP = 0xF107
|
||||
AFX_IDP_INTERNAL_FAILURE = 0xF108
|
||||
AFX_IDP_COMMAND_FAILURE = 0xF109
|
||||
AFX_IDP_FAILED_MEMORY_ALLOC = 0xF10A
|
||||
AFX_IDP_PARSE_INT = 0xF110
|
||||
AFX_IDP_PARSE_REAL = 0xF111
|
||||
AFX_IDP_PARSE_INT_RANGE = 0xF112
|
||||
AFX_IDP_PARSE_REAL_RANGE = 0xF113
|
||||
AFX_IDP_PARSE_STRING_SIZE = 0xF114
|
||||
AFX_IDP_PARSE_RADIO_BUTTON = 0xF115
|
||||
AFX_IDP_PARSE_BYTE = 0xF116
|
||||
AFX_IDP_PARSE_UINT = 0xF117
|
||||
AFX_IDP_PARSE_DATETIME = 0xF118
|
||||
AFX_IDP_PARSE_CURRENCY = 0xF119
|
||||
AFX_IDP_FAILED_INVALID_FORMAT = 0xF120
|
||||
AFX_IDP_FAILED_INVALID_PATH = 0xF121
|
||||
AFX_IDP_FAILED_DISK_FULL = 0xF122
|
||||
AFX_IDP_FAILED_ACCESS_READ = 0xF123
|
||||
AFX_IDP_FAILED_ACCESS_WRITE = 0xF124
|
||||
AFX_IDP_FAILED_IO_ERROR_READ = 0xF125
|
||||
AFX_IDP_FAILED_IO_ERROR_WRITE = 0xF126
|
||||
AFX_IDP_STATIC_OBJECT = 0xF180
|
||||
AFX_IDP_FAILED_TO_CONNECT = 0xF181
|
||||
AFX_IDP_SERVER_BUSY = 0xF182
|
||||
AFX_IDP_BAD_VERB = 0xF183
|
||||
AFX_IDP_FAILED_TO_NOTIFY = 0xF185
|
||||
AFX_IDP_FAILED_TO_LAUNCH = 0xF186
|
||||
AFX_IDP_ASK_TO_UPDATE = 0xF187
|
||||
AFX_IDP_FAILED_TO_UPDATE = 0xF188
|
||||
AFX_IDP_FAILED_TO_REGISTER = 0xF189
|
||||
AFX_IDP_FAILED_TO_AUTO_REGISTER = 0xF18A
|
||||
AFX_IDP_FAILED_TO_CONVERT = 0xF18B
|
||||
AFX_IDP_GET_NOT_SUPPORTED = 0xF18C
|
||||
AFX_IDP_SET_NOT_SUPPORTED = 0xF18D
|
||||
AFX_IDP_ASK_TO_DISCARD = 0xF18E
|
||||
AFX_IDP_FAILED_TO_CREATE = 0xF18F
|
||||
AFX_IDP_FAILED_MAPI_LOAD = 0xF190
|
||||
AFX_IDP_INVALID_MAPI_DLL = 0xF191
|
||||
AFX_IDP_FAILED_MAPI_SEND = 0xF192
|
||||
AFX_IDP_FILE_NONE = 0xF1A0
|
||||
AFX_IDP_FILE_GENERIC = 0xF1A1
|
||||
AFX_IDP_FILE_NOT_FOUND = 0xF1A2
|
||||
AFX_IDP_FILE_BAD_PATH = 0xF1A3
|
||||
AFX_IDP_FILE_TOO_MANY_OPEN = 0xF1A4
|
||||
AFX_IDP_FILE_ACCESS_DENIED = 0xF1A5
|
||||
AFX_IDP_FILE_INVALID_FILE = 0xF1A6
|
||||
AFX_IDP_FILE_REMOVE_CURRENT = 0xF1A7
|
||||
AFX_IDP_FILE_DIR_FULL = 0xF1A8
|
||||
AFX_IDP_FILE_BAD_SEEK = 0xF1A9
|
||||
AFX_IDP_FILE_HARD_IO = 0xF1AA
|
||||
AFX_IDP_FILE_SHARING = 0xF1AB
|
||||
AFX_IDP_FILE_LOCKING = 0xF1AC
|
||||
AFX_IDP_FILE_DISKFULL = 0xF1AD
|
||||
AFX_IDP_FILE_EOF = 0xF1AE
|
||||
AFX_IDP_ARCH_NONE = 0xF1B0
|
||||
AFX_IDP_ARCH_GENERIC = 0xF1B1
|
||||
AFX_IDP_ARCH_READONLY = 0xF1B2
|
||||
AFX_IDP_ARCH_ENDOFFILE = 0xF1B3
|
||||
AFX_IDP_ARCH_WRITEONLY = 0xF1B4
|
||||
AFX_IDP_ARCH_BADINDEX = 0xF1B5
|
||||
AFX_IDP_ARCH_BADCLASS = 0xF1B6
|
||||
AFX_IDP_ARCH_BADSCHEMA = 0xF1B7
|
||||
AFX_IDS_OCC_SCALEUNITS_PIXELS = 0xF1C0
|
||||
AFX_IDS_STATUS_FONT = 0xF230
|
||||
AFX_IDS_TOOLTIP_FONT = 0xF231
|
||||
AFX_IDS_UNICODE_FONT = 0xF232
|
||||
AFX_IDS_MINI_FONT = 0xF233
|
||||
AFX_IDP_SQL_FIRST = 0xF280
|
||||
AFX_IDP_SQL_CONNECT_FAIL = 0xF281
|
||||
AFX_IDP_SQL_RECORDSET_FORWARD_ONLY = 0xF282
|
||||
AFX_IDP_SQL_EMPTY_COLUMN_LIST = 0xF283
|
||||
AFX_IDP_SQL_FIELD_SCHEMA_MISMATCH = 0xF284
|
||||
AFX_IDP_SQL_ILLEGAL_MODE = 0xF285
|
||||
AFX_IDP_SQL_MULTIPLE_ROWS_AFFECTED = 0xF286
|
||||
AFX_IDP_SQL_NO_CURRENT_RECORD = 0xF287
|
||||
AFX_IDP_SQL_NO_ROWS_AFFECTED = 0xF288
|
||||
AFX_IDP_SQL_RECORDSET_READONLY = 0xF289
|
||||
AFX_IDP_SQL_SQL_NO_TOTAL = 0xF28A
|
||||
AFX_IDP_SQL_ODBC_LOAD_FAILED = 0xF28B
|
||||
AFX_IDP_SQL_DYNASET_NOT_SUPPORTED = 0xF28C
|
||||
AFX_IDP_SQL_SNAPSHOT_NOT_SUPPORTED = 0xF28D
|
||||
AFX_IDP_SQL_API_CONFORMANCE = 0xF28E
|
||||
AFX_IDP_SQL_SQL_CONFORMANCE = 0xF28F
|
||||
AFX_IDP_SQL_NO_DATA_FOUND = 0xF290
|
||||
AFX_IDP_SQL_ROW_UPDATE_NOT_SUPPORTED = 0xF291
|
||||
AFX_IDP_SQL_ODBC_V2_REQUIRED = 0xF292
|
||||
AFX_IDP_SQL_NO_POSITIONED_UPDATES = 0xF293
|
||||
AFX_IDP_SQL_LOCK_MODE_NOT_SUPPORTED = 0xF294
|
||||
AFX_IDP_SQL_DATA_TRUNCATED = 0xF295
|
||||
AFX_IDP_SQL_ROW_FETCH = 0xF296
|
||||
AFX_IDP_SQL_INCORRECT_ODBC = 0xF297
|
||||
AFX_IDP_SQL_UPDATE_DELETE_FAILED = 0xF298
|
||||
AFX_IDP_SQL_DYNAMIC_CURSOR_NOT_SUPPORTED = 0xF299
|
||||
AFX_IDP_DAO_FIRST = 0xF2A0
|
||||
AFX_IDP_DAO_ENGINE_INITIALIZATION = 0xF2A0
|
||||
AFX_IDP_DAO_DFX_BIND = 0xF2A1
|
||||
AFX_IDP_DAO_OBJECT_NOT_OPEN = 0xF2A2
|
||||
AFX_IDP_DAO_ROWTOOSHORT = 0xF2A3
|
||||
AFX_IDP_DAO_BADBINDINFO = 0xF2A4
|
||||
AFX_IDP_DAO_COLUMNUNAVAILABLE = 0xF2A5
|
||||
AFX_IDC_LISTBOX = 100
|
||||
AFX_IDC_CHANGE = 101
|
||||
AFX_IDC_PRINT_DOCNAME = 201
|
||||
AFX_IDC_PRINT_PRINTERNAME = 202
|
||||
AFX_IDC_PRINT_PORTNAME = 203
|
||||
AFX_IDC_PRINT_PAGENUM = 204
|
||||
ID_APPLY_NOW = 0x3021
|
||||
ID_WIZBACK = 0x3023
|
||||
ID_WIZNEXT = 0x3024
|
||||
ID_WIZFINISH = 0x3025
|
||||
AFX_IDC_TAB_CONTROL = 0x3020
|
||||
AFX_IDD_FILEOPEN = 28676
|
||||
AFX_IDD_FILESAVE = 28677
|
||||
AFX_IDD_FONT = 28678
|
||||
AFX_IDD_COLOR = 28679
|
||||
AFX_IDD_PRINT = 28680
|
||||
AFX_IDD_PRINTSETUP = 28681
|
||||
AFX_IDD_FIND = 28682
|
||||
AFX_IDD_REPLACE = 28683
|
||||
AFX_IDD_NEWTYPEDLG = 30721
|
||||
AFX_IDD_PRINTDLG = 30722
|
||||
AFX_IDD_PREVIEW_TOOLBAR = 30723
|
||||
AFX_IDD_PREVIEW_SHORTTOOLBAR = 30731
|
||||
AFX_IDD_INSERTOBJECT = 30724
|
||||
AFX_IDD_CHANGEICON = 30725
|
||||
AFX_IDD_CONVERT = 30726
|
||||
AFX_IDD_PASTESPECIAL = 30727
|
||||
AFX_IDD_EDITLINKS = 30728
|
||||
AFX_IDD_FILEBROWSE = 30729
|
||||
AFX_IDD_BUSY = 30730
|
||||
AFX_IDD_OBJECTPROPERTIES = 30732
|
||||
AFX_IDD_CHANGESOURCE = 30733
|
||||
AFX_IDC_CONTEXTHELP = 30977
|
||||
AFX_IDC_MAGNIFY = 30978
|
||||
AFX_IDC_SMALLARROWS = 30979
|
||||
AFX_IDC_HSPLITBAR = 30980
|
||||
AFX_IDC_VSPLITBAR = 30981
|
||||
AFX_IDC_NODROPCRSR = 30982
|
||||
AFX_IDC_TRACKNWSE = 30983
|
||||
AFX_IDC_TRACKNESW = 30984
|
||||
AFX_IDC_TRACKNS = 30985
|
||||
AFX_IDC_TRACKWE = 30986
|
||||
AFX_IDC_TRACK4WAY = 30987
|
||||
AFX_IDC_MOVE4WAY = 30988
|
||||
AFX_IDB_MINIFRAME_MENU = 30994
|
||||
AFX_IDB_CHECKLISTBOX_NT = 30995
|
||||
AFX_IDB_CHECKLISTBOX_95 = 30996
|
||||
AFX_IDR_PREVIEW_ACCEL = 30997
|
||||
AFX_IDI_STD_MDIFRAME = 31233
|
||||
AFX_IDI_STD_FRAME = 31234
|
||||
AFX_IDC_FONTPROP = 1000
|
||||
AFX_IDC_FONTNAMES = 1001
|
||||
AFX_IDC_FONTSTYLES = 1002
|
||||
AFX_IDC_FONTSIZES = 1003
|
||||
AFX_IDC_STRIKEOUT = 1004
|
||||
AFX_IDC_UNDERLINE = 1005
|
||||
AFX_IDC_SAMPLEBOX = 1006
|
||||
AFX_IDC_COLOR_BLACK = 1100
|
||||
AFX_IDC_COLOR_WHITE = 1101
|
||||
AFX_IDC_COLOR_RED = 1102
|
||||
AFX_IDC_COLOR_GREEN = 1103
|
||||
AFX_IDC_COLOR_BLUE = 1104
|
||||
AFX_IDC_COLOR_YELLOW = 1105
|
||||
AFX_IDC_COLOR_MAGENTA = 1106
|
||||
AFX_IDC_COLOR_CYAN = 1107
|
||||
AFX_IDC_COLOR_GRAY = 1108
|
||||
AFX_IDC_COLOR_LIGHTGRAY = 1109
|
||||
AFX_IDC_COLOR_DARKRED = 1110
|
||||
AFX_IDC_COLOR_DARKGREEN = 1111
|
||||
AFX_IDC_COLOR_DARKBLUE = 1112
|
||||
AFX_IDC_COLOR_LIGHTBROWN = 1113
|
||||
AFX_IDC_COLOR_DARKMAGENTA = 1114
|
||||
AFX_IDC_COLOR_DARKCYAN = 1115
|
||||
AFX_IDC_COLORPROP = 1116
|
||||
AFX_IDC_SYSTEMCOLORS = 1117
|
||||
AFX_IDC_PROPNAME = 1201
|
||||
AFX_IDC_PICTURE = 1202
|
||||
AFX_IDC_BROWSE = 1203
|
||||
AFX_IDC_CLEAR = 1204
|
||||
AFX_IDD_PROPPAGE_COLOR = 32257
|
||||
AFX_IDD_PROPPAGE_FONT = 32258
|
||||
AFX_IDD_PROPPAGE_PICTURE = 32259
|
||||
AFX_IDB_TRUETYPE = 32384
|
||||
AFX_IDS_PROPPAGE_UNKNOWN = 0xFE01
|
||||
AFX_IDS_COLOR_DESKTOP = 0xFE04
|
||||
AFX_IDS_COLOR_APPWORKSPACE = 0xFE05
|
||||
AFX_IDS_COLOR_WNDBACKGND = 0xFE06
|
||||
AFX_IDS_COLOR_WNDTEXT = 0xFE07
|
||||
AFX_IDS_COLOR_MENUBAR = 0xFE08
|
||||
AFX_IDS_COLOR_MENUTEXT = 0xFE09
|
||||
AFX_IDS_COLOR_ACTIVEBAR = 0xFE0A
|
||||
AFX_IDS_COLOR_INACTIVEBAR = 0xFE0B
|
||||
AFX_IDS_COLOR_ACTIVETEXT = 0xFE0C
|
||||
AFX_IDS_COLOR_INACTIVETEXT = 0xFE0D
|
||||
AFX_IDS_COLOR_ACTIVEBORDER = 0xFE0E
|
||||
AFX_IDS_COLOR_INACTIVEBORDER = 0xFE0F
|
||||
AFX_IDS_COLOR_WNDFRAME = 0xFE10
|
||||
AFX_IDS_COLOR_SCROLLBARS = 0xFE11
|
||||
AFX_IDS_COLOR_BTNFACE = 0xFE12
|
||||
AFX_IDS_COLOR_BTNSHADOW = 0xFE13
|
||||
AFX_IDS_COLOR_BTNTEXT = 0xFE14
|
||||
AFX_IDS_COLOR_BTNHIGHLIGHT = 0xFE15
|
||||
AFX_IDS_COLOR_DISABLEDTEXT = 0xFE16
|
||||
AFX_IDS_COLOR_HIGHLIGHT = 0xFE17
|
||||
AFX_IDS_COLOR_HIGHLIGHTTEXT = 0xFE18
|
||||
AFX_IDS_REGULAR = 0xFE19
|
||||
AFX_IDS_BOLD = 0xFE1A
|
||||
AFX_IDS_ITALIC = 0xFE1B
|
||||
AFX_IDS_BOLDITALIC = 0xFE1C
|
||||
AFX_IDS_SAMPLETEXT = 0xFE1D
|
||||
AFX_IDS_DISPLAYSTRING_FONT = 0xFE1E
|
||||
AFX_IDS_DISPLAYSTRING_COLOR = 0xFE1F
|
||||
AFX_IDS_DISPLAYSTRING_PICTURE = 0xFE20
|
||||
AFX_IDS_PICTUREFILTER = 0xFE21
|
||||
AFX_IDS_PICTYPE_UNKNOWN = 0xFE22
|
||||
AFX_IDS_PICTYPE_NONE = 0xFE23
|
||||
AFX_IDS_PICTYPE_BITMAP = 0xFE24
|
||||
AFX_IDS_PICTYPE_METAFILE = 0xFE25
|
||||
AFX_IDS_PICTYPE_ICON = 0xFE26
|
||||
AFX_IDS_COLOR_PPG = 0xFE28
|
||||
AFX_IDS_COLOR_PPG_CAPTION = 0xFE29
|
||||
AFX_IDS_FONT_PPG = 0xFE2A
|
||||
AFX_IDS_FONT_PPG_CAPTION = 0xFE2B
|
||||
AFX_IDS_PICTURE_PPG = 0xFE2C
|
||||
AFX_IDS_PICTURE_PPG_CAPTION = 0xFE2D
|
||||
AFX_IDS_PICTUREBROWSETITLE = 0xFE30
|
||||
AFX_IDS_BORDERSTYLE_0 = 0xFE31
|
||||
AFX_IDS_BORDERSTYLE_1 = 0xFE32
|
||||
AFX_IDS_VERB_EDIT = 0xFE40
|
||||
AFX_IDS_VERB_PROPERTIES = 0xFE41
|
||||
AFX_IDP_PICTURECANTOPEN = 0xFE83
|
||||
AFX_IDP_PICTURECANTLOAD = 0xFE84
|
||||
AFX_IDP_PICTURETOOLARGE = 0xFE85
|
||||
AFX_IDP_PICTUREREADFAILED = 0xFE86
|
||||
AFX_IDP_E_ILLEGALFUNCTIONCALL = 0xFEA0
|
||||
AFX_IDP_E_OVERFLOW = 0xFEA1
|
||||
AFX_IDP_E_OUTOFMEMORY = 0xFEA2
|
||||
AFX_IDP_E_DIVISIONBYZERO = 0xFEA3
|
||||
AFX_IDP_E_OUTOFSTRINGSPACE = 0xFEA4
|
||||
AFX_IDP_E_OUTOFSTACKSPACE = 0xFEA5
|
||||
AFX_IDP_E_BADFILENAMEORNUMBER = 0xFEA6
|
||||
AFX_IDP_E_FILENOTFOUND = 0xFEA7
|
||||
AFX_IDP_E_BADFILEMODE = 0xFEA8
|
||||
AFX_IDP_E_FILEALREADYOPEN = 0xFEA9
|
||||
AFX_IDP_E_DEVICEIOERROR = 0xFEAA
|
||||
AFX_IDP_E_FILEALREADYEXISTS = 0xFEAB
|
||||
AFX_IDP_E_BADRECORDLENGTH = 0xFEAC
|
||||
AFX_IDP_E_DISKFULL = 0xFEAD
|
||||
AFX_IDP_E_BADRECORDNUMBER = 0xFEAE
|
||||
AFX_IDP_E_BADFILENAME = 0xFEAF
|
||||
AFX_IDP_E_TOOMANYFILES = 0xFEB0
|
||||
AFX_IDP_E_DEVICEUNAVAILABLE = 0xFEB1
|
||||
AFX_IDP_E_PERMISSIONDENIED = 0xFEB2
|
||||
AFX_IDP_E_DISKNOTREADY = 0xFEB3
|
||||
AFX_IDP_E_PATHFILEACCESSERROR = 0xFEB4
|
||||
AFX_IDP_E_PATHNOTFOUND = 0xFEB5
|
||||
AFX_IDP_E_INVALIDPATTERNSTRING = 0xFEB6
|
||||
AFX_IDP_E_INVALIDUSEOFNULL = 0xFEB7
|
||||
AFX_IDP_E_INVALIDFILEFORMAT = 0xFEB8
|
||||
AFX_IDP_E_INVALIDPROPERTYVALUE = 0xFEB9
|
||||
AFX_IDP_E_INVALIDPROPERTYARRAYINDEX = 0xFEBA
|
||||
AFX_IDP_E_SETNOTSUPPORTEDATRUNTIME = 0xFEBB
|
||||
AFX_IDP_E_SETNOTSUPPORTED = 0xFEBC
|
||||
AFX_IDP_E_NEEDPROPERTYARRAYINDEX = 0xFEBD
|
||||
AFX_IDP_E_SETNOTPERMITTED = 0xFEBE
|
||||
AFX_IDP_E_GETNOTSUPPORTEDATRUNTIME = 0xFEBF
|
||||
AFX_IDP_E_GETNOTSUPPORTED = 0xFEC0
|
||||
AFX_IDP_E_PROPERTYNOTFOUND = 0xFEC1
|
||||
AFX_IDP_E_INVALIDCLIPBOARDFORMAT = 0xFEC2
|
||||
AFX_IDP_E_INVALIDPICTURE = 0xFEC3
|
||||
AFX_IDP_E_PRINTERERROR = 0xFEC4
|
||||
AFX_IDP_E_CANTSAVEFILETOTEMP = 0xFEC5
|
||||
AFX_IDP_E_SEARCHTEXTNOTFOUND = 0xFEC6
|
||||
AFX_IDP_E_REPLACEMENTSTOOLONG = 0xFEC7
|
||||
1549
Pywin32/lib/x32/win32/lib/commctrl.py
Normal file
24
Pywin32/lib/x32/win32/lib/dbi.py
Normal file
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Skeleton replacement for removed dbi module.
|
||||
Use of objects created by this module should be replaced with native Python objects.
|
||||
Dates are now returned as datetime.datetime objects, but will still accept PyTime
|
||||
objects also.
|
||||
Raw data for binary fields should be passed as buffer objects for Python 2.x,
|
||||
and memoryview objects in Py3k.
|
||||
"""
|
||||
|
||||
import warnings
|
||||
warnings.warn(
|
||||
"dbi module is obsolete, code should now use native python datetime and buffer/memoryview objects",
|
||||
DeprecationWarning)
|
||||
|
||||
import datetime
|
||||
dbDate = dbiDate = datetime.datetime
|
||||
|
||||
try:
|
||||
dbRaw = dbiRaw = buffer
|
||||
except NameError:
|
||||
dbRaw = dbiRaw = memoryview
|
||||
|
||||
# type names are still exported by odbc module
|
||||
from odbc import *
|
||||
867
Pywin32/lib/x32/win32/lib/mmsystem.py
Normal file
@@ -0,0 +1,867 @@
|
||||
# Generated by h2py from d:/msdev/include/mmsystem.h
|
||||
MAXPNAMELEN = 32
|
||||
MAXERRORLENGTH = 256
|
||||
MAX_JOYSTICKOEMVXDNAME = 260
|
||||
MM_MICROSOFT = 1
|
||||
MM_MIDI_MAPPER = 1
|
||||
MM_WAVE_MAPPER = 2
|
||||
MM_SNDBLST_MIDIOUT = 3
|
||||
MM_SNDBLST_MIDIIN = 4
|
||||
MM_SNDBLST_SYNTH = 5
|
||||
MM_SNDBLST_WAVEOUT = 6
|
||||
MM_SNDBLST_WAVEIN = 7
|
||||
MM_ADLIB = 9
|
||||
MM_MPU401_MIDIOUT = 10
|
||||
MM_MPU401_MIDIIN = 11
|
||||
MM_PC_JOYSTICK = 12
|
||||
TIME_MS = 0x0001
|
||||
TIME_SAMPLES = 0x0002
|
||||
TIME_BYTES = 0x0004
|
||||
TIME_SMPTE = 0x0008
|
||||
TIME_MIDI = 0x0010
|
||||
TIME_TICKS = 0x0020
|
||||
MM_JOY1MOVE = 0x3A0
|
||||
MM_JOY2MOVE = 0x3A1
|
||||
MM_JOY1ZMOVE = 0x3A2
|
||||
MM_JOY2ZMOVE = 0x3A3
|
||||
MM_JOY1BUTTONDOWN = 0x3B5
|
||||
MM_JOY2BUTTONDOWN = 0x3B6
|
||||
MM_JOY1BUTTONUP = 0x3B7
|
||||
MM_JOY2BUTTONUP = 0x3B8
|
||||
MM_MCINOTIFY = 0x3B9
|
||||
MM_WOM_OPEN = 0x3BB
|
||||
MM_WOM_CLOSE = 0x3BC
|
||||
MM_WOM_DONE = 0x3BD
|
||||
MM_WIM_OPEN = 0x3BE
|
||||
MM_WIM_CLOSE = 0x3BF
|
||||
MM_WIM_DATA = 0x3C0
|
||||
MM_MIM_OPEN = 0x3C1
|
||||
MM_MIM_CLOSE = 0x3C2
|
||||
MM_MIM_DATA = 0x3C3
|
||||
MM_MIM_LONGDATA = 0x3C4
|
||||
MM_MIM_ERROR = 0x3C5
|
||||
MM_MIM_LONGERROR = 0x3C6
|
||||
MM_MOM_OPEN = 0x3C7
|
||||
MM_MOM_CLOSE = 0x3C8
|
||||
MM_MOM_DONE = 0x3C9
|
||||
MM_STREAM_OPEN = 0x3D4
|
||||
MM_STREAM_CLOSE = 0x3D5
|
||||
MM_STREAM_DONE = 0x3D6
|
||||
MM_STREAM_ERROR = 0x3D7
|
||||
MM_MOM_POSITIONCB = 0x3CA
|
||||
MM_MIM_MOREDATA = 0x3CC
|
||||
MM_MIXM_LINE_CHANGE = 0x3D0
|
||||
MM_MIXM_CONTROL_CHANGE = 0x3D1
|
||||
MMSYSERR_BASE = 0
|
||||
WAVERR_BASE = 32
|
||||
MIDIERR_BASE = 64
|
||||
TIMERR_BASE = 96
|
||||
JOYERR_BASE = 160
|
||||
MCIERR_BASE = 256
|
||||
MIXERR_BASE = 1024
|
||||
MCI_STRING_OFFSET = 512
|
||||
MCI_VD_OFFSET = 1024
|
||||
MCI_CD_OFFSET = 1088
|
||||
MCI_WAVE_OFFSET = 1152
|
||||
MCI_SEQ_OFFSET = 1216
|
||||
MMSYSERR_NOERROR = 0
|
||||
MMSYSERR_ERROR = (MMSYSERR_BASE + 1)
|
||||
MMSYSERR_BADDEVICEID = (MMSYSERR_BASE + 2)
|
||||
MMSYSERR_NOTENABLED = (MMSYSERR_BASE + 3)
|
||||
MMSYSERR_ALLOCATED = (MMSYSERR_BASE + 4)
|
||||
MMSYSERR_INVALHANDLE = (MMSYSERR_BASE + 5)
|
||||
MMSYSERR_NODRIVER = (MMSYSERR_BASE + 6)
|
||||
MMSYSERR_NOMEM = (MMSYSERR_BASE + 7)
|
||||
MMSYSERR_NOTSUPPORTED = (MMSYSERR_BASE + 8)
|
||||
MMSYSERR_BADERRNUM = (MMSYSERR_BASE + 9)
|
||||
MMSYSERR_INVALFLAG = (MMSYSERR_BASE + 10)
|
||||
MMSYSERR_INVALPARAM = (MMSYSERR_BASE + 11)
|
||||
MMSYSERR_HANDLEBUSY = (MMSYSERR_BASE + 12)
|
||||
MMSYSERR_INVALIDALIAS = (MMSYSERR_BASE + 13)
|
||||
MMSYSERR_BADDB = (MMSYSERR_BASE + 14)
|
||||
MMSYSERR_KEYNOTFOUND = (MMSYSERR_BASE + 15)
|
||||
MMSYSERR_READERROR = (MMSYSERR_BASE + 16)
|
||||
MMSYSERR_WRITEERROR = (MMSYSERR_BASE + 17)
|
||||
MMSYSERR_DELETEERROR = (MMSYSERR_BASE + 18)
|
||||
MMSYSERR_VALNOTFOUND = (MMSYSERR_BASE + 19)
|
||||
MMSYSERR_NODRIVERCB = (MMSYSERR_BASE + 20)
|
||||
MMSYSERR_LASTERROR = (MMSYSERR_BASE + 20)
|
||||
DRV_LOAD = 0x0001
|
||||
DRV_ENABLE = 0x0002
|
||||
DRV_OPEN = 0x0003
|
||||
DRV_CLOSE = 0x0004
|
||||
DRV_DISABLE = 0x0005
|
||||
DRV_FREE = 0x0006
|
||||
DRV_CONFIGURE = 0x0007
|
||||
DRV_QUERYCONFIGURE = 0x0008
|
||||
DRV_INSTALL = 0x0009
|
||||
DRV_REMOVE = 0x000A
|
||||
DRV_EXITSESSION = 0x000B
|
||||
DRV_POWER = 0x000F
|
||||
DRV_RESERVED = 0x0800
|
||||
DRV_USER = 0x4000
|
||||
DRVCNF_CANCEL = 0x0000
|
||||
DRVCNF_OK = 0x0001
|
||||
DRVCNF_RESTART = 0x0002
|
||||
DRV_CANCEL = DRVCNF_CANCEL
|
||||
DRV_OK = DRVCNF_OK
|
||||
DRV_RESTART = DRVCNF_RESTART
|
||||
DRV_MCI_FIRST = DRV_RESERVED
|
||||
DRV_MCI_LAST = (DRV_RESERVED + 0xFFF)
|
||||
CALLBACK_TYPEMASK = 0x00070000
|
||||
CALLBACK_NULL = 0x00000000
|
||||
CALLBACK_WINDOW = 0x00010000
|
||||
CALLBACK_TASK = 0x00020000
|
||||
CALLBACK_FUNCTION = 0x00030000
|
||||
CALLBACK_THREAD = (CALLBACK_TASK)
|
||||
CALLBACK_EVENT = 0x00050000
|
||||
SND_SYNC = 0x0000
|
||||
SND_ASYNC = 0x0001
|
||||
SND_NODEFAULT = 0x0002
|
||||
SND_MEMORY = 0x0004
|
||||
SND_LOOP = 0x0008
|
||||
SND_NOSTOP = 0x0010
|
||||
SND_NOWAIT = 0x00002000
|
||||
SND_ALIAS = 0x00010000
|
||||
SND_ALIAS_ID = 0x00110000
|
||||
SND_FILENAME = 0x00020000
|
||||
SND_RESOURCE = 0x00040004
|
||||
SND_PURGE = 0x0040
|
||||
SND_APPLICATION = 0x0080
|
||||
SND_ALIAS_START = 0
|
||||
WAVERR_BADFORMAT = (WAVERR_BASE + 0)
|
||||
WAVERR_STILLPLAYING = (WAVERR_BASE + 1)
|
||||
WAVERR_UNPREPARED = (WAVERR_BASE + 2)
|
||||
WAVERR_SYNC = (WAVERR_BASE + 3)
|
||||
WAVERR_LASTERROR = (WAVERR_BASE + 3)
|
||||
WOM_OPEN = MM_WOM_OPEN
|
||||
WOM_CLOSE = MM_WOM_CLOSE
|
||||
WOM_DONE = MM_WOM_DONE
|
||||
WIM_OPEN = MM_WIM_OPEN
|
||||
WIM_CLOSE = MM_WIM_CLOSE
|
||||
WIM_DATA = MM_WIM_DATA
|
||||
WAVE_MAPPER = -1 # 0xFFFFFFFF
|
||||
WAVE_FORMAT_QUERY = 0x0001
|
||||
WAVE_ALLOWSYNC = 0x0002
|
||||
WAVE_MAPPED = 0x0004
|
||||
WAVE_FORMAT_DIRECT = 0x0008
|
||||
WAVE_FORMAT_DIRECT_QUERY = (WAVE_FORMAT_QUERY | WAVE_FORMAT_DIRECT)
|
||||
WHDR_DONE = 0x00000001
|
||||
WHDR_PREPARED = 0x00000002
|
||||
WHDR_BEGINLOOP = 0x00000004
|
||||
WHDR_ENDLOOP = 0x00000008
|
||||
WHDR_INQUEUE = 0x00000010
|
||||
WAVECAPS_PITCH = 0x0001
|
||||
WAVECAPS_PLAYBACKRATE = 0x0002
|
||||
WAVECAPS_VOLUME = 0x0004
|
||||
WAVECAPS_LRVOLUME = 0x0008
|
||||
WAVECAPS_SYNC = 0x0010
|
||||
WAVECAPS_SAMPLEACCURATE = 0x0020
|
||||
WAVECAPS_DIRECTSOUND = 0x0040
|
||||
WAVE_INVALIDFORMAT = 0x00000000
|
||||
WAVE_FORMAT_1M08 = 0x00000001
|
||||
WAVE_FORMAT_1S08 = 0x00000002
|
||||
WAVE_FORMAT_1M16 = 0x00000004
|
||||
WAVE_FORMAT_1S16 = 0x00000008
|
||||
WAVE_FORMAT_2M08 = 0x00000010
|
||||
WAVE_FORMAT_2S08 = 0x00000020
|
||||
WAVE_FORMAT_2M16 = 0x00000040
|
||||
WAVE_FORMAT_2S16 = 0x00000080
|
||||
WAVE_FORMAT_4M08 = 0x00000100
|
||||
WAVE_FORMAT_4S08 = 0x00000200
|
||||
WAVE_FORMAT_4M16 = 0x00000400
|
||||
WAVE_FORMAT_4S16 = 0x00000800
|
||||
WAVE_FORMAT_PCM = 1
|
||||
WAVE_FORMAT_IEEE_FLOAT = 3
|
||||
MIDIERR_UNPREPARED = (MIDIERR_BASE + 0)
|
||||
MIDIERR_STILLPLAYING = (MIDIERR_BASE + 1)
|
||||
MIDIERR_NOMAP = (MIDIERR_BASE + 2)
|
||||
MIDIERR_NOTREADY = (MIDIERR_BASE + 3)
|
||||
MIDIERR_NODEVICE = (MIDIERR_BASE + 4)
|
||||
MIDIERR_INVALIDSETUP = (MIDIERR_BASE + 5)
|
||||
MIDIERR_BADOPENMODE = (MIDIERR_BASE + 6)
|
||||
MIDIERR_DONT_CONTINUE = (MIDIERR_BASE + 7)
|
||||
MIDIERR_LASTERROR = (MIDIERR_BASE + 7)
|
||||
MIDIPATCHSIZE = 128
|
||||
MIM_OPEN = MM_MIM_OPEN
|
||||
MIM_CLOSE = MM_MIM_CLOSE
|
||||
MIM_DATA = MM_MIM_DATA
|
||||
MIM_LONGDATA = MM_MIM_LONGDATA
|
||||
MIM_ERROR = MM_MIM_ERROR
|
||||
MIM_LONGERROR = MM_MIM_LONGERROR
|
||||
MOM_OPEN = MM_MOM_OPEN
|
||||
MOM_CLOSE = MM_MOM_CLOSE
|
||||
MOM_DONE = MM_MOM_DONE
|
||||
MIM_MOREDATA = MM_MIM_MOREDATA
|
||||
MOM_POSITIONCB = MM_MOM_POSITIONCB
|
||||
MIDI_IO_STATUS = 0x00000020
|
||||
MIDI_CACHE_ALL = 1
|
||||
MIDI_CACHE_BESTFIT = 2
|
||||
MIDI_CACHE_QUERY = 3
|
||||
MIDI_UNCACHE = 4
|
||||
MOD_MIDIPORT = 1
|
||||
MOD_SYNTH = 2
|
||||
MOD_SQSYNTH = 3
|
||||
MOD_FMSYNTH = 4
|
||||
MOD_MAPPER = 5
|
||||
MIDICAPS_VOLUME = 0x0001
|
||||
MIDICAPS_LRVOLUME = 0x0002
|
||||
MIDICAPS_CACHE = 0x0004
|
||||
MIDICAPS_STREAM = 0x0008
|
||||
MHDR_DONE = 0x00000001
|
||||
MHDR_PREPARED = 0x00000002
|
||||
MHDR_INQUEUE = 0x00000004
|
||||
MHDR_ISSTRM = 0x00000008
|
||||
MEVT_F_SHORT = 0x00000000
|
||||
MEVT_F_LONG = -2147483648 # 0x80000000
|
||||
MEVT_F_CALLBACK = 0x40000000
|
||||
def MEVT_EVENTTYPE(x): return ((BYTE)(((x)>>24)&0xFF))
|
||||
|
||||
def MEVT_EVENTPARM(x): return ((DWORD)((x)&0x00FFFFFF))
|
||||
|
||||
MIDISTRM_ERROR = (-2)
|
||||
MIDIPROP_SET = -2147483648 # 0x80000000
|
||||
MIDIPROP_GET = 0x40000000
|
||||
MIDIPROP_TIMEDIV = 0x00000001
|
||||
MIDIPROP_TEMPO = 0x00000002
|
||||
AUXCAPS_CDAUDIO = 1
|
||||
AUXCAPS_AUXIN = 2
|
||||
AUXCAPS_VOLUME = 0x0001
|
||||
AUXCAPS_LRVOLUME = 0x0002
|
||||
MIXER_SHORT_NAME_CHARS = 16
|
||||
MIXER_LONG_NAME_CHARS = 64
|
||||
MIXERR_INVALLINE = (MIXERR_BASE + 0)
|
||||
MIXERR_INVALCONTROL = (MIXERR_BASE + 1)
|
||||
MIXERR_INVALVALUE = (MIXERR_BASE + 2)
|
||||
MIXERR_LASTERROR = (MIXERR_BASE + 2)
|
||||
MIXER_OBJECTF_HANDLE = -2147483648 # 0x80000000
|
||||
MIXER_OBJECTF_MIXER = 0x00000000
|
||||
MIXER_OBJECTF_HMIXER = (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIXER)
|
||||
MIXER_OBJECTF_WAVEOUT = 0x10000000
|
||||
MIXER_OBJECTF_HWAVEOUT = (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_WAVEOUT)
|
||||
MIXER_OBJECTF_WAVEIN = 0x20000000
|
||||
MIXER_OBJECTF_HWAVEIN = (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_WAVEIN)
|
||||
MIXER_OBJECTF_MIDIOUT = 0x30000000
|
||||
MIXER_OBJECTF_HMIDIOUT = (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIDIOUT)
|
||||
MIXER_OBJECTF_MIDIIN = 0x40000000
|
||||
MIXER_OBJECTF_HMIDIIN = (MIXER_OBJECTF_HANDLE|MIXER_OBJECTF_MIDIIN)
|
||||
MIXER_OBJECTF_AUX = 0x50000000
|
||||
MIXERLINE_LINEF_ACTIVE = 0x00000001
|
||||
MIXERLINE_LINEF_DISCONNECTED = 0x00008000
|
||||
MIXERLINE_LINEF_SOURCE = -2147483648 # 0x80000000
|
||||
MIXERLINE_COMPONENTTYPE_DST_FIRST = 0x00000000
|
||||
MIXERLINE_COMPONENTTYPE_DST_UNDEFINED = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 0)
|
||||
MIXERLINE_COMPONENTTYPE_DST_DIGITAL = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 1)
|
||||
MIXERLINE_COMPONENTTYPE_DST_LINE = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 2)
|
||||
MIXERLINE_COMPONENTTYPE_DST_MONITOR = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 3)
|
||||
MIXERLINE_COMPONENTTYPE_DST_SPEAKERS = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 4)
|
||||
MIXERLINE_COMPONENTTYPE_DST_HEADPHONES = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 5)
|
||||
MIXERLINE_COMPONENTTYPE_DST_TELEPHONE = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 6)
|
||||
MIXERLINE_COMPONENTTYPE_DST_WAVEIN = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 7)
|
||||
MIXERLINE_COMPONENTTYPE_DST_VOICEIN = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8)
|
||||
MIXERLINE_COMPONENTTYPE_DST_LAST = (MIXERLINE_COMPONENTTYPE_DST_FIRST + 8)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_FIRST = 0x00001000
|
||||
MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 0)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_DIGITAL = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 1)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_LINE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 2)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 3)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 4)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 5)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 6)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 7)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 8)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 9)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_ANALOG = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10)
|
||||
MIXERLINE_COMPONENTTYPE_SRC_LAST = (MIXERLINE_COMPONENTTYPE_SRC_FIRST + 10)
|
||||
MIXERLINE_TARGETTYPE_UNDEFINED = 0
|
||||
MIXERLINE_TARGETTYPE_WAVEOUT = 1
|
||||
MIXERLINE_TARGETTYPE_WAVEIN = 2
|
||||
MIXERLINE_TARGETTYPE_MIDIOUT = 3
|
||||
MIXERLINE_TARGETTYPE_MIDIIN = 4
|
||||
MIXERLINE_TARGETTYPE_AUX = 5
|
||||
MIXER_GETLINEINFOF_DESTINATION = 0x00000000
|
||||
MIXER_GETLINEINFOF_SOURCE = 0x00000001
|
||||
MIXER_GETLINEINFOF_LINEID = 0x00000002
|
||||
MIXER_GETLINEINFOF_COMPONENTTYPE = 0x00000003
|
||||
MIXER_GETLINEINFOF_TARGETTYPE = 0x00000004
|
||||
MIXER_GETLINEINFOF_QUERYMASK = 0x0000000F
|
||||
MIXERCONTROL_CONTROLF_UNIFORM = 0x00000001
|
||||
MIXERCONTROL_CONTROLF_MULTIPLE = 0x00000002
|
||||
MIXERCONTROL_CONTROLF_DISABLED = -2147483648 # 0x80000000
|
||||
MIXERCONTROL_CT_CLASS_MASK = -268435456 # 0xF0000000
|
||||
MIXERCONTROL_CT_CLASS_CUSTOM = 0x00000000
|
||||
MIXERCONTROL_CT_CLASS_METER = 0x10000000
|
||||
MIXERCONTROL_CT_CLASS_SWITCH = 0x20000000
|
||||
MIXERCONTROL_CT_CLASS_NUMBER = 0x30000000
|
||||
MIXERCONTROL_CT_CLASS_SLIDER = 0x40000000
|
||||
MIXERCONTROL_CT_CLASS_FADER = 0x50000000
|
||||
MIXERCONTROL_CT_CLASS_TIME = 0x60000000
|
||||
MIXERCONTROL_CT_CLASS_LIST = 0x70000000
|
||||
MIXERCONTROL_CT_SUBCLASS_MASK = 0x0F000000
|
||||
MIXERCONTROL_CT_SC_SWITCH_BOOLEAN = 0x00000000
|
||||
MIXERCONTROL_CT_SC_SWITCH_BUTTON = 0x01000000
|
||||
MIXERCONTROL_CT_SC_METER_POLLED = 0x00000000
|
||||
MIXERCONTROL_CT_SC_TIME_MICROSECS = 0x00000000
|
||||
MIXERCONTROL_CT_SC_TIME_MILLISECS = 0x01000000
|
||||
MIXERCONTROL_CT_SC_LIST_SINGLE = 0x00000000
|
||||
MIXERCONTROL_CT_SC_LIST_MULTIPLE = 0x01000000
|
||||
MIXERCONTROL_CT_UNITS_MASK = 0x00FF0000
|
||||
MIXERCONTROL_CT_UNITS_CUSTOM = 0x00000000
|
||||
MIXERCONTROL_CT_UNITS_BOOLEAN = 0x00010000
|
||||
MIXERCONTROL_CT_UNITS_SIGNED = 0x00020000
|
||||
MIXERCONTROL_CT_UNITS_UNSIGNED = 0x00030000
|
||||
MIXERCONTROL_CT_UNITS_DECIBELS = 0x00040000
|
||||
MIXERCONTROL_CT_UNITS_PERCENT = 0x00050000
|
||||
MIXERCONTROL_CONTROLTYPE_CUSTOM = (MIXERCONTROL_CT_CLASS_CUSTOM | MIXERCONTROL_CT_UNITS_CUSTOM)
|
||||
MIXERCONTROL_CONTROLTYPE_BOOLEANMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_BOOLEAN)
|
||||
MIXERCONTROL_CONTROLTYPE_SIGNEDMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_SIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_PEAKMETER = (MIXERCONTROL_CONTROLTYPE_SIGNEDMETER + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER = (MIXERCONTROL_CT_CLASS_METER | MIXERCONTROL_CT_SC_METER_POLLED | MIXERCONTROL_CT_UNITS_UNSIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_BOOLEAN = (MIXERCONTROL_CT_CLASS_SWITCH | MIXERCONTROL_CT_SC_SWITCH_BOOLEAN | MIXERCONTROL_CT_UNITS_BOOLEAN)
|
||||
MIXERCONTROL_CONTROLTYPE_ONOFF = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_MUTE = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 2)
|
||||
MIXERCONTROL_CONTROLTYPE_MONO = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 3)
|
||||
MIXERCONTROL_CONTROLTYPE_LOUDNESS = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 4)
|
||||
MIXERCONTROL_CONTROLTYPE_STEREOENH = (MIXERCONTROL_CONTROLTYPE_BOOLEAN + 5)
|
||||
MIXERCONTROL_CONTROLTYPE_BUTTON = (MIXERCONTROL_CT_CLASS_SWITCH | MIXERCONTROL_CT_SC_SWITCH_BUTTON | MIXERCONTROL_CT_UNITS_BOOLEAN)
|
||||
MIXERCONTROL_CONTROLTYPE_DECIBELS = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_DECIBELS)
|
||||
MIXERCONTROL_CONTROLTYPE_SIGNED = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_SIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_UNSIGNED = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_UNSIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_PERCENT = (MIXERCONTROL_CT_CLASS_NUMBER | MIXERCONTROL_CT_UNITS_PERCENT)
|
||||
MIXERCONTROL_CONTROLTYPE_SLIDER = (MIXERCONTROL_CT_CLASS_SLIDER | MIXERCONTROL_CT_UNITS_SIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_PAN = (MIXERCONTROL_CONTROLTYPE_SLIDER + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_QSOUNDPAN = (MIXERCONTROL_CONTROLTYPE_SLIDER + 2)
|
||||
MIXERCONTROL_CONTROLTYPE_FADER = (MIXERCONTROL_CT_CLASS_FADER | MIXERCONTROL_CT_UNITS_UNSIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_VOLUME = (MIXERCONTROL_CONTROLTYPE_FADER + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_BASS = (MIXERCONTROL_CONTROLTYPE_FADER + 2)
|
||||
MIXERCONTROL_CONTROLTYPE_TREBLE = (MIXERCONTROL_CONTROLTYPE_FADER + 3)
|
||||
MIXERCONTROL_CONTROLTYPE_EQUALIZER = (MIXERCONTROL_CONTROLTYPE_FADER + 4)
|
||||
MIXERCONTROL_CONTROLTYPE_SINGLESELECT = (MIXERCONTROL_CT_CLASS_LIST | MIXERCONTROL_CT_SC_LIST_SINGLE | MIXERCONTROL_CT_UNITS_BOOLEAN)
|
||||
MIXERCONTROL_CONTROLTYPE_MUX = (MIXERCONTROL_CONTROLTYPE_SINGLESELECT + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT = (MIXERCONTROL_CT_CLASS_LIST | MIXERCONTROL_CT_SC_LIST_MULTIPLE | MIXERCONTROL_CT_UNITS_BOOLEAN)
|
||||
MIXERCONTROL_CONTROLTYPE_MIXER = (MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT + 1)
|
||||
MIXERCONTROL_CONTROLTYPE_MICROTIME = (MIXERCONTROL_CT_CLASS_TIME | MIXERCONTROL_CT_SC_TIME_MICROSECS | MIXERCONTROL_CT_UNITS_UNSIGNED)
|
||||
MIXERCONTROL_CONTROLTYPE_MILLITIME = (MIXERCONTROL_CT_CLASS_TIME | MIXERCONTROL_CT_SC_TIME_MILLISECS | MIXERCONTROL_CT_UNITS_UNSIGNED)
|
||||
MIXER_GETLINECONTROLSF_ALL = 0x00000000
|
||||
MIXER_GETLINECONTROLSF_ONEBYID = 0x00000001
|
||||
MIXER_GETLINECONTROLSF_ONEBYTYPE = 0x00000002
|
||||
MIXER_GETLINECONTROLSF_QUERYMASK = 0x0000000F
|
||||
MIXER_GETCONTROLDETAILSF_VALUE = 0x00000000
|
||||
MIXER_GETCONTROLDETAILSF_LISTTEXT = 0x00000001
|
||||
MIXER_GETCONTROLDETAILSF_QUERYMASK = 0x0000000F
|
||||
MIXER_SETCONTROLDETAILSF_VALUE = 0x00000000
|
||||
MIXER_SETCONTROLDETAILSF_CUSTOM = 0x00000001
|
||||
MIXER_SETCONTROLDETAILSF_QUERYMASK = 0x0000000F
|
||||
TIMERR_NOERROR = (0)
|
||||
TIMERR_NOCANDO = (TIMERR_BASE+1)
|
||||
TIMERR_STRUCT = (TIMERR_BASE+33)
|
||||
TIME_ONESHOT = 0x0000
|
||||
TIME_PERIODIC = 0x0001
|
||||
TIME_CALLBACK_FUNCTION = 0x0000
|
||||
TIME_CALLBACK_EVENT_SET = 0x0010
|
||||
TIME_CALLBACK_EVENT_PULSE = 0x0020
|
||||
JOYERR_NOERROR = (0)
|
||||
JOYERR_PARMS = (JOYERR_BASE+5)
|
||||
JOYERR_NOCANDO = (JOYERR_BASE+6)
|
||||
JOYERR_UNPLUGGED = (JOYERR_BASE+7)
|
||||
JOY_BUTTON1 = 0x0001
|
||||
JOY_BUTTON2 = 0x0002
|
||||
JOY_BUTTON3 = 0x0004
|
||||
JOY_BUTTON4 = 0x0008
|
||||
JOY_BUTTON1CHG = 0x0100
|
||||
JOY_BUTTON2CHG = 0x0200
|
||||
JOY_BUTTON3CHG = 0x0400
|
||||
JOY_BUTTON4CHG = 0x0800
|
||||
JOY_BUTTON5 = 0x00000010
|
||||
JOY_BUTTON6 = 0x00000020
|
||||
JOY_BUTTON7 = 0x00000040
|
||||
JOY_BUTTON8 = 0x00000080
|
||||
JOY_BUTTON9 = 0x00000100
|
||||
JOY_BUTTON10 = 0x00000200
|
||||
JOY_BUTTON11 = 0x00000400
|
||||
JOY_BUTTON12 = 0x00000800
|
||||
JOY_BUTTON13 = 0x00001000
|
||||
JOY_BUTTON14 = 0x00002000
|
||||
JOY_BUTTON15 = 0x00004000
|
||||
JOY_BUTTON16 = 0x00008000
|
||||
JOY_BUTTON17 = 0x00010000
|
||||
JOY_BUTTON18 = 0x00020000
|
||||
JOY_BUTTON19 = 0x00040000
|
||||
JOY_BUTTON20 = 0x00080000
|
||||
JOY_BUTTON21 = 0x00100000
|
||||
JOY_BUTTON22 = 0x00200000
|
||||
JOY_BUTTON23 = 0x00400000
|
||||
JOY_BUTTON24 = 0x00800000
|
||||
JOY_BUTTON25 = 0x01000000
|
||||
JOY_BUTTON26 = 0x02000000
|
||||
JOY_BUTTON27 = 0x04000000
|
||||
JOY_BUTTON28 = 0x08000000
|
||||
JOY_BUTTON29 = 0x10000000
|
||||
JOY_BUTTON30 = 0x20000000
|
||||
JOY_BUTTON31 = 0x40000000
|
||||
JOY_BUTTON32 = -2147483648 # 0x80000000
|
||||
JOY_POVFORWARD = 0
|
||||
JOY_POVRIGHT = 9000
|
||||
JOY_POVBACKWARD = 18000
|
||||
JOY_POVLEFT = 27000
|
||||
JOY_RETURNX = 0x00000001
|
||||
JOY_RETURNY = 0x00000002
|
||||
JOY_RETURNZ = 0x00000004
|
||||
JOY_RETURNR = 0x00000008
|
||||
JOY_RETURNU = 0x00000010
|
||||
JOY_RETURNV = 0x00000020
|
||||
JOY_RETURNPOV = 0x00000040
|
||||
JOY_RETURNBUTTONS = 0x00000080
|
||||
JOY_RETURNRAWDATA = 0x00000100
|
||||
JOY_RETURNPOVCTS = 0x00000200
|
||||
JOY_RETURNCENTERED = 0x00000400
|
||||
JOY_USEDEADZONE = 0x00000800
|
||||
JOY_RETURNALL = (JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | \
|
||||
JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | \
|
||||
JOY_RETURNPOV | JOY_RETURNBUTTONS)
|
||||
JOY_CAL_READALWAYS = 0x00010000
|
||||
JOY_CAL_READXYONLY = 0x00020000
|
||||
JOY_CAL_READ3 = 0x00040000
|
||||
JOY_CAL_READ4 = 0x00080000
|
||||
JOY_CAL_READXONLY = 0x00100000
|
||||
JOY_CAL_READYONLY = 0x00200000
|
||||
JOY_CAL_READ5 = 0x00400000
|
||||
JOY_CAL_READ6 = 0x00800000
|
||||
JOY_CAL_READZONLY = 0x01000000
|
||||
JOY_CAL_READRONLY = 0x02000000
|
||||
JOY_CAL_READUONLY = 0x04000000
|
||||
JOY_CAL_READVONLY = 0x08000000
|
||||
JOYSTICKID1 = 0
|
||||
JOYSTICKID2 = 1
|
||||
JOYCAPS_HASZ = 0x0001
|
||||
JOYCAPS_HASR = 0x0002
|
||||
JOYCAPS_HASU = 0x0004
|
||||
JOYCAPS_HASV = 0x0008
|
||||
JOYCAPS_HASPOV = 0x0010
|
||||
JOYCAPS_POV4DIR = 0x0020
|
||||
JOYCAPS_POVCTS = 0x0040
|
||||
MMIOERR_BASE = 256
|
||||
MMIOERR_FILENOTFOUND = (MMIOERR_BASE + 1)
|
||||
MMIOERR_OUTOFMEMORY = (MMIOERR_BASE + 2)
|
||||
MMIOERR_CANNOTOPEN = (MMIOERR_BASE + 3)
|
||||
MMIOERR_CANNOTCLOSE = (MMIOERR_BASE + 4)
|
||||
MMIOERR_CANNOTREAD = (MMIOERR_BASE + 5)
|
||||
MMIOERR_CANNOTWRITE = (MMIOERR_BASE + 6)
|
||||
MMIOERR_CANNOTSEEK = (MMIOERR_BASE + 7)
|
||||
MMIOERR_CANNOTEXPAND = (MMIOERR_BASE + 8)
|
||||
MMIOERR_CHUNKNOTFOUND = (MMIOERR_BASE + 9)
|
||||
MMIOERR_UNBUFFERED = (MMIOERR_BASE + 10)
|
||||
MMIOERR_PATHNOTFOUND = (MMIOERR_BASE + 11)
|
||||
MMIOERR_ACCESSDENIED = (MMIOERR_BASE + 12)
|
||||
MMIOERR_SHARINGVIOLATION = (MMIOERR_BASE + 13)
|
||||
MMIOERR_NETWORKERROR = (MMIOERR_BASE + 14)
|
||||
MMIOERR_TOOMANYOPENFILES = (MMIOERR_BASE + 15)
|
||||
MMIOERR_INVALIDFILE = (MMIOERR_BASE + 16)
|
||||
CFSEPCHAR = ord('+')
|
||||
MMIO_RWMODE = 0x00000003
|
||||
MMIO_SHAREMODE = 0x00000070
|
||||
MMIO_CREATE = 0x00001000
|
||||
MMIO_PARSE = 0x00000100
|
||||
MMIO_DELETE = 0x00000200
|
||||
MMIO_EXIST = 0x00004000
|
||||
MMIO_ALLOCBUF = 0x00010000
|
||||
MMIO_GETTEMP = 0x00020000
|
||||
MMIO_DIRTY = 0x10000000
|
||||
MMIO_READ = 0x00000000
|
||||
MMIO_WRITE = 0x00000001
|
||||
MMIO_READWRITE = 0x00000002
|
||||
MMIO_COMPAT = 0x00000000
|
||||
MMIO_EXCLUSIVE = 0x00000010
|
||||
MMIO_DENYWRITE = 0x00000020
|
||||
MMIO_DENYREAD = 0x00000030
|
||||
MMIO_DENYNONE = 0x00000040
|
||||
MMIO_FHOPEN = 0x0010
|
||||
MMIO_EMPTYBUF = 0x0010
|
||||
MMIO_TOUPPER = 0x0010
|
||||
MMIO_INSTALLPROC = 0x00010000
|
||||
MMIO_GLOBALPROC = 0x10000000
|
||||
MMIO_REMOVEPROC = 0x00020000
|
||||
MMIO_UNICODEPROC = 0x01000000
|
||||
MMIO_FINDPROC = 0x00040000
|
||||
MMIO_FINDCHUNK = 0x0010
|
||||
MMIO_FINDRIFF = 0x0020
|
||||
MMIO_FINDLIST = 0x0040
|
||||
MMIO_CREATERIFF = 0x0020
|
||||
MMIO_CREATELIST = 0x0040
|
||||
MMIOM_READ = MMIO_READ
|
||||
MMIOM_WRITE = MMIO_WRITE
|
||||
MMIOM_SEEK = 2
|
||||
MMIOM_OPEN = 3
|
||||
MMIOM_CLOSE = 4
|
||||
MMIOM_WRITEFLUSH = 5
|
||||
MMIOM_RENAME = 6
|
||||
MMIOM_USER = 0x8000
|
||||
SEEK_SET = 0
|
||||
SEEK_CUR = 1
|
||||
SEEK_END = 2
|
||||
MMIO_DEFAULTBUFFER = 8192
|
||||
MCIERR_INVALID_DEVICE_ID = (MCIERR_BASE + 1)
|
||||
MCIERR_UNRECOGNIZED_KEYWORD = (MCIERR_BASE + 3)
|
||||
MCIERR_UNRECOGNIZED_COMMAND = (MCIERR_BASE + 5)
|
||||
MCIERR_HARDWARE = (MCIERR_BASE + 6)
|
||||
MCIERR_INVALID_DEVICE_NAME = (MCIERR_BASE + 7)
|
||||
MCIERR_OUT_OF_MEMORY = (MCIERR_BASE + 8)
|
||||
MCIERR_DEVICE_OPEN = (MCIERR_BASE + 9)
|
||||
MCIERR_CANNOT_LOAD_DRIVER = (MCIERR_BASE + 10)
|
||||
MCIERR_MISSING_COMMAND_STRING = (MCIERR_BASE + 11)
|
||||
MCIERR_PARAM_OVERFLOW = (MCIERR_BASE + 12)
|
||||
MCIERR_MISSING_STRING_ARGUMENT = (MCIERR_BASE + 13)
|
||||
MCIERR_BAD_INTEGER = (MCIERR_BASE + 14)
|
||||
MCIERR_PARSER_INTERNAL = (MCIERR_BASE + 15)
|
||||
MCIERR_DRIVER_INTERNAL = (MCIERR_BASE + 16)
|
||||
MCIERR_MISSING_PARAMETER = (MCIERR_BASE + 17)
|
||||
MCIERR_UNSUPPORTED_FUNCTION = (MCIERR_BASE + 18)
|
||||
MCIERR_FILE_NOT_FOUND = (MCIERR_BASE + 19)
|
||||
MCIERR_DEVICE_NOT_READY = (MCIERR_BASE + 20)
|
||||
MCIERR_INTERNAL = (MCIERR_BASE + 21)
|
||||
MCIERR_DRIVER = (MCIERR_BASE + 22)
|
||||
MCIERR_CANNOT_USE_ALL = (MCIERR_BASE + 23)
|
||||
MCIERR_MULTIPLE = (MCIERR_BASE + 24)
|
||||
MCIERR_EXTENSION_NOT_FOUND = (MCIERR_BASE + 25)
|
||||
MCIERR_OUTOFRANGE = (MCIERR_BASE + 26)
|
||||
MCIERR_FLAGS_NOT_COMPATIBLE = (MCIERR_BASE + 28)
|
||||
MCIERR_FILE_NOT_SAVED = (MCIERR_BASE + 30)
|
||||
MCIERR_DEVICE_TYPE_REQUIRED = (MCIERR_BASE + 31)
|
||||
MCIERR_DEVICE_LOCKED = (MCIERR_BASE + 32)
|
||||
MCIERR_DUPLICATE_ALIAS = (MCIERR_BASE + 33)
|
||||
MCIERR_BAD_CONSTANT = (MCIERR_BASE + 34)
|
||||
MCIERR_MUST_USE_SHAREABLE = (MCIERR_BASE + 35)
|
||||
MCIERR_MISSING_DEVICE_NAME = (MCIERR_BASE + 36)
|
||||
MCIERR_BAD_TIME_FORMAT = (MCIERR_BASE + 37)
|
||||
MCIERR_NO_CLOSING_QUOTE = (MCIERR_BASE + 38)
|
||||
MCIERR_DUPLICATE_FLAGS = (MCIERR_BASE + 39)
|
||||
MCIERR_INVALID_FILE = (MCIERR_BASE + 40)
|
||||
MCIERR_NULL_PARAMETER_BLOCK = (MCIERR_BASE + 41)
|
||||
MCIERR_UNNAMED_RESOURCE = (MCIERR_BASE + 42)
|
||||
MCIERR_NEW_REQUIRES_ALIAS = (MCIERR_BASE + 43)
|
||||
MCIERR_NOTIFY_ON_AUTO_OPEN = (MCIERR_BASE + 44)
|
||||
MCIERR_NO_ELEMENT_ALLOWED = (MCIERR_BASE + 45)
|
||||
MCIERR_NONAPPLICABLE_FUNCTION = (MCIERR_BASE + 46)
|
||||
MCIERR_ILLEGAL_FOR_AUTO_OPEN = (MCIERR_BASE + 47)
|
||||
MCIERR_FILENAME_REQUIRED = (MCIERR_BASE + 48)
|
||||
MCIERR_EXTRA_CHARACTERS = (MCIERR_BASE + 49)
|
||||
MCIERR_DEVICE_NOT_INSTALLED = (MCIERR_BASE + 50)
|
||||
MCIERR_GET_CD = (MCIERR_BASE + 51)
|
||||
MCIERR_SET_CD = (MCIERR_BASE + 52)
|
||||
MCIERR_SET_DRIVE = (MCIERR_BASE + 53)
|
||||
MCIERR_DEVICE_LENGTH = (MCIERR_BASE + 54)
|
||||
MCIERR_DEVICE_ORD_LENGTH = (MCIERR_BASE + 55)
|
||||
MCIERR_NO_INTEGER = (MCIERR_BASE + 56)
|
||||
MCIERR_WAVE_OUTPUTSINUSE = (MCIERR_BASE + 64)
|
||||
MCIERR_WAVE_SETOUTPUTINUSE = (MCIERR_BASE + 65)
|
||||
MCIERR_WAVE_INPUTSINUSE = (MCIERR_BASE + 66)
|
||||
MCIERR_WAVE_SETINPUTINUSE = (MCIERR_BASE + 67)
|
||||
MCIERR_WAVE_OUTPUTUNSPECIFIED = (MCIERR_BASE + 68)
|
||||
MCIERR_WAVE_INPUTUNSPECIFIED = (MCIERR_BASE + 69)
|
||||
MCIERR_WAVE_OUTPUTSUNSUITABLE = (MCIERR_BASE + 70)
|
||||
MCIERR_WAVE_SETOUTPUTUNSUITABLE = (MCIERR_BASE + 71)
|
||||
MCIERR_WAVE_INPUTSUNSUITABLE = (MCIERR_BASE + 72)
|
||||
MCIERR_WAVE_SETINPUTUNSUITABLE = (MCIERR_BASE + 73)
|
||||
MCIERR_SEQ_DIV_INCOMPATIBLE = (MCIERR_BASE + 80)
|
||||
MCIERR_SEQ_PORT_INUSE = (MCIERR_BASE + 81)
|
||||
MCIERR_SEQ_PORT_NONEXISTENT = (MCIERR_BASE + 82)
|
||||
MCIERR_SEQ_PORT_MAPNODEVICE = (MCIERR_BASE + 83)
|
||||
MCIERR_SEQ_PORT_MISCERROR = (MCIERR_BASE + 84)
|
||||
MCIERR_SEQ_TIMER = (MCIERR_BASE + 85)
|
||||
MCIERR_SEQ_PORTUNSPECIFIED = (MCIERR_BASE + 86)
|
||||
MCIERR_SEQ_NOMIDIPRESENT = (MCIERR_BASE + 87)
|
||||
MCIERR_NO_WINDOW = (MCIERR_BASE + 90)
|
||||
MCIERR_CREATEWINDOW = (MCIERR_BASE + 91)
|
||||
MCIERR_FILE_READ = (MCIERR_BASE + 92)
|
||||
MCIERR_FILE_WRITE = (MCIERR_BASE + 93)
|
||||
MCIERR_NO_IDENTITY = (MCIERR_BASE + 94)
|
||||
MCIERR_CUSTOM_DRIVER_BASE = (MCIERR_BASE + 256)
|
||||
MCI_FIRST = DRV_MCI_FIRST
|
||||
MCI_OPEN = 0x0803
|
||||
MCI_CLOSE = 0x0804
|
||||
MCI_ESCAPE = 0x0805
|
||||
MCI_PLAY = 0x0806
|
||||
MCI_SEEK = 0x0807
|
||||
MCI_STOP = 0x0808
|
||||
MCI_PAUSE = 0x0809
|
||||
MCI_INFO = 0x080A
|
||||
MCI_GETDEVCAPS = 0x080B
|
||||
MCI_SPIN = 0x080C
|
||||
MCI_SET = 0x080D
|
||||
MCI_STEP = 0x080E
|
||||
MCI_RECORD = 0x080F
|
||||
MCI_SYSINFO = 0x0810
|
||||
MCI_BREAK = 0x0811
|
||||
MCI_SAVE = 0x0813
|
||||
MCI_STATUS = 0x0814
|
||||
MCI_CUE = 0x0830
|
||||
MCI_REALIZE = 0x0840
|
||||
MCI_WINDOW = 0x0841
|
||||
MCI_PUT = 0x0842
|
||||
MCI_WHERE = 0x0843
|
||||
MCI_FREEZE = 0x0844
|
||||
MCI_UNFREEZE = 0x0845
|
||||
MCI_LOAD = 0x0850
|
||||
MCI_CUT = 0x0851
|
||||
MCI_COPY = 0x0852
|
||||
MCI_PASTE = 0x0853
|
||||
MCI_UPDATE = 0x0854
|
||||
MCI_RESUME = 0x0855
|
||||
MCI_DELETE = 0x0856
|
||||
MCI_USER_MESSAGES = (DRV_MCI_FIRST + 0x400)
|
||||
MCI_LAST = 0x0FFF
|
||||
MCI_DEVTYPE_VCR = 513
|
||||
MCI_DEVTYPE_VIDEODISC = 514
|
||||
MCI_DEVTYPE_OVERLAY = 515
|
||||
MCI_DEVTYPE_CD_AUDIO = 516
|
||||
MCI_DEVTYPE_DAT = 517
|
||||
MCI_DEVTYPE_SCANNER = 518
|
||||
MCI_DEVTYPE_ANIMATION = 519
|
||||
MCI_DEVTYPE_DIGITAL_VIDEO = 520
|
||||
MCI_DEVTYPE_OTHER = 521
|
||||
MCI_DEVTYPE_WAVEFORM_AUDIO = 522
|
||||
MCI_DEVTYPE_SEQUENCER = 523
|
||||
MCI_DEVTYPE_FIRST = MCI_DEVTYPE_VCR
|
||||
MCI_DEVTYPE_LAST = MCI_DEVTYPE_SEQUENCER
|
||||
MCI_DEVTYPE_FIRST_USER = 0x1000
|
||||
MCI_MODE_NOT_READY = (MCI_STRING_OFFSET + 12)
|
||||
MCI_MODE_STOP = (MCI_STRING_OFFSET + 13)
|
||||
MCI_MODE_PLAY = (MCI_STRING_OFFSET + 14)
|
||||
MCI_MODE_RECORD = (MCI_STRING_OFFSET + 15)
|
||||
MCI_MODE_SEEK = (MCI_STRING_OFFSET + 16)
|
||||
MCI_MODE_PAUSE = (MCI_STRING_OFFSET + 17)
|
||||
MCI_MODE_OPEN = (MCI_STRING_OFFSET + 18)
|
||||
MCI_FORMAT_MILLISECONDS = 0
|
||||
MCI_FORMAT_HMS = 1
|
||||
MCI_FORMAT_MSF = 2
|
||||
MCI_FORMAT_FRAMES = 3
|
||||
MCI_FORMAT_SMPTE_24 = 4
|
||||
MCI_FORMAT_SMPTE_25 = 5
|
||||
MCI_FORMAT_SMPTE_30 = 6
|
||||
MCI_FORMAT_SMPTE_30DROP = 7
|
||||
MCI_FORMAT_BYTES = 8
|
||||
MCI_FORMAT_SAMPLES = 9
|
||||
MCI_FORMAT_TMSF = 10
|
||||
def MCI_MSF_MINUTE(msf): return ((BYTE)(msf))
|
||||
|
||||
def MCI_MSF_SECOND(msf): return ((BYTE)(((WORD)(msf)) >> 8))
|
||||
|
||||
def MCI_MSF_FRAME(msf): return ((BYTE)((msf)>>16))
|
||||
|
||||
def MCI_TMSF_TRACK(tmsf): return ((BYTE)(tmsf))
|
||||
|
||||
def MCI_TMSF_MINUTE(tmsf): return ((BYTE)(((WORD)(tmsf)) >> 8))
|
||||
|
||||
def MCI_TMSF_SECOND(tmsf): return ((BYTE)((tmsf)>>16))
|
||||
|
||||
def MCI_TMSF_FRAME(tmsf): return ((BYTE)((tmsf)>>24))
|
||||
|
||||
def MCI_HMS_HOUR(hms): return ((BYTE)(hms))
|
||||
|
||||
def MCI_HMS_MINUTE(hms): return ((BYTE)(((WORD)(hms)) >> 8))
|
||||
|
||||
def MCI_HMS_SECOND(hms): return ((BYTE)((hms)>>16))
|
||||
|
||||
MCI_NOTIFY_SUCCESSFUL = 0x0001
|
||||
MCI_NOTIFY_SUPERSEDED = 0x0002
|
||||
MCI_NOTIFY_ABORTED = 0x0004
|
||||
MCI_NOTIFY_FAILURE = 0x0008
|
||||
MCI_NOTIFY = 0x00000001
|
||||
MCI_WAIT = 0x00000002
|
||||
MCI_FROM = 0x00000004
|
||||
MCI_TO = 0x00000008
|
||||
MCI_TRACK = 0x00000010
|
||||
MCI_OPEN_SHAREABLE = 0x00000100
|
||||
MCI_OPEN_ELEMENT = 0x00000200
|
||||
MCI_OPEN_ALIAS = 0x00000400
|
||||
MCI_OPEN_ELEMENT_ID = 0x00000800
|
||||
MCI_OPEN_TYPE_ID = 0x00001000
|
||||
MCI_OPEN_TYPE = 0x00002000
|
||||
MCI_SEEK_TO_START = 0x00000100
|
||||
MCI_SEEK_TO_END = 0x00000200
|
||||
MCI_STATUS_ITEM = 0x00000100
|
||||
MCI_STATUS_START = 0x00000200
|
||||
MCI_STATUS_LENGTH = 0x00000001
|
||||
MCI_STATUS_POSITION = 0x00000002
|
||||
MCI_STATUS_NUMBER_OF_TRACKS = 0x00000003
|
||||
MCI_STATUS_MODE = 0x00000004
|
||||
MCI_STATUS_MEDIA_PRESENT = 0x00000005
|
||||
MCI_STATUS_TIME_FORMAT = 0x00000006
|
||||
MCI_STATUS_READY = 0x00000007
|
||||
MCI_STATUS_CURRENT_TRACK = 0x00000008
|
||||
MCI_INFO_PRODUCT = 0x00000100
|
||||
MCI_INFO_FILE = 0x00000200
|
||||
MCI_INFO_MEDIA_UPC = 0x00000400
|
||||
MCI_INFO_MEDIA_IDENTITY = 0x00000800
|
||||
MCI_INFO_NAME = 0x00001000
|
||||
MCI_INFO_COPYRIGHT = 0x00002000
|
||||
MCI_GETDEVCAPS_ITEM = 0x00000100
|
||||
MCI_GETDEVCAPS_CAN_RECORD = 0x00000001
|
||||
MCI_GETDEVCAPS_HAS_AUDIO = 0x00000002
|
||||
MCI_GETDEVCAPS_HAS_VIDEO = 0x00000003
|
||||
MCI_GETDEVCAPS_DEVICE_TYPE = 0x00000004
|
||||
MCI_GETDEVCAPS_USES_FILES = 0x00000005
|
||||
MCI_GETDEVCAPS_COMPOUND_DEVICE = 0x00000006
|
||||
MCI_GETDEVCAPS_CAN_EJECT = 0x00000007
|
||||
MCI_GETDEVCAPS_CAN_PLAY = 0x00000008
|
||||
MCI_GETDEVCAPS_CAN_SAVE = 0x00000009
|
||||
MCI_SYSINFO_QUANTITY = 0x00000100
|
||||
MCI_SYSINFO_OPEN = 0x00000200
|
||||
MCI_SYSINFO_NAME = 0x00000400
|
||||
MCI_SYSINFO_INSTALLNAME = 0x00000800
|
||||
MCI_SET_DOOR_OPEN = 0x00000100
|
||||
MCI_SET_DOOR_CLOSED = 0x00000200
|
||||
MCI_SET_TIME_FORMAT = 0x00000400
|
||||
MCI_SET_AUDIO = 0x00000800
|
||||
MCI_SET_VIDEO = 0x00001000
|
||||
MCI_SET_ON = 0x00002000
|
||||
MCI_SET_OFF = 0x00004000
|
||||
MCI_SET_AUDIO_ALL = 0x00000000
|
||||
MCI_SET_AUDIO_LEFT = 0x00000001
|
||||
MCI_SET_AUDIO_RIGHT = 0x00000002
|
||||
MCI_BREAK_KEY = 0x00000100
|
||||
MCI_BREAK_HWND = 0x00000200
|
||||
MCI_BREAK_OFF = 0x00000400
|
||||
MCI_RECORD_INSERT = 0x00000100
|
||||
MCI_RECORD_OVERWRITE = 0x00000200
|
||||
MCI_SAVE_FILE = 0x00000100
|
||||
MCI_LOAD_FILE = 0x00000100
|
||||
MCI_VD_MODE_PARK = (MCI_VD_OFFSET + 1)
|
||||
MCI_VD_MEDIA_CLV = (MCI_VD_OFFSET + 2)
|
||||
MCI_VD_MEDIA_CAV = (MCI_VD_OFFSET + 3)
|
||||
MCI_VD_MEDIA_OTHER = (MCI_VD_OFFSET + 4)
|
||||
MCI_VD_FORMAT_TRACK = 0x4001
|
||||
MCI_VD_PLAY_REVERSE = 0x00010000
|
||||
MCI_VD_PLAY_FAST = 0x00020000
|
||||
MCI_VD_PLAY_SPEED = 0x00040000
|
||||
MCI_VD_PLAY_SCAN = 0x00080000
|
||||
MCI_VD_PLAY_SLOW = 0x00100000
|
||||
MCI_VD_SEEK_REVERSE = 0x00010000
|
||||
MCI_VD_STATUS_SPEED = 0x00004002
|
||||
MCI_VD_STATUS_FORWARD = 0x00004003
|
||||
MCI_VD_STATUS_MEDIA_TYPE = 0x00004004
|
||||
MCI_VD_STATUS_SIDE = 0x00004005
|
||||
MCI_VD_STATUS_DISC_SIZE = 0x00004006
|
||||
MCI_VD_GETDEVCAPS_CLV = 0x00010000
|
||||
MCI_VD_GETDEVCAPS_CAV = 0x00020000
|
||||
MCI_VD_SPIN_UP = 0x00010000
|
||||
MCI_VD_SPIN_DOWN = 0x00020000
|
||||
MCI_VD_GETDEVCAPS_CAN_REVERSE = 0x00004002
|
||||
MCI_VD_GETDEVCAPS_FAST_RATE = 0x00004003
|
||||
MCI_VD_GETDEVCAPS_SLOW_RATE = 0x00004004
|
||||
MCI_VD_GETDEVCAPS_NORMAL_RATE = 0x00004005
|
||||
MCI_VD_STEP_FRAMES = 0x00010000
|
||||
MCI_VD_STEP_REVERSE = 0x00020000
|
||||
MCI_VD_ESCAPE_STRING = 0x00000100
|
||||
MCI_CDA_STATUS_TYPE_TRACK = 0x00004001
|
||||
MCI_CDA_TRACK_AUDIO = (MCI_CD_OFFSET + 0)
|
||||
MCI_CDA_TRACK_OTHER = (MCI_CD_OFFSET + 1)
|
||||
MCI_WAVE_PCM = (MCI_WAVE_OFFSET + 0)
|
||||
MCI_WAVE_MAPPER = (MCI_WAVE_OFFSET + 1)
|
||||
MCI_WAVE_OPEN_BUFFER = 0x00010000
|
||||
MCI_WAVE_SET_FORMATTAG = 0x00010000
|
||||
MCI_WAVE_SET_CHANNELS = 0x00020000
|
||||
MCI_WAVE_SET_SAMPLESPERSEC = 0x00040000
|
||||
MCI_WAVE_SET_AVGBYTESPERSEC = 0x00080000
|
||||
MCI_WAVE_SET_BLOCKALIGN = 0x00100000
|
||||
MCI_WAVE_SET_BITSPERSAMPLE = 0x00200000
|
||||
MCI_WAVE_INPUT = 0x00400000
|
||||
MCI_WAVE_OUTPUT = 0x00800000
|
||||
MCI_WAVE_STATUS_FORMATTAG = 0x00004001
|
||||
MCI_WAVE_STATUS_CHANNELS = 0x00004002
|
||||
MCI_WAVE_STATUS_SAMPLESPERSEC = 0x00004003
|
||||
MCI_WAVE_STATUS_AVGBYTESPERSEC = 0x00004004
|
||||
MCI_WAVE_STATUS_BLOCKALIGN = 0x00004005
|
||||
MCI_WAVE_STATUS_BITSPERSAMPLE = 0x00004006
|
||||
MCI_WAVE_STATUS_LEVEL = 0x00004007
|
||||
MCI_WAVE_SET_ANYINPUT = 0x04000000
|
||||
MCI_WAVE_SET_ANYOUTPUT = 0x08000000
|
||||
MCI_WAVE_GETDEVCAPS_INPUTS = 0x00004001
|
||||
MCI_WAVE_GETDEVCAPS_OUTPUTS = 0x00004002
|
||||
MCI_SEQ_DIV_PPQN = (0 + MCI_SEQ_OFFSET)
|
||||
MCI_SEQ_DIV_SMPTE_24 = (1 + MCI_SEQ_OFFSET)
|
||||
MCI_SEQ_DIV_SMPTE_25 = (2 + MCI_SEQ_OFFSET)
|
||||
MCI_SEQ_DIV_SMPTE_30DROP = (3 + MCI_SEQ_OFFSET)
|
||||
MCI_SEQ_DIV_SMPTE_30 = (4 + MCI_SEQ_OFFSET)
|
||||
MCI_SEQ_FORMAT_SONGPTR = 0x4001
|
||||
MCI_SEQ_FILE = 0x4002
|
||||
MCI_SEQ_MIDI = 0x4003
|
||||
MCI_SEQ_SMPTE = 0x4004
|
||||
MCI_SEQ_NONE = 65533
|
||||
MCI_SEQ_MAPPER = 65535
|
||||
MCI_SEQ_STATUS_TEMPO = 0x00004002
|
||||
MCI_SEQ_STATUS_PORT = 0x00004003
|
||||
MCI_SEQ_STATUS_SLAVE = 0x00004007
|
||||
MCI_SEQ_STATUS_MASTER = 0x00004008
|
||||
MCI_SEQ_STATUS_OFFSET = 0x00004009
|
||||
MCI_SEQ_STATUS_DIVTYPE = 0x0000400A
|
||||
MCI_SEQ_STATUS_NAME = 0x0000400B
|
||||
MCI_SEQ_STATUS_COPYRIGHT = 0x0000400C
|
||||
MCI_SEQ_SET_TEMPO = 0x00010000
|
||||
MCI_SEQ_SET_PORT = 0x00020000
|
||||
MCI_SEQ_SET_SLAVE = 0x00040000
|
||||
MCI_SEQ_SET_MASTER = 0x00080000
|
||||
MCI_SEQ_SET_OFFSET = 0x01000000
|
||||
MCI_ANIM_OPEN_WS = 0x00010000
|
||||
MCI_ANIM_OPEN_PARENT = 0x00020000
|
||||
MCI_ANIM_OPEN_NOSTATIC = 0x00040000
|
||||
MCI_ANIM_PLAY_SPEED = 0x00010000
|
||||
MCI_ANIM_PLAY_REVERSE = 0x00020000
|
||||
MCI_ANIM_PLAY_FAST = 0x00040000
|
||||
MCI_ANIM_PLAY_SLOW = 0x00080000
|
||||
MCI_ANIM_PLAY_SCAN = 0x00100000
|
||||
MCI_ANIM_STEP_REVERSE = 0x00010000
|
||||
MCI_ANIM_STEP_FRAMES = 0x00020000
|
||||
MCI_ANIM_STATUS_SPEED = 0x00004001
|
||||
MCI_ANIM_STATUS_FORWARD = 0x00004002
|
||||
MCI_ANIM_STATUS_HWND = 0x00004003
|
||||
MCI_ANIM_STATUS_HPAL = 0x00004004
|
||||
MCI_ANIM_STATUS_STRETCH = 0x00004005
|
||||
MCI_ANIM_INFO_TEXT = 0x00010000
|
||||
MCI_ANIM_GETDEVCAPS_CAN_REVERSE = 0x00004001
|
||||
MCI_ANIM_GETDEVCAPS_FAST_RATE = 0x00004002
|
||||
MCI_ANIM_GETDEVCAPS_SLOW_RATE = 0x00004003
|
||||
MCI_ANIM_GETDEVCAPS_NORMAL_RATE = 0x00004004
|
||||
MCI_ANIM_GETDEVCAPS_PALETTES = 0x00004006
|
||||
MCI_ANIM_GETDEVCAPS_CAN_STRETCH = 0x00004007
|
||||
MCI_ANIM_GETDEVCAPS_MAX_WINDOWS = 0x00004008
|
||||
MCI_ANIM_REALIZE_NORM = 0x00010000
|
||||
MCI_ANIM_REALIZE_BKGD = 0x00020000
|
||||
MCI_ANIM_WINDOW_HWND = 0x00010000
|
||||
MCI_ANIM_WINDOW_STATE = 0x00040000
|
||||
MCI_ANIM_WINDOW_TEXT = 0x00080000
|
||||
MCI_ANIM_WINDOW_ENABLE_STRETCH = 0x00100000
|
||||
MCI_ANIM_WINDOW_DISABLE_STRETCH = 0x00200000
|
||||
MCI_ANIM_WINDOW_DEFAULT = 0x00000000
|
||||
MCI_ANIM_RECT = 0x00010000
|
||||
MCI_ANIM_PUT_SOURCE = 0x00020000
|
||||
MCI_ANIM_PUT_DESTINATION = 0x00040000
|
||||
MCI_ANIM_WHERE_SOURCE = 0x00020000
|
||||
MCI_ANIM_WHERE_DESTINATION = 0x00040000
|
||||
MCI_ANIM_UPDATE_HDC = 0x00020000
|
||||
MCI_OVLY_OPEN_WS = 0x00010000
|
||||
MCI_OVLY_OPEN_PARENT = 0x00020000
|
||||
MCI_OVLY_STATUS_HWND = 0x00004001
|
||||
MCI_OVLY_STATUS_STRETCH = 0x00004002
|
||||
MCI_OVLY_INFO_TEXT = 0x00010000
|
||||
MCI_OVLY_GETDEVCAPS_CAN_STRETCH = 0x00004001
|
||||
MCI_OVLY_GETDEVCAPS_CAN_FREEZE = 0x00004002
|
||||
MCI_OVLY_GETDEVCAPS_MAX_WINDOWS = 0x00004003
|
||||
MCI_OVLY_WINDOW_HWND = 0x00010000
|
||||
MCI_OVLY_WINDOW_STATE = 0x00040000
|
||||
MCI_OVLY_WINDOW_TEXT = 0x00080000
|
||||
MCI_OVLY_WINDOW_ENABLE_STRETCH = 0x00100000
|
||||
MCI_OVLY_WINDOW_DISABLE_STRETCH = 0x00200000
|
||||
MCI_OVLY_WINDOW_DEFAULT = 0x00000000
|
||||
MCI_OVLY_RECT = 0x00010000
|
||||
MCI_OVLY_PUT_SOURCE = 0x00020000
|
||||
MCI_OVLY_PUT_DESTINATION = 0x00040000
|
||||
MCI_OVLY_PUT_FRAME = 0x00080000
|
||||
MCI_OVLY_PUT_VIDEO = 0x00100000
|
||||
MCI_OVLY_WHERE_SOURCE = 0x00020000
|
||||
MCI_OVLY_WHERE_DESTINATION = 0x00040000
|
||||
MCI_OVLY_WHERE_FRAME = 0x00080000
|
||||
MCI_OVLY_WHERE_VIDEO = 0x00100000
|
||||
SELECTDIB = 41
|
||||
def DIBINDEX(n): return MAKELONG((n),0x10FF)
|
||||
|
||||
292
Pywin32/lib/x32/win32/lib/netbios.py
Normal file
@@ -0,0 +1,292 @@
|
||||
import sys
|
||||
import win32wnet
|
||||
import struct
|
||||
|
||||
# Constants generated by h2py from nb30.h
|
||||
NCBNAMSZ = 16
|
||||
MAX_LANA = 254
|
||||
NAME_FLAGS_MASK = 0x87
|
||||
GROUP_NAME = 0x80
|
||||
UNIQUE_NAME = 0x00
|
||||
REGISTERING = 0x00
|
||||
REGISTERED = 0x04
|
||||
DEREGISTERED = 0x05
|
||||
DUPLICATE = 0x06
|
||||
DUPLICATE_DEREG = 0x07
|
||||
LISTEN_OUTSTANDING = 0x01
|
||||
CALL_PENDING = 0x02
|
||||
SESSION_ESTABLISHED = 0x03
|
||||
HANGUP_PENDING = 0x04
|
||||
HANGUP_COMPLETE = 0x05
|
||||
SESSION_ABORTED = 0x06
|
||||
ALL_TRANSPORTS = "M\0\0\0"
|
||||
MS_NBF = "MNBF"
|
||||
NCBCALL = 0x10
|
||||
NCBLISTEN = 0x11
|
||||
NCBHANGUP = 0x12
|
||||
NCBSEND = 0x14
|
||||
NCBRECV = 0x15
|
||||
NCBRECVANY = 0x16
|
||||
NCBCHAINSEND = 0x17
|
||||
NCBDGSEND = 0x20
|
||||
NCBDGRECV = 0x21
|
||||
NCBDGSENDBC = 0x22
|
||||
NCBDGRECVBC = 0x23
|
||||
NCBADDNAME = 0x30
|
||||
NCBDELNAME = 0x31
|
||||
NCBRESET = 0x32
|
||||
NCBASTAT = 0x33
|
||||
NCBSSTAT = 0x34
|
||||
NCBCANCEL = 0x35
|
||||
NCBADDGRNAME = 0x36
|
||||
NCBENUM = 0x37
|
||||
NCBUNLINK = 0x70
|
||||
NCBSENDNA = 0x71
|
||||
NCBCHAINSENDNA = 0x72
|
||||
NCBLANSTALERT = 0x73
|
||||
NCBACTION = 0x77
|
||||
NCBFINDNAME = 0x78
|
||||
NCBTRACE = 0x79
|
||||
ASYNCH = 0x80
|
||||
NRC_GOODRET = 0x00
|
||||
NRC_BUFLEN = 0x01
|
||||
NRC_ILLCMD = 0x03
|
||||
NRC_CMDTMO = 0x05
|
||||
NRC_INCOMP = 0x06
|
||||
NRC_BADDR = 0x07
|
||||
NRC_SNUMOUT = 0x08
|
||||
NRC_NORES = 0x09
|
||||
NRC_SCLOSED = 0x0a
|
||||
NRC_CMDCAN = 0x0b
|
||||
NRC_DUPNAME = 0x0d
|
||||
NRC_NAMTFUL = 0x0e
|
||||
NRC_ACTSES = 0x0f
|
||||
NRC_LOCTFUL = 0x11
|
||||
NRC_REMTFUL = 0x12
|
||||
NRC_ILLNN = 0x13
|
||||
NRC_NOCALL = 0x14
|
||||
NRC_NOWILD = 0x15
|
||||
NRC_INUSE = 0x16
|
||||
NRC_NAMERR = 0x17
|
||||
NRC_SABORT = 0x18
|
||||
NRC_NAMCONF = 0x19
|
||||
NRC_IFBUSY = 0x21
|
||||
NRC_TOOMANY = 0x22
|
||||
NRC_BRIDGE = 0x23
|
||||
NRC_CANOCCR = 0x24
|
||||
NRC_CANCEL = 0x26
|
||||
NRC_DUPENV = 0x30
|
||||
NRC_ENVNOTDEF = 0x34
|
||||
NRC_OSRESNOTAV = 0x35
|
||||
NRC_MAXAPPS = 0x36
|
||||
NRC_NOSAPS = 0x37
|
||||
NRC_NORESOURCES = 0x38
|
||||
NRC_INVADDRESS = 0x39
|
||||
NRC_INVDDID = 0x3B
|
||||
NRC_LOCKFAIL = 0x3C
|
||||
NRC_OPENERR = 0x3f
|
||||
NRC_SYSTEM = 0x40
|
||||
NRC_PENDING = 0xff
|
||||
|
||||
|
||||
UCHAR = "B"
|
||||
WORD = "H"
|
||||
DWORD = "I"
|
||||
USHORT = "H"
|
||||
ULONG = "I"
|
||||
|
||||
ADAPTER_STATUS_ITEMS = [
|
||||
("6s", "adapter_address"),
|
||||
(UCHAR, "rev_major"),
|
||||
(UCHAR, "reserved0"),
|
||||
(UCHAR, "adapter_type"),
|
||||
(UCHAR, "rev_minor"),
|
||||
(WORD, "duration"),
|
||||
(WORD, "frmr_recv"),
|
||||
(WORD, "frmr_xmit"),
|
||||
|
||||
(WORD, "iframe_recv_err"),
|
||||
|
||||
(WORD, "xmit_aborts"),
|
||||
(DWORD, "xmit_success"),
|
||||
(DWORD, "recv_success"),
|
||||
|
||||
(WORD, "iframe_xmit_err"),
|
||||
|
||||
(WORD, "recv_buff_unavail"),
|
||||
(WORD, "t1_timeouts"),
|
||||
(WORD, "ti_timeouts"),
|
||||
(DWORD, "reserved1"),
|
||||
(WORD, "free_ncbs"),
|
||||
(WORD, "max_cfg_ncbs"),
|
||||
(WORD, "max_ncbs"),
|
||||
(WORD, "xmit_buf_unavail"),
|
||||
(WORD, "max_dgram_size"),
|
||||
(WORD, "pending_sess"),
|
||||
(WORD, "max_cfg_sess"),
|
||||
(WORD, "max_sess"),
|
||||
(WORD, "max_sess_pkt_size"),
|
||||
(WORD, "name_count"),
|
||||
]
|
||||
|
||||
NAME_BUFFER_ITEMS = [
|
||||
(str(NCBNAMSZ) + "s", "name"),
|
||||
(UCHAR, "name_num"),
|
||||
(UCHAR, "name_flags"),
|
||||
]
|
||||
|
||||
SESSION_HEADER_ITEMS = [
|
||||
(UCHAR, "sess_name"),
|
||||
(UCHAR, "num_sess"),
|
||||
(UCHAR, "rcv_dg_outstanding"),
|
||||
(UCHAR, "rcv_any_outstanding"),
|
||||
]
|
||||
|
||||
SESSION_BUFFER_ITEMS = [
|
||||
(UCHAR, "lsn"),
|
||||
(UCHAR, "state"),
|
||||
(str(NCBNAMSZ)+"s", "local_name"),
|
||||
(str(NCBNAMSZ)+"s", "remote_name"),
|
||||
(UCHAR, "rcvs_outstanding"),
|
||||
(UCHAR, "sends_outstanding"),
|
||||
]
|
||||
|
||||
LANA_ENUM_ITEMS = [
|
||||
("B", "length"), # Number of valid entries in lana[]
|
||||
(str(MAX_LANA+1) + "s", "lana"),
|
||||
]
|
||||
|
||||
FIND_NAME_HEADER_ITEMS = [
|
||||
(WORD, "node_count"),
|
||||
(UCHAR, "reserved"),
|
||||
(UCHAR, "unique_group"),
|
||||
]
|
||||
|
||||
FIND_NAME_BUFFER_ITEMS = [
|
||||
(UCHAR, "length"),
|
||||
(UCHAR, "access_control"),
|
||||
(UCHAR, "frame_control"),
|
||||
("6s", "destination_addr"),
|
||||
("6s", "source_addr"),
|
||||
("18s", "routing_info"),
|
||||
]
|
||||
|
||||
ACTION_HEADER_ITEMS = [
|
||||
(ULONG, "transport_id"),
|
||||
(USHORT, "action_code"),
|
||||
(USHORT, "reserved"),
|
||||
]
|
||||
|
||||
del UCHAR, WORD, DWORD, USHORT, ULONG
|
||||
|
||||
NCB = win32wnet.NCB
|
||||
def Netbios(ncb):
|
||||
ob = ncb.Buffer
|
||||
is_ours = hasattr(ob, "_pack")
|
||||
if is_ours:
|
||||
ob._pack()
|
||||
try:
|
||||
return win32wnet.Netbios(ncb)
|
||||
finally:
|
||||
if is_ours:
|
||||
ob._unpack()
|
||||
|
||||
class NCBStruct:
|
||||
def __init__(self, items):
|
||||
self._format = "".join([item[0] for item in items])
|
||||
self._items = items
|
||||
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
|
||||
|
||||
for format, name in self._items:
|
||||
if len(format)==1:
|
||||
if format == 'c':
|
||||
val = '\0'
|
||||
else:
|
||||
val = 0
|
||||
else:
|
||||
l = int(format[:-1])
|
||||
val = '\0' * l
|
||||
self.__dict__[name] = val
|
||||
|
||||
def _pack(self):
|
||||
vals = []
|
||||
for format, name in self._items:
|
||||
try:
|
||||
vals.append(self.__dict__[name])
|
||||
except KeyError:
|
||||
vals.append(None)
|
||||
|
||||
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
|
||||
|
||||
def _unpack(self):
|
||||
items = struct.unpack(self._format, self._buffer_)
|
||||
assert len(items)==len(self._items), "unexpected number of items to unpack!"
|
||||
for (format, name), val in zip(self._items, items):
|
||||
self.__dict__[name] = val
|
||||
|
||||
def __setattr__(self, attr, val):
|
||||
if attr not in self.__dict__ and attr[0]!='_':
|
||||
for format, attr_name in self._items:
|
||||
if attr==attr_name:
|
||||
break
|
||||
else:
|
||||
raise AttributeError(attr)
|
||||
self.__dict__[attr] = val
|
||||
|
||||
def ADAPTER_STATUS():
|
||||
return NCBStruct(ADAPTER_STATUS_ITEMS)
|
||||
|
||||
def NAME_BUFFER():
|
||||
return NCBStruct(NAME_BUFFER_ITEMS)
|
||||
|
||||
def SESSION_HEADER():
|
||||
return NCBStruct(SESSION_HEADER_ITEMS)
|
||||
|
||||
def SESSION_BUFFER():
|
||||
return NCBStruct(SESSION_BUFFER_ITEMS)
|
||||
|
||||
def LANA_ENUM():
|
||||
return NCBStruct(LANA_ENUM_ITEMS)
|
||||
|
||||
def FIND_NAME_HEADER():
|
||||
return NCBStruct(FIND_NAME_HEADER_ITEMS)
|
||||
|
||||
def FIND_NAME_BUFFER():
|
||||
return NCBStruct(FIND_NAME_BUFFER_ITEMS)
|
||||
|
||||
def ACTION_HEADER():
|
||||
return NCBStruct(ACTION_HEADER_ITEMS)
|
||||
|
||||
def byte_to_int(b):
|
||||
"""Given an element in a binary buffer, return its integer value"""
|
||||
if sys.version_info >= (3,0):
|
||||
# a byte is already an int in py3k
|
||||
return b
|
||||
return ord(b) # its a char from a string in py2k.
|
||||
|
||||
if __name__=='__main__':
|
||||
# code ported from "HOWTO: Get the MAC Address for an Ethernet Adapter"
|
||||
# MS KB ID: Q118623
|
||||
ncb = NCB()
|
||||
ncb.Command = NCBENUM
|
||||
la_enum = LANA_ENUM()
|
||||
ncb.Buffer = la_enum
|
||||
rc = Netbios(ncb)
|
||||
if rc != 0: raise RuntimeError("Unexpected result %d" % (rc,))
|
||||
for i in range(la_enum.length):
|
||||
ncb.Reset()
|
||||
ncb.Command = NCBRESET
|
||||
ncb.Lana_num = byte_to_int(la_enum.lana[i])
|
||||
rc = Netbios(ncb)
|
||||
if rc != 0: raise RuntimeError("Unexpected result %d" % (rc,))
|
||||
ncb.Reset()
|
||||
ncb.Command = NCBASTAT
|
||||
ncb.Lana_num = byte_to_int(la_enum.lana[i])
|
||||
ncb.Callname = "* ".encode("ascii") # ensure bytes on py2x and 3k
|
||||
adapter = ADAPTER_STATUS()
|
||||
ncb.Buffer = adapter
|
||||
Netbios(ncb)
|
||||
print("Adapter address:", end=' ')
|
||||
for ch in adapter.adapter_address:
|
||||
print("%02x" % (byte_to_int(ch),), end=' ')
|
||||
print()
|
||||
689
Pywin32/lib/x32/win32/lib/ntsecuritycon.py
Normal file
@@ -0,0 +1,689 @@
|
||||
# Hacked from winnt.h
|
||||
|
||||
DELETE = (65536)
|
||||
READ_CONTROL = (131072)
|
||||
WRITE_DAC = (262144)
|
||||
WRITE_OWNER = (524288)
|
||||
SYNCHRONIZE = (1048576)
|
||||
STANDARD_RIGHTS_REQUIRED = (983040)
|
||||
STANDARD_RIGHTS_READ = (READ_CONTROL)
|
||||
STANDARD_RIGHTS_WRITE = (READ_CONTROL)
|
||||
STANDARD_RIGHTS_EXECUTE = (READ_CONTROL)
|
||||
STANDARD_RIGHTS_ALL = (2031616)
|
||||
SPECIFIC_RIGHTS_ALL = (65535)
|
||||
ACCESS_SYSTEM_SECURITY = (16777216)
|
||||
MAXIMUM_ALLOWED = (33554432)
|
||||
GENERIC_READ = (-2147483648)
|
||||
GENERIC_WRITE = (1073741824)
|
||||
GENERIC_EXECUTE = (536870912)
|
||||
GENERIC_ALL = (268435456)
|
||||
|
||||
# file security permissions
|
||||
FILE_READ_DATA= ( 1 )
|
||||
FILE_LIST_DIRECTORY= ( 1 )
|
||||
FILE_WRITE_DATA= ( 2 )
|
||||
FILE_ADD_FILE= ( 2 )
|
||||
FILE_APPEND_DATA= ( 4 )
|
||||
FILE_ADD_SUBDIRECTORY= ( 4 )
|
||||
FILE_CREATE_PIPE_INSTANCE= ( 4 )
|
||||
FILE_READ_EA= ( 8 )
|
||||
FILE_WRITE_EA= ( 16 )
|
||||
FILE_EXECUTE= ( 32 )
|
||||
FILE_TRAVERSE= ( 32 )
|
||||
FILE_DELETE_CHILD= ( 64 )
|
||||
FILE_READ_ATTRIBUTES= ( 128 )
|
||||
FILE_WRITE_ATTRIBUTES= ( 256 )
|
||||
FILE_ALL_ACCESS= (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 1023)
|
||||
FILE_GENERIC_READ= (STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE)
|
||||
FILE_GENERIC_WRITE= (STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE)
|
||||
FILE_GENERIC_EXECUTE= (STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE)
|
||||
|
||||
|
||||
SECURITY_NULL_SID_AUTHORITY = (0,0,0,0,0,0)
|
||||
SECURITY_WORLD_SID_AUTHORITY = (0,0,0,0,0,1)
|
||||
SECURITY_LOCAL_SID_AUTHORITY = (0,0,0,0,0,2)
|
||||
SECURITY_CREATOR_SID_AUTHORITY = (0,0,0,0,0,3)
|
||||
SECURITY_NON_UNIQUE_AUTHORITY = (0,0,0,0,0,4)
|
||||
SECURITY_RESOURCE_MANAGER_AUTHORITY = (0,0,0,0,0,9)
|
||||
|
||||
SECURITY_NULL_RID = 0
|
||||
SECURITY_WORLD_RID = 0
|
||||
SECURITY_LOCAL_RID = 0X00000000
|
||||
|
||||
SECURITY_CREATOR_OWNER_RID = 0
|
||||
SECURITY_CREATOR_GROUP_RID = 1
|
||||
|
||||
SECURITY_CREATOR_OWNER_SERVER_RID = 2
|
||||
SECURITY_CREATOR_GROUP_SERVER_RID = 3
|
||||
SECURITY_CREATOR_OWNER_RIGHTS_RID = 4
|
||||
|
||||
# NT well-known SIDs
|
||||
SECURITY_NT_AUTHORITY = (0,0,0,0,0,5)
|
||||
|
||||
SECURITY_DIALUP_RID = 1
|
||||
SECURITY_NETWORK_RID = 2
|
||||
SECURITY_BATCH_RID = 3
|
||||
SECURITY_INTERACTIVE_RID = 4
|
||||
SECURITY_SERVICE_RID = 6
|
||||
SECURITY_ANONYMOUS_LOGON_RID = 7
|
||||
SECURITY_PROXY_RID = 8
|
||||
SECURITY_SERVER_LOGON_RID = 9
|
||||
|
||||
SECURITY_LOGON_IDS_RID = 5
|
||||
SECURITY_LOGON_IDS_RID_COUNT = 3
|
||||
|
||||
SECURITY_LOCAL_SYSTEM_RID = 18
|
||||
|
||||
SECURITY_NT_NON_UNIQUE = 21
|
||||
|
||||
SECURITY_BUILTIN_DOMAIN_RID = 32
|
||||
|
||||
# well-known domain relative sub-authority values (RIDs)...
|
||||
DOMAIN_USER_RID_ADMIN = 500
|
||||
DOMAIN_USER_RID_GUEST = 501
|
||||
DOMAIN_USER_RID_KRBTGT = 502
|
||||
DOMAIN_USER_RID_MAX = 999
|
||||
|
||||
# well-known groups ...
|
||||
DOMAIN_GROUP_RID_ADMINS = 512
|
||||
DOMAIN_GROUP_RID_USERS = 513
|
||||
DOMAIN_GROUP_RID_GUESTS = 514
|
||||
DOMAIN_GROUP_RID_COMPUTERS = 515
|
||||
DOMAIN_GROUP_RID_CONTROLLERS = 516
|
||||
DOMAIN_GROUP_RID_CERT_ADMINS = 517
|
||||
DOMAIN_GROUP_RID_SCHEMA_ADMINS = 518
|
||||
DOMAIN_GROUP_RID_ENTERPRISE_ADMINS = 519
|
||||
DOMAIN_GROUP_RID_POLICY_ADMINS = 520
|
||||
DOMAIN_GROUP_RID_READONLY_CONTROLLERS = 521
|
||||
|
||||
# well-known aliases ...
|
||||
DOMAIN_ALIAS_RID_ADMINS = 544
|
||||
DOMAIN_ALIAS_RID_USERS = 545
|
||||
DOMAIN_ALIAS_RID_GUESTS = 546
|
||||
DOMAIN_ALIAS_RID_POWER_USERS = 547
|
||||
DOMAIN_ALIAS_RID_ACCOUNT_OPS = 548
|
||||
DOMAIN_ALIAS_RID_SYSTEM_OPS = 549
|
||||
DOMAIN_ALIAS_RID_PRINT_OPS = 550
|
||||
DOMAIN_ALIAS_RID_BACKUP_OPS = 551
|
||||
DOMAIN_ALIAS_RID_REPLICATOR = 552
|
||||
DOMAIN_ALIAS_RID_RAS_SERVERS = 553
|
||||
DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 554
|
||||
DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 555
|
||||
DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 556
|
||||
DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 557
|
||||
DOMAIN_ALIAS_RID_MONITORING_USERS = 558
|
||||
DOMAIN_ALIAS_RID_LOGGING_USERS = 559
|
||||
DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 560
|
||||
DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 561
|
||||
DOMAIN_ALIAS_RID_DCOM_USERS = 562
|
||||
DOMAIN_ALIAS_RID_IUSERS = 568
|
||||
DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 569
|
||||
DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 571
|
||||
DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 572
|
||||
DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 573
|
||||
|
||||
SECURITY_MANDATORY_LABEL_AUTHORITY = (0,0,0,0,0,16)
|
||||
SECURITY_MANDATORY_UNTRUSTED_RID = 0x00000000
|
||||
SECURITY_MANDATORY_LOW_RID = 0x00001000
|
||||
SECURITY_MANDATORY_MEDIUM_RID = 0x00002000
|
||||
SECURITY_MANDATORY_HIGH_RID = 0x00003000
|
||||
SECURITY_MANDATORY_SYSTEM_RID = 0x00004000
|
||||
SECURITY_MANDATORY_PROTECTED_PROCESS_RID = 0x00005000
|
||||
SECURITY_MANDATORY_MAXIMUM_USER_RID = SECURITY_MANDATORY_SYSTEM_RID
|
||||
|
||||
SYSTEM_LUID = (999, 0)
|
||||
ANONYMOUS_LOGON_LUID = (998, 0)
|
||||
LOCALSERVICE_LUID = (997, 0)
|
||||
NETWORKSERVICE_LUID = (996, 0)
|
||||
IUSER_LUID = (995, 0)
|
||||
|
||||
# Group attributes
|
||||
|
||||
SE_GROUP_MANDATORY = 1
|
||||
SE_GROUP_ENABLED_BY_DEFAULT = 2
|
||||
SE_GROUP_ENABLED = 4
|
||||
SE_GROUP_OWNER = 8
|
||||
SE_GROUP_USE_FOR_DENY_ONLY = 16
|
||||
SE_GROUP_INTEGRITY = 32
|
||||
SE_GROUP_INTEGRITY_ENABLED = 64
|
||||
SE_GROUP_RESOURCE = 536870912
|
||||
SE_GROUP_LOGON_ID = -1073741824
|
||||
|
||||
|
||||
# User attributes
|
||||
# (None yet defined.)
|
||||
|
||||
# ACE types
|
||||
ACCESS_MIN_MS_ACE_TYPE = (0)
|
||||
ACCESS_ALLOWED_ACE_TYPE = (0)
|
||||
ACCESS_DENIED_ACE_TYPE = (1)
|
||||
SYSTEM_AUDIT_ACE_TYPE = (2)
|
||||
SYSTEM_ALARM_ACE_TYPE = (3)
|
||||
ACCESS_MAX_MS_V2_ACE_TYPE = (3)
|
||||
ACCESS_ALLOWED_COMPOUND_ACE_TYPE = (4)
|
||||
ACCESS_MAX_MS_V3_ACE_TYPE = (4)
|
||||
ACCESS_MIN_MS_OBJECT_ACE_TYPE = (5)
|
||||
ACCESS_ALLOWED_OBJECT_ACE_TYPE = (5)
|
||||
ACCESS_DENIED_OBJECT_ACE_TYPE = (6)
|
||||
SYSTEM_AUDIT_OBJECT_ACE_TYPE = (7)
|
||||
SYSTEM_ALARM_OBJECT_ACE_TYPE = (8)
|
||||
ACCESS_MAX_MS_OBJECT_ACE_TYPE = (8)
|
||||
ACCESS_MAX_MS_V4_ACE_TYPE = (8)
|
||||
ACCESS_MAX_MS_ACE_TYPE = (8)
|
||||
ACCESS_ALLOWED_CALLBACK_ACE_TYPE = 9
|
||||
ACCESS_DENIED_CALLBACK_ACE_TYPE = 10
|
||||
ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE = 11
|
||||
ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE = 12
|
||||
SYSTEM_AUDIT_CALLBACK_ACE_TYPE = 13
|
||||
SYSTEM_ALARM_CALLBACK_ACE_TYPE = 14
|
||||
SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE = 15
|
||||
SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE = 16
|
||||
SYSTEM_MANDATORY_LABEL_ACE_TYPE = 17
|
||||
ACCESS_MAX_MS_V5_ACE_TYPE = 17
|
||||
|
||||
# The following are the inherit flags that go into the AceFlags field
|
||||
# of an Ace header.
|
||||
|
||||
OBJECT_INHERIT_ACE = 1
|
||||
CONTAINER_INHERIT_ACE = 2
|
||||
NO_PROPAGATE_INHERIT_ACE = 4
|
||||
INHERIT_ONLY_ACE = 8
|
||||
VALID_INHERIT_FLAGS = 15
|
||||
|
||||
|
||||
SUCCESSFUL_ACCESS_ACE_FLAG = 64
|
||||
FAILED_ACCESS_ACE_FLAG = 128
|
||||
|
||||
SE_OWNER_DEFAULTED = 1
|
||||
SE_GROUP_DEFAULTED = 2
|
||||
SE_DACL_PRESENT = 4
|
||||
SE_DACL_DEFAULTED = 8
|
||||
SE_SACL_PRESENT = 16
|
||||
SE_SACL_DEFAULTED = 32
|
||||
SE_SELF_RELATIVE = 32768
|
||||
|
||||
|
||||
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 1
|
||||
SE_PRIVILEGE_ENABLED = 2
|
||||
SE_PRIVILEGE_USED_FOR_ACCESS = -2147483648
|
||||
|
||||
PRIVILEGE_SET_ALL_NECESSARY = 1
|
||||
|
||||
# NT Defined Privileges
|
||||
|
||||
SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"
|
||||
SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"
|
||||
SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"
|
||||
SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"
|
||||
SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"
|
||||
SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"
|
||||
SE_TCB_NAME = "SeTcbPrivilege"
|
||||
SE_SECURITY_NAME = "SeSecurityPrivilege"
|
||||
SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
|
||||
SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"
|
||||
SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"
|
||||
SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"
|
||||
SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"
|
||||
SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"
|
||||
SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"
|
||||
SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"
|
||||
SE_BACKUP_NAME = "SeBackupPrivilege"
|
||||
SE_RESTORE_NAME = "SeRestorePrivilege"
|
||||
SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
|
||||
SE_DEBUG_NAME = "SeDebugPrivilege"
|
||||
SE_AUDIT_NAME = "SeAuditPrivilege"
|
||||
SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"
|
||||
SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"
|
||||
SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"
|
||||
|
||||
|
||||
# Enum SECURITY_IMPERSONATION_LEVEL:
|
||||
SecurityAnonymous = 0
|
||||
SecurityIdentification = 1
|
||||
SecurityImpersonation = 2
|
||||
SecurityDelegation = 3
|
||||
|
||||
SECURITY_MAX_IMPERSONATION_LEVEL = SecurityDelegation
|
||||
|
||||
DEFAULT_IMPERSONATION_LEVEL = SecurityImpersonation
|
||||
|
||||
TOKEN_ASSIGN_PRIMARY = 1
|
||||
TOKEN_DUPLICATE = 2
|
||||
TOKEN_IMPERSONATE = 4
|
||||
TOKEN_QUERY = 8
|
||||
TOKEN_QUERY_SOURCE = 16
|
||||
TOKEN_ADJUST_PRIVILEGES = 32
|
||||
TOKEN_ADJUST_GROUPS = 64
|
||||
TOKEN_ADJUST_DEFAULT = 128
|
||||
|
||||
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |\
|
||||
TOKEN_ASSIGN_PRIMARY |\
|
||||
TOKEN_DUPLICATE |\
|
||||
TOKEN_IMPERSONATE |\
|
||||
TOKEN_QUERY |\
|
||||
TOKEN_QUERY_SOURCE |\
|
||||
TOKEN_ADJUST_PRIVILEGES |\
|
||||
TOKEN_ADJUST_GROUPS |\
|
||||
TOKEN_ADJUST_DEFAULT)
|
||||
|
||||
|
||||
TOKEN_READ = (STANDARD_RIGHTS_READ |\
|
||||
TOKEN_QUERY)
|
||||
|
||||
|
||||
TOKEN_WRITE = (STANDARD_RIGHTS_WRITE |\
|
||||
TOKEN_ADJUST_PRIVILEGES |\
|
||||
TOKEN_ADJUST_GROUPS |\
|
||||
TOKEN_ADJUST_DEFAULT)
|
||||
|
||||
TOKEN_EXECUTE = (STANDARD_RIGHTS_EXECUTE)
|
||||
|
||||
SidTypeUser = 1
|
||||
SidTypeGroup = 2
|
||||
SidTypeDomain =3
|
||||
SidTypeAlias = 4
|
||||
SidTypeWellKnownGroup = 5
|
||||
SidTypeDeletedAccount = 6
|
||||
SidTypeInvalid = 7
|
||||
SidTypeUnknown = 8
|
||||
SidTypeComputer = 9
|
||||
SidTypeLabel = 10
|
||||
|
||||
# Token types
|
||||
TokenPrimary = 1
|
||||
TokenImpersonation = 2
|
||||
|
||||
# TOKEN_INFORMATION_CLASS, used with Get/SetTokenInformation
|
||||
TokenUser = 1
|
||||
TokenGroups = 2
|
||||
TokenPrivileges = 3
|
||||
TokenOwner = 4
|
||||
TokenPrimaryGroup = 5
|
||||
TokenDefaultDacl = 6
|
||||
TokenSource = 7
|
||||
TokenType = 8
|
||||
TokenImpersonationLevel = 9
|
||||
TokenStatistics = 10
|
||||
TokenRestrictedSids = 11
|
||||
TokenSessionId = 12
|
||||
TokenGroupsAndPrivileges = 13
|
||||
TokenSessionReference = 14
|
||||
TokenSandBoxInert = 15
|
||||
TokenAuditPolicy = 16
|
||||
TokenOrigin = 17
|
||||
TokenElevationType = 18
|
||||
TokenLinkedToken = 19
|
||||
TokenElevation = 20
|
||||
TokenHasRestrictions = 21
|
||||
TokenAccessInformation = 22
|
||||
TokenVirtualizationAllowed = 23
|
||||
TokenVirtualizationEnabled = 24
|
||||
TokenIntegrityLevel = 25
|
||||
TokenUIAccess = 26
|
||||
TokenMandatoryPolicy = 27
|
||||
TokenLogonSid = 28
|
||||
|
||||
# DirectoryService related constants.
|
||||
# Generated by h2py from NtDsAPI.h
|
||||
DS_BEHAVIOR_WIN2000 = 0
|
||||
DS_BEHAVIOR_WIN2003_WITH_MIXED_DOMAINS = 1
|
||||
DS_BEHAVIOR_WIN2003 = 2
|
||||
DS_SYNCED_EVENT_NAME = "NTDSInitialSyncsCompleted"
|
||||
ACTRL_DS_OPEN = 0x00000000
|
||||
ACTRL_DS_CREATE_CHILD = 0x00000001
|
||||
ACTRL_DS_DELETE_CHILD = 0x00000002
|
||||
ACTRL_DS_LIST = 0x00000004
|
||||
ACTRL_DS_SELF = 0x00000008
|
||||
ACTRL_DS_READ_PROP = 0x00000010
|
||||
ACTRL_DS_WRITE_PROP = 0x00000020
|
||||
ACTRL_DS_DELETE_TREE = 0x00000040
|
||||
ACTRL_DS_LIST_OBJECT = 0x00000080
|
||||
ACTRL_DS_CONTROL_ACCESS = 0x00000100
|
||||
NTDSAPI_BIND_ALLOW_DELEGATION = (0x00000001)
|
||||
DS_REPSYNC_ASYNCHRONOUS_OPERATION = 0x00000001
|
||||
DS_REPSYNC_WRITEABLE = 0x00000002
|
||||
DS_REPSYNC_PERIODIC = 0x00000004
|
||||
DS_REPSYNC_INTERSITE_MESSAGING = 0x00000008
|
||||
DS_REPSYNC_ALL_SOURCES = 0x00000010
|
||||
DS_REPSYNC_FULL = 0x00000020
|
||||
DS_REPSYNC_URGENT = 0x00000040
|
||||
DS_REPSYNC_NO_DISCARD = 0x00000080
|
||||
DS_REPSYNC_FORCE = 0x00000100
|
||||
DS_REPSYNC_ADD_REFERENCE = 0x00000200
|
||||
DS_REPSYNC_NEVER_COMPLETED = 0x00000400
|
||||
DS_REPSYNC_TWO_WAY = 0x00000800
|
||||
DS_REPSYNC_NEVER_NOTIFY = 0x00001000
|
||||
DS_REPSYNC_INITIAL = 0x00002000
|
||||
DS_REPSYNC_USE_COMPRESSION = 0x00004000
|
||||
DS_REPSYNC_ABANDONED = 0x00008000
|
||||
DS_REPSYNC_INITIAL_IN_PROGRESS = 0x00010000
|
||||
DS_REPSYNC_PARTIAL_ATTRIBUTE_SET = 0x00020000
|
||||
DS_REPSYNC_REQUEUE = 0x00040000
|
||||
DS_REPSYNC_NOTIFICATION = 0x00080000
|
||||
DS_REPSYNC_ASYNCHRONOUS_REPLICA = 0x00100000
|
||||
DS_REPSYNC_CRITICAL = 0x00200000
|
||||
DS_REPSYNC_FULL_IN_PROGRESS = 0x00400000
|
||||
DS_REPSYNC_PREEMPTED = 0x00800000
|
||||
DS_REPADD_ASYNCHRONOUS_OPERATION = 0x00000001
|
||||
DS_REPADD_WRITEABLE = 0x00000002
|
||||
DS_REPADD_INITIAL = 0x00000004
|
||||
DS_REPADD_PERIODIC = 0x00000008
|
||||
DS_REPADD_INTERSITE_MESSAGING = 0x00000010
|
||||
DS_REPADD_ASYNCHRONOUS_REPLICA = 0x00000020
|
||||
DS_REPADD_DISABLE_NOTIFICATION = 0x00000040
|
||||
DS_REPADD_DISABLE_PERIODIC = 0x00000080
|
||||
DS_REPADD_USE_COMPRESSION = 0x00000100
|
||||
DS_REPADD_NEVER_NOTIFY = 0x00000200
|
||||
DS_REPADD_TWO_WAY = 0x00000400
|
||||
DS_REPADD_CRITICAL = 0x00000800
|
||||
DS_REPDEL_ASYNCHRONOUS_OPERATION = 0x00000001
|
||||
DS_REPDEL_WRITEABLE = 0x00000002
|
||||
DS_REPDEL_INTERSITE_MESSAGING = 0x00000004
|
||||
DS_REPDEL_IGNORE_ERRORS = 0x00000008
|
||||
DS_REPDEL_LOCAL_ONLY = 0x00000010
|
||||
DS_REPDEL_NO_SOURCE = 0x00000020
|
||||
DS_REPDEL_REF_OK = 0x00000040
|
||||
DS_REPMOD_ASYNCHRONOUS_OPERATION = 0x00000001
|
||||
DS_REPMOD_WRITEABLE = 0x00000002
|
||||
DS_REPMOD_UPDATE_FLAGS = 0x00000001
|
||||
DS_REPMOD_UPDATE_ADDRESS = 0x00000002
|
||||
DS_REPMOD_UPDATE_SCHEDULE = 0x00000004
|
||||
DS_REPMOD_UPDATE_RESULT = 0x00000008
|
||||
DS_REPMOD_UPDATE_TRANSPORT = 0x00000010
|
||||
DS_REPUPD_ASYNCHRONOUS_OPERATION = 0x00000001
|
||||
DS_REPUPD_WRITEABLE = 0x00000002
|
||||
DS_REPUPD_ADD_REFERENCE = 0x00000004
|
||||
DS_REPUPD_DELETE_REFERENCE = 0x00000008
|
||||
DS_INSTANCETYPE_IS_NC_HEAD = 0x00000001
|
||||
DS_INSTANCETYPE_NC_IS_WRITEABLE = 0x00000004
|
||||
DS_INSTANCETYPE_NC_COMING = 0x00000010
|
||||
DS_INSTANCETYPE_NC_GOING = 0x00000020
|
||||
NTDSDSA_OPT_IS_GC = ( 1 << 0 )
|
||||
NTDSDSA_OPT_DISABLE_INBOUND_REPL = ( 1 << 1 )
|
||||
NTDSDSA_OPT_DISABLE_OUTBOUND_REPL = ( 1 << 2 )
|
||||
NTDSDSA_OPT_DISABLE_NTDSCONN_XLATE = ( 1 << 3 )
|
||||
NTDSCONN_OPT_IS_GENERATED = ( 1 << 0 )
|
||||
NTDSCONN_OPT_TWOWAY_SYNC = ( 1 << 1 )
|
||||
NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT = (1 << 2 )
|
||||
NTDSCONN_OPT_USE_NOTIFY = (1 << 3)
|
||||
NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION = (1 << 4)
|
||||
NTDSCONN_OPT_USER_OWNED_SCHEDULE = (1 << 5)
|
||||
NTDSCONN_KCC_NO_REASON = ( 0 )
|
||||
NTDSCONN_KCC_GC_TOPOLOGY = ( 1 << 0 )
|
||||
NTDSCONN_KCC_RING_TOPOLOGY = ( 1 << 1 )
|
||||
NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY = ( 1 << 2 )
|
||||
NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY = ( 1 << 3 )
|
||||
NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY = ( 1 << 4 )
|
||||
NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY = (1 << 5)
|
||||
NTDSCONN_KCC_INTERSITE_TOPOLOGY = (1 << 6)
|
||||
NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY = (1 << 7)
|
||||
NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY = (1 << 8)
|
||||
NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY = (1 << 9)
|
||||
FRSCONN_PRIORITY_MASK = 0x70000000
|
||||
FRSCONN_MAX_PRIORITY = 0x8
|
||||
NTDSCONN_OPT_IGNORE_SCHEDULE_MASK = (-2147483648)
|
||||
|
||||
NTDSSETTINGS_OPT_IS_AUTO_TOPOLOGY_DISABLED = ( 1 << 0 )
|
||||
NTDSSETTINGS_OPT_IS_TOPL_CLEANUP_DISABLED = ( 1 << 1 )
|
||||
NTDSSETTINGS_OPT_IS_TOPL_MIN_HOPS_DISABLED = ( 1 << 2 )
|
||||
NTDSSETTINGS_OPT_IS_TOPL_DETECT_STALE_DISABLED = ( 1 << 3 )
|
||||
NTDSSETTINGS_OPT_IS_INTER_SITE_AUTO_TOPOLOGY_DISABLED = ( 1 << 4 )
|
||||
NTDSSETTINGS_OPT_IS_GROUP_CACHING_ENABLED = ( 1 << 5 )
|
||||
NTDSSETTINGS_OPT_FORCE_KCC_WHISTLER_BEHAVIOR = ( 1 << 6 )
|
||||
NTDSSETTINGS_OPT_FORCE_KCC_W2K_ELECTION = ( 1 << 7 )
|
||||
NTDSSETTINGS_OPT_IS_RAND_BH_SELECTION_DISABLED = ( 1 << 8 )
|
||||
NTDSSETTINGS_OPT_IS_SCHEDULE_HASHING_ENABLED = ( 1 << 9 )
|
||||
NTDSSETTINGS_OPT_IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED = ( 1 << 10 )
|
||||
NTDSSETTINGS_DEFAULT_SERVER_REDUNDANCY = 2
|
||||
NTDSTRANSPORT_OPT_IGNORE_SCHEDULES = ( 1 << 0 )
|
||||
NTDSTRANSPORT_OPT_BRIDGES_REQUIRED = (1 << 1 )
|
||||
NTDSSITECONN_OPT_USE_NOTIFY = ( 1 << 0 )
|
||||
NTDSSITECONN_OPT_TWOWAY_SYNC = ( 1 << 1 )
|
||||
NTDSSITECONN_OPT_DISABLE_COMPRESSION = ( 1 << 2 )
|
||||
NTDSSITELINK_OPT_USE_NOTIFY = ( 1 << 0 )
|
||||
NTDSSITELINK_OPT_TWOWAY_SYNC = ( 1 << 1 )
|
||||
NTDSSITELINK_OPT_DISABLE_COMPRESSION = ( 1 << 2 )
|
||||
GUID_USERS_CONTAINER_A = "a9d1ca15768811d1aded00c04fd8d5cd"
|
||||
GUID_COMPUTRS_CONTAINER_A = "aa312825768811d1aded00c04fd8d5cd"
|
||||
GUID_SYSTEMS_CONTAINER_A = "ab1d30f3768811d1aded00c04fd8d5cd"
|
||||
GUID_DOMAIN_CONTROLLERS_CONTAINER_A = "a361b2ffffd211d1aa4b00c04fd7d83a"
|
||||
GUID_INFRASTRUCTURE_CONTAINER_A = "2fbac1870ade11d297c400c04fd8d5cd"
|
||||
GUID_DELETED_OBJECTS_CONTAINER_A = "18e2ea80684f11d2b9aa00c04f79f805"
|
||||
GUID_LOSTANDFOUND_CONTAINER_A = "ab8153b7768811d1aded00c04fd8d5cd"
|
||||
GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_A = "22b70c67d56e4efb91e9300fca3dc1aa"
|
||||
GUID_PROGRAM_DATA_CONTAINER_A = "09460c08ae1e4a4ea0f64aee7daa1e5a"
|
||||
GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_A = "f4be92a4c777485e878e9421d53087db"
|
||||
GUID_NTDS_QUOTAS_CONTAINER_A = "6227f0af1fc2410d8e3bb10615bb5b0f"
|
||||
GUID_USERS_CONTAINER_BYTE = "\xa9\xd1\xca\x15\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
|
||||
GUID_COMPUTRS_CONTAINER_BYTE = "\xaa\x31\x28\x25\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
|
||||
GUID_SYSTEMS_CONTAINER_BYTE = "\xab\x1d\x30\xf3\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
|
||||
GUID_DOMAIN_CONTROLLERS_CONTAINER_BYTE = "\xa3\x61\xb2\xff\xff\xd2\x11\xd1\xaa\x4b\x00\xc0\x4f\xd7\xd8\x3a"
|
||||
GUID_INFRASTRUCTURE_CONTAINER_BYTE = "\x2f\xba\xc1\x87\x0a\xde\x11\xd2\x97\xc4\x00\xc0\x4f\xd8\xd5\xcd"
|
||||
GUID_DELETED_OBJECTS_CONTAINER_BYTE = "\x18\xe2\xea\x80\x68\x4f\x11\xd2\xb9\xaa\x00\xc0\x4f\x79\xf8\x05"
|
||||
GUID_LOSTANDFOUND_CONTAINER_BYTE = "\xab\x81\x53\xb7\x76\x88\x11\xd1\xad\xed\x00\xc0\x4f\xd8\xd5\xcd"
|
||||
GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = "\x22\xb7\x0c\x67\xd5\x6e\x4e\xfb\x91\xe9\x30\x0f\xca\x3d\xc1\xaa"
|
||||
GUID_PROGRAM_DATA_CONTAINER_BYTE = "\x09\x46\x0c\x08\xae\x1e\x4a\x4e\xa0\xf6\x4a\xee\x7d\xaa\x1e\x5a"
|
||||
GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_BYTE = "\xf4\xbe\x92\xa4\xc7\x77\x48\x5e\x87\x8e\x94\x21\xd5\x30\x87\xdb"
|
||||
GUID_NTDS_QUOTAS_CONTAINER_BYTE = "\x62\x27\xf0\xaf\x1f\xc2\x41\x0d\x8e\x3b\xb1\x06\x15\xbb\x5b\x0f"
|
||||
DS_REPSYNCALL_NO_OPTIONS = 0x00000000
|
||||
DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE = 0x00000001
|
||||
DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY = 0x00000002
|
||||
DS_REPSYNCALL_ID_SERVERS_BY_DN = 0x00000004
|
||||
DS_REPSYNCALL_DO_NOT_SYNC = 0x00000008
|
||||
DS_REPSYNCALL_SKIP_INITIAL_CHECK = 0x00000010
|
||||
DS_REPSYNCALL_PUSH_CHANGES_OUTWARD = 0x00000020
|
||||
DS_REPSYNCALL_CROSS_SITE_BOUNDARIES = 0x00000040
|
||||
DS_LIST_DSA_OBJECT_FOR_SERVER = 0
|
||||
DS_LIST_DNS_HOST_NAME_FOR_SERVER = 1
|
||||
DS_LIST_ACCOUNT_OBJECT_FOR_SERVER = 2
|
||||
DS_ROLE_SCHEMA_OWNER = 0
|
||||
DS_ROLE_DOMAIN_OWNER = 1
|
||||
DS_ROLE_PDC_OWNER = 2
|
||||
DS_ROLE_RID_OWNER = 3
|
||||
DS_ROLE_INFRASTRUCTURE_OWNER = 4
|
||||
DS_SCHEMA_GUID_NOT_FOUND = 0
|
||||
DS_SCHEMA_GUID_ATTR = 1
|
||||
DS_SCHEMA_GUID_ATTR_SET = 2
|
||||
DS_SCHEMA_GUID_CLASS = 3
|
||||
DS_SCHEMA_GUID_CONTROL_RIGHT = 4
|
||||
DS_KCC_FLAG_ASYNC_OP = (1 << 0)
|
||||
DS_KCC_FLAG_DAMPED = (1 << 1)
|
||||
DS_EXIST_ADVISORY_MODE = (0x1)
|
||||
DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS = (0x00000001)
|
||||
DS_REPL_NBR_WRITEABLE = (0x00000010)
|
||||
DS_REPL_NBR_SYNC_ON_STARTUP = (0x00000020)
|
||||
DS_REPL_NBR_DO_SCHEDULED_SYNCS = (0x00000040)
|
||||
DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT = (0x00000080)
|
||||
DS_REPL_NBR_TWO_WAY_SYNC = (0x00000200)
|
||||
DS_REPL_NBR_RETURN_OBJECT_PARENTS = (0x00000800)
|
||||
DS_REPL_NBR_FULL_SYNC_IN_PROGRESS = (0x00010000)
|
||||
DS_REPL_NBR_FULL_SYNC_NEXT_PACKET = (0x00020000)
|
||||
DS_REPL_NBR_NEVER_SYNCED = (0x00200000)
|
||||
DS_REPL_NBR_PREEMPTED = (0x01000000)
|
||||
DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS = (0x04000000)
|
||||
DS_REPL_NBR_DISABLE_SCHEDULED_SYNC = (0x08000000)
|
||||
DS_REPL_NBR_COMPRESS_CHANGES = (0x10000000)
|
||||
DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS = (0x20000000)
|
||||
DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET = (0x40000000)
|
||||
DS_REPL_NBR_MODIFIABLE_MASK = \
|
||||
( \
|
||||
DS_REPL_NBR_SYNC_ON_STARTUP | \
|
||||
DS_REPL_NBR_DO_SCHEDULED_SYNCS | \
|
||||
DS_REPL_NBR_TWO_WAY_SYNC | \
|
||||
DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS | \
|
||||
DS_REPL_NBR_DISABLE_SCHEDULED_SYNC | \
|
||||
DS_REPL_NBR_COMPRESS_CHANGES | \
|
||||
DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS \
|
||||
)
|
||||
|
||||
# from enum DS_NAME_FORMAT
|
||||
DS_UNKNOWN_NAME = 0
|
||||
DS_FQDN_1779_NAME = 1
|
||||
DS_NT4_ACCOUNT_NAME = 2
|
||||
DS_DISPLAY_NAME = 3
|
||||
DS_UNIQUE_ID_NAME = 6
|
||||
DS_CANONICAL_NAME = 7
|
||||
DS_USER_PRINCIPAL_NAME = 8
|
||||
DS_CANONICAL_NAME_EX = 9
|
||||
DS_SERVICE_PRINCIPAL_NAME = 10
|
||||
DS_SID_OR_SID_HISTORY_NAME = 11
|
||||
DS_DNS_DOMAIN_NAME = 12
|
||||
|
||||
DS_DOMAIN_SIMPLE_NAME = DS_USER_PRINCIPAL_NAME
|
||||
DS_ENTERPRISE_SIMPLE_NAME = DS_USER_PRINCIPAL_NAME
|
||||
|
||||
# from enum DS_NAME_FLAGS
|
||||
DS_NAME_NO_FLAGS = 0x0
|
||||
DS_NAME_FLAG_SYNTACTICAL_ONLY = 0x1
|
||||
DS_NAME_FLAG_EVAL_AT_DC = 0x2
|
||||
DS_NAME_FLAG_GCVERIFY = 0x4
|
||||
DS_NAME_FLAG_TRUST_REFERRAL = 0x8
|
||||
|
||||
# from enum DS_NAME_ERROR
|
||||
DS_NAME_NO_ERROR = 0
|
||||
DS_NAME_ERROR_RESOLVING = 1
|
||||
DS_NAME_ERROR_NOT_FOUND = 2
|
||||
DS_NAME_ERROR_NOT_UNIQUE = 3
|
||||
DS_NAME_ERROR_NO_MAPPING = 4
|
||||
DS_NAME_ERROR_DOMAIN_ONLY = 5
|
||||
DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = 6
|
||||
DS_NAME_ERROR_TRUST_REFERRAL = 7
|
||||
|
||||
|
||||
# from enum DS_SPN_NAME_TYPE
|
||||
DS_SPN_DNS_HOST = 0
|
||||
DS_SPN_DN_HOST = 1
|
||||
DS_SPN_NB_HOST = 2
|
||||
DS_SPN_DOMAIN = 3
|
||||
DS_SPN_NB_DOMAIN = 4
|
||||
DS_SPN_SERVICE = 5
|
||||
|
||||
# from enum DS_SPN_WRITE_OP
|
||||
DS_SPN_ADD_SPN_OP = 0
|
||||
DS_SPN_REPLACE_SPN_OP = 1
|
||||
DS_SPN_DELETE_SPN_OP = 2
|
||||
|
||||
# Generated by h2py from DsGetDC.h
|
||||
DS_FORCE_REDISCOVERY = 0x00000001
|
||||
DS_DIRECTORY_SERVICE_REQUIRED = 0x00000010
|
||||
DS_DIRECTORY_SERVICE_PREFERRED = 0x00000020
|
||||
DS_GC_SERVER_REQUIRED = 0x00000040
|
||||
DS_PDC_REQUIRED = 0x00000080
|
||||
DS_BACKGROUND_ONLY = 0x00000100
|
||||
DS_IP_REQUIRED = 0x00000200
|
||||
DS_KDC_REQUIRED = 0x00000400
|
||||
DS_TIMESERV_REQUIRED = 0x00000800
|
||||
DS_WRITABLE_REQUIRED = 0x00001000
|
||||
DS_GOOD_TIMESERV_PREFERRED = 0x00002000
|
||||
DS_AVOID_SELF = 0x00004000
|
||||
DS_ONLY_LDAP_NEEDED = 0x00008000
|
||||
DS_IS_FLAT_NAME = 0x00010000
|
||||
DS_IS_DNS_NAME = 0x00020000
|
||||
DS_RETURN_DNS_NAME = 0x40000000
|
||||
DS_RETURN_FLAT_NAME = (-2147483648)
|
||||
DSGETDC_VALID_FLAGS = ( \
|
||||
DS_FORCE_REDISCOVERY | \
|
||||
DS_DIRECTORY_SERVICE_REQUIRED | \
|
||||
DS_DIRECTORY_SERVICE_PREFERRED | \
|
||||
DS_GC_SERVER_REQUIRED | \
|
||||
DS_PDC_REQUIRED | \
|
||||
DS_BACKGROUND_ONLY | \
|
||||
DS_IP_REQUIRED | \
|
||||
DS_KDC_REQUIRED | \
|
||||
DS_TIMESERV_REQUIRED | \
|
||||
DS_WRITABLE_REQUIRED | \
|
||||
DS_GOOD_TIMESERV_PREFERRED | \
|
||||
DS_AVOID_SELF | \
|
||||
DS_ONLY_LDAP_NEEDED | \
|
||||
DS_IS_FLAT_NAME | \
|
||||
DS_IS_DNS_NAME | \
|
||||
DS_RETURN_FLAT_NAME | \
|
||||
DS_RETURN_DNS_NAME )
|
||||
DS_INET_ADDRESS = 1
|
||||
DS_NETBIOS_ADDRESS = 2
|
||||
DS_PDC_FLAG = 0x00000001
|
||||
DS_GC_FLAG = 0x00000004
|
||||
DS_LDAP_FLAG = 0x00000008
|
||||
DS_DS_FLAG = 0x00000010
|
||||
DS_KDC_FLAG = 0x00000020
|
||||
DS_TIMESERV_FLAG = 0x00000040
|
||||
DS_CLOSEST_FLAG = 0x00000080
|
||||
DS_WRITABLE_FLAG = 0x00000100
|
||||
DS_GOOD_TIMESERV_FLAG = 0x00000200
|
||||
DS_NDNC_FLAG = 0x00000400
|
||||
DS_PING_FLAGS = 0x0000FFFF
|
||||
DS_DNS_CONTROLLER_FLAG = 0x20000000
|
||||
DS_DNS_DOMAIN_FLAG = 0x40000000
|
||||
DS_DNS_FOREST_FLAG = (-2147483648)
|
||||
DS_DOMAIN_IN_FOREST = 0x0001
|
||||
DS_DOMAIN_DIRECT_OUTBOUND = 0x0002
|
||||
DS_DOMAIN_TREE_ROOT = 0x0004
|
||||
DS_DOMAIN_PRIMARY = 0x0008
|
||||
DS_DOMAIN_NATIVE_MODE = 0x0010
|
||||
DS_DOMAIN_DIRECT_INBOUND = 0x0020
|
||||
DS_DOMAIN_VALID_FLAGS = ( \
|
||||
DS_DOMAIN_IN_FOREST | \
|
||||
DS_DOMAIN_DIRECT_OUTBOUND | \
|
||||
DS_DOMAIN_TREE_ROOT | \
|
||||
DS_DOMAIN_PRIMARY | \
|
||||
DS_DOMAIN_NATIVE_MODE | \
|
||||
DS_DOMAIN_DIRECT_INBOUND )
|
||||
DS_GFTI_UPDATE_TDO = 0x1
|
||||
DS_GFTI_VALID_FLAGS = 0x1
|
||||
DS_ONLY_DO_SITE_NAME = 0x01
|
||||
DS_NOTIFY_AFTER_SITE_RECORDS = 0x02
|
||||
DS_OPEN_VALID_OPTION_FLAGS = ( DS_ONLY_DO_SITE_NAME | DS_NOTIFY_AFTER_SITE_RECORDS )
|
||||
DS_OPEN_VALID_FLAGS = ( \
|
||||
DS_FORCE_REDISCOVERY | \
|
||||
DS_ONLY_LDAP_NEEDED | \
|
||||
DS_KDC_REQUIRED | \
|
||||
DS_PDC_REQUIRED | \
|
||||
DS_GC_SERVER_REQUIRED | \
|
||||
DS_WRITABLE_REQUIRED )
|
||||
|
||||
## from aclui.h
|
||||
# SI_OBJECT_INFO.dwFlags
|
||||
SI_EDIT_PERMS = 0x00000000
|
||||
SI_EDIT_OWNER = 0x00000001
|
||||
SI_EDIT_AUDITS = 0x00000002
|
||||
SI_CONTAINER = 0x00000004
|
||||
SI_READONLY = 0x00000008
|
||||
SI_ADVANCED = 0x00000010
|
||||
SI_RESET = 0x00000020
|
||||
SI_OWNER_READONLY = 0x00000040
|
||||
SI_EDIT_PROPERTIES = 0x00000080
|
||||
SI_OWNER_RECURSE = 0x00000100
|
||||
SI_NO_ACL_PROTECT = 0x00000200
|
||||
SI_NO_TREE_APPLY = 0x00000400
|
||||
SI_PAGE_TITLE = 0x00000800
|
||||
SI_SERVER_IS_DC = 0x00001000
|
||||
SI_RESET_DACL_TREE = 0x00004000
|
||||
SI_RESET_SACL_TREE = 0x00008000
|
||||
SI_OBJECT_GUID = 0x00010000
|
||||
SI_EDIT_EFFECTIVE = 0x00020000
|
||||
SI_RESET_DACL = 0x00040000
|
||||
SI_RESET_SACL = 0x00080000
|
||||
SI_RESET_OWNER = 0x00100000
|
||||
SI_NO_ADDITIONAL_PERMISSION = 0x00200000
|
||||
SI_MAY_WRITE = 0x10000000
|
||||
SI_EDIT_ALL = (SI_EDIT_PERMS | SI_EDIT_OWNER | SI_EDIT_AUDITS)
|
||||
SI_AUDITS_ELEVATION_REQUIRED = 0x02000000
|
||||
SI_VIEW_ONLY = 0x00400000
|
||||
SI_OWNER_ELEVATION_REQUIRED = 0x04000000
|
||||
SI_PERMS_ELEVATION_REQUIRED = 0x01000000
|
||||
|
||||
# SI_ACCESS.dwFlags
|
||||
SI_ACCESS_SPECIFIC = 0x00010000
|
||||
SI_ACCESS_GENERAL = 0x00020000
|
||||
SI_ACCESS_CONTAINER = 0x00040000
|
||||
SI_ACCESS_PROPERTY = 0x00080000
|
||||
|
||||
# SI_PAGE_TYPE enum
|
||||
SI_PAGE_PERM = 0
|
||||
SI_PAGE_ADVPERM = 1
|
||||
SI_PAGE_AUDIT = 2
|
||||
SI_PAGE_OWNER = 3
|
||||
SI_PAGE_EFFECTIVE =4
|
||||
|
||||
CFSTR_ACLUI_SID_INFO_LIST = "CFSTR_ACLUI_SID_INFO_LIST"
|
||||
PSPCB_SI_INITDIALOG = 1025 ## WM_USER+1
|
||||
270
Pywin32/lib/x32/win32/lib/pywin32_testutil.py
Normal file
@@ -0,0 +1,270 @@
|
||||
# Utilities for the pywin32 tests
|
||||
import sys
|
||||
import unittest
|
||||
import gc
|
||||
import winerror
|
||||
|
||||
##
|
||||
## General purpose utilities for the test suite.
|
||||
##
|
||||
|
||||
def int2long(val):
|
||||
"""return a long on py2k"""
|
||||
return val + 0x100000000 - 0x100000000
|
||||
|
||||
# The test suite has lots of string constants containing binary data, but
|
||||
# the strings are used in various "bytes" contexts.
|
||||
def str2bytes(sval):
|
||||
if sys.version_info < (3,0) and isinstance(sval, str):
|
||||
sval = sval.decode("latin1")
|
||||
return sval.encode("latin1")
|
||||
|
||||
|
||||
# Sometimes we want to pass a string that should explicitly be treated as
|
||||
# a memory blob.
|
||||
def str2memory(sval):
|
||||
if sys.version_info < (3,0):
|
||||
return buffer(sval)
|
||||
# py3k.
|
||||
return memoryview(sval.encode("latin1"))
|
||||
|
||||
|
||||
# Sometimes we want to pass an object that exposes its memory
|
||||
def ob2memory(ob):
|
||||
if sys.version_info < (3,0):
|
||||
return buffer(ob)
|
||||
# py3k.
|
||||
return memoryview(ob)
|
||||
|
||||
|
||||
# Note: no str2unicode: we use u'' literals or unicode() function, and 2to3
|
||||
#
|
||||
|
||||
##
|
||||
## unittest related stuff
|
||||
##
|
||||
|
||||
# This is a specialized TestCase adaptor which wraps a real test.
|
||||
class LeakTestCase(unittest.TestCase):
|
||||
"""An 'adaptor' which takes another test. In debug builds we execute the
|
||||
test once to remove one-off side-effects, then capture the total
|
||||
reference count, then execute the test a few times. If the total
|
||||
refcount at the end is greater than we first captured, we have a leak!
|
||||
|
||||
In release builds the test is executed just once, as normal.
|
||||
|
||||
Generally used automatically by the test runner - you can safely
|
||||
ignore this.
|
||||
"""
|
||||
def __init__(self, real_test):
|
||||
unittest.TestCase.__init__(self)
|
||||
self.real_test = real_test
|
||||
self.num_test_cases = 1
|
||||
self.num_leak_iters = 2 # seems to be enough!
|
||||
if hasattr(sys, "gettotalrefcount"):
|
||||
self.num_test_cases = self.num_test_cases + self.num_leak_iters
|
||||
|
||||
def countTestCases(self):
|
||||
return self.num_test_cases
|
||||
|
||||
def __call__(self, result = None):
|
||||
# For the COM suite's sake, always ensure we don't leak
|
||||
# gateways/interfaces
|
||||
from pythoncom import _GetInterfaceCount, _GetGatewayCount
|
||||
gc.collect()
|
||||
ni = _GetInterfaceCount()
|
||||
ng = _GetGatewayCount()
|
||||
self.real_test(result)
|
||||
# Failed - no point checking anything else
|
||||
if result.shouldStop or not result.wasSuccessful():
|
||||
return
|
||||
self._do_leak_tests(result)
|
||||
gc.collect()
|
||||
lost_i = _GetInterfaceCount() - ni
|
||||
lost_g = _GetGatewayCount() - ng
|
||||
if lost_i or lost_g:
|
||||
msg = "%d interface objects and %d gateway objects leaked" \
|
||||
% (lost_i, lost_g)
|
||||
exc = AssertionError(msg)
|
||||
result.addFailure(self.real_test, (exc.__class__, exc, None))
|
||||
|
||||
def runTest(self):
|
||||
assert 0, "not used"
|
||||
|
||||
def _do_leak_tests(self, result = None):
|
||||
try:
|
||||
gtrc = sys.gettotalrefcount
|
||||
except AttributeError:
|
||||
return # can't do leak tests in this build
|
||||
# Assume already called once, to prime any caches etc
|
||||
gc.collect()
|
||||
trc = gtrc()
|
||||
for i in range(self.num_leak_iters):
|
||||
self.real_test(result)
|
||||
if result.shouldStop:
|
||||
break
|
||||
del i # created after we remembered the refcount!
|
||||
# int division here means one or 2 stray references won't force
|
||||
# failure, but one per loop
|
||||
gc.collect()
|
||||
lost = (gtrc() - trc) // self.num_leak_iters
|
||||
if lost < 0:
|
||||
msg = "LeakTest: %s appeared to gain %d references!!" % (self.real_test, -lost)
|
||||
result.addFailure(self.real_test, (AssertionError, msg, None))
|
||||
if lost > 0:
|
||||
msg = "LeakTest: %s lost %d references" % (self.real_test, lost)
|
||||
exc = AssertionError(msg)
|
||||
result.addFailure(self.real_test, (exc.__class__, exc, None))
|
||||
|
||||
|
||||
class TestLoader(unittest.TestLoader):
|
||||
def loadTestsFromTestCase(self, testCaseClass):
|
||||
"""Return a suite of all tests cases contained in testCaseClass"""
|
||||
leak_tests = []
|
||||
for name in self.getTestCaseNames(testCaseClass):
|
||||
real_test = testCaseClass(name)
|
||||
leak_test = self._getTestWrapper(real_test)
|
||||
leak_tests.append(leak_test)
|
||||
return self.suiteClass(leak_tests)
|
||||
|
||||
def fixupTestsForLeakTests(self, test):
|
||||
if isinstance(test, unittest.TestSuite):
|
||||
test._tests = [self.fixupTestsForLeakTests(t) for t in test._tests]
|
||||
return test
|
||||
else:
|
||||
# just a normal test case.
|
||||
return self._getTestWrapper(test)
|
||||
|
||||
def _getTestWrapper(self, test):
|
||||
# one or 2 tests in the COM test suite set this...
|
||||
no_leak_tests = getattr(test, "no_leak_tests", False)
|
||||
if no_leak_tests:
|
||||
print("Test says it doesn't want leak tests!")
|
||||
return test
|
||||
return LeakTestCase(test)
|
||||
|
||||
def loadTestsFromModule(self, mod):
|
||||
if hasattr(mod, "suite"):
|
||||
tests = mod.suite()
|
||||
else:
|
||||
tests = unittest.TestLoader.loadTestsFromModule(self, mod)
|
||||
return self.fixupTestsForLeakTests(tests)
|
||||
|
||||
def loadTestsFromName(self, name, module=None):
|
||||
test = unittest.TestLoader.loadTestsFromName(self, name, module)
|
||||
if isinstance(test, unittest.TestSuite):
|
||||
pass # hmmm? print "Don't wrap suites yet!", test._tests
|
||||
elif isinstance(test, unittest.TestCase):
|
||||
test = self._getTestWrapper(test)
|
||||
else:
|
||||
print("XXX - what is", test)
|
||||
return test
|
||||
|
||||
# Lots of classes necessary to support one simple feature: we want a 3rd
|
||||
# test result state - "SKIPPED" - to indicate that the test wasn't able
|
||||
# to be executed for various reasons. Inspired by bzr's tests, but it
|
||||
# has other concepts, such as "Expected Failure", which we don't bother
|
||||
# with.
|
||||
|
||||
# win32 error codes that probably mean we need to be elevated (ie, if we
|
||||
# aren't elevated, we treat these error codes as 'skipped')
|
||||
non_admin_error_codes = [winerror.ERROR_ACCESS_DENIED,
|
||||
winerror.ERROR_PRIVILEGE_NOT_HELD]
|
||||
|
||||
_is_admin = None
|
||||
def check_is_admin():
|
||||
global _is_admin
|
||||
if _is_admin is None:
|
||||
from win32com.shell.shell import IsUserAnAdmin
|
||||
import pythoncom
|
||||
try:
|
||||
_is_admin = IsUserAnAdmin()
|
||||
except pythoncom.com_error as exc:
|
||||
if exc.hresult != winerror.E_NOTIMPL:
|
||||
raise
|
||||
# not impl on this platform - must be old - assume is admin
|
||||
_is_admin = True
|
||||
return _is_admin
|
||||
|
||||
|
||||
# If this exception is raised by a test, the test is reported as a 'skip'
|
||||
class TestSkipped(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# The 'TestResult' subclass that records the failures and has the special
|
||||
# handling for the TestSkipped exception.
|
||||
class TestResult(unittest._TextTestResult):
|
||||
def __init__(self, *args, **kw):
|
||||
super(TestResult, self).__init__(*args, **kw)
|
||||
self.skips = {} # count of skips for each reason.
|
||||
|
||||
def addError(self, test, err):
|
||||
"""Called when an error has occurred. 'err' is a tuple of values as
|
||||
returned by sys.exc_info().
|
||||
"""
|
||||
# translate a couple of 'well-known' exceptions into 'skipped'
|
||||
import pywintypes
|
||||
exc_val = err[1]
|
||||
# translate ERROR_ACCESS_DENIED for non-admin users to be skipped.
|
||||
# (access denied errors for an admin user aren't expected.)
|
||||
if isinstance(exc_val, pywintypes.error) \
|
||||
and exc_val.winerror in non_admin_error_codes \
|
||||
and not check_is_admin():
|
||||
exc_val = TestSkipped(exc_val)
|
||||
# and COM errors due to objects not being registered (the com test
|
||||
# suite will attempt to catch this and handle it itself if the user
|
||||
# is admin)
|
||||
elif isinstance(exc_val, pywintypes.com_error) and \
|
||||
exc_val.hresult in [winerror.CO_E_CLASSSTRING,
|
||||
winerror.REGDB_E_CLASSNOTREG,
|
||||
winerror.TYPE_E_LIBNOTREGISTERED]:
|
||||
exc_val = TestSkipped(exc_val)
|
||||
# NotImplemented generally means the platform doesn't support the
|
||||
# functionality.
|
||||
elif isinstance(exc_val, NotImplementedError):
|
||||
exc_val = TestSkipped(NotImplementedError)
|
||||
|
||||
if isinstance(exc_val, TestSkipped):
|
||||
reason = exc_val.args[0]
|
||||
# if the reason itself is another exception, get its args.
|
||||
try:
|
||||
reason = tuple(reason.args)
|
||||
except (AttributeError, TypeError):
|
||||
pass
|
||||
self.skips.setdefault(reason, 0)
|
||||
self.skips[reason] += 1
|
||||
if self.showAll:
|
||||
self.stream.writeln("SKIP (%s)" % (reason,))
|
||||
elif self.dots:
|
||||
self.stream.write('S')
|
||||
self.stream.flush()
|
||||
return
|
||||
super(TestResult, self).addError(test, err)
|
||||
|
||||
def printErrors(self):
|
||||
super(TestResult, self).printErrors()
|
||||
for reason, num_skipped in self.skips.items():
|
||||
self.stream.writeln("SKIPPED: %d tests - %s" % (num_skipped, reason))
|
||||
|
||||
# TestRunner subclass necessary just to get our TestResult hooked up.
|
||||
class TestRunner(unittest.TextTestRunner):
|
||||
def _makeResult(self):
|
||||
return TestResult(self.stream, self.descriptions, self.verbosity)
|
||||
|
||||
|
||||
# TestProgream subclass necessary just to get our TestRunner hooked up,
|
||||
# which is necessary to get our TestResult hooked up *sob*
|
||||
class TestProgram(unittest.TestProgram):
|
||||
def runTests(self):
|
||||
# clobber existing runner - *sob* - it shouldn't be this hard
|
||||
self.testRunner = TestRunner(verbosity=self.verbosity)
|
||||
unittest.TestProgram.runTests(self)
|
||||
|
||||
# A convenient entry-point - if used, 'SKIPPED' exceptions will be supressed.
|
||||
def testmain(*args, **kw):
|
||||
new_kw = kw.copy()
|
||||
if 'testLoader' not in new_kw:
|
||||
new_kw['testLoader'] = TestLoader()
|
||||
program_class = new_kw.get('testProgram', TestProgram)
|
||||
program_class(*args, **new_kw)
|
||||
124
Pywin32/lib/x32/win32/lib/pywintypes.py
Normal file
@@ -0,0 +1,124 @@
|
||||
# Magic utility that "redirects" to pywintypesxx.dll
|
||||
import imp, sys, os
|
||||
def __import_pywin32_system_module__(modname, globs):
|
||||
# This has been through a number of iterations. The problem: how to
|
||||
# locate pywintypesXX.dll when it may be in a number of places, and how
|
||||
# to avoid ever loading it twice. This problem is compounded by the
|
||||
# fact that the "right" way to do this requires win32api, but this
|
||||
# itself requires pywintypesXX.
|
||||
# And the killer problem is that someone may have done 'import win32api'
|
||||
# before this code is called. In that case Windows will have already
|
||||
# loaded pywintypesXX as part of loading win32api - but by the time
|
||||
# we get here, we may locate a different one. This appears to work, but
|
||||
# then starts raising bizarre TypeErrors complaining that something
|
||||
# is not a pywintypes type when it clearly is!
|
||||
|
||||
# So in what we hope is the last major iteration of this, we now
|
||||
# rely on a _win32sysloader module, implemented in C but not relying
|
||||
# on pywintypesXX.dll. It then can check if the DLL we are looking for
|
||||
# lib is already loaded.
|
||||
if not sys.platform.startswith("win32"):
|
||||
# These extensions can be built on Linux via the 'mainwin' toolkit.
|
||||
# Look for a native 'lib{modname}.so'
|
||||
# NOTE: The _win32sysloader module will probably build in this
|
||||
# environment, so it may be better to use that here too.
|
||||
for ext, mode, ext_type in imp.get_suffixes():
|
||||
if ext_type==imp.C_EXTENSION:
|
||||
for path in sys.path:
|
||||
look = os.path.join(path, "lib" + modname + ext)
|
||||
if os.path.isfile(look):
|
||||
mod = imp.load_module(modname, None, look,
|
||||
(ext, mode, ext_type))
|
||||
# and fill our namespace with it.
|
||||
# XXX - if this ever moves to py3k, this will probably
|
||||
# need similar adjustments as below...
|
||||
globs.update(mod.__dict__)
|
||||
return
|
||||
raise ImportError("No dynamic module " + modname)
|
||||
# See if this is a debug build.
|
||||
for suffix_item in imp.get_suffixes():
|
||||
if suffix_item[0]=='_d.pyd':
|
||||
suffix = '_d'
|
||||
break
|
||||
else:
|
||||
suffix = ""
|
||||
filename = "%s%d%d%s.dll" % \
|
||||
(modname, sys.version_info[0], sys.version_info[1], suffix)
|
||||
if hasattr(sys, "frozen"):
|
||||
# If we are running from a frozen program (py2exe, McMillan, freeze)
|
||||
# then we try and load the DLL from our sys.path
|
||||
# XXX - This path may also benefit from _win32sysloader? However,
|
||||
# MarkH has never seen the DLL load problem with py2exe programs...
|
||||
for look in sys.path:
|
||||
# If the sys.path entry is a (presumably) .zip file, use the
|
||||
# directory
|
||||
if os.path.isfile(look):
|
||||
look = os.path.dirname(look)
|
||||
found = os.path.join(look, filename)
|
||||
if os.path.isfile(found):
|
||||
break
|
||||
else:
|
||||
raise ImportError("Module '%s' isn't in frozen sys.path %s" % (modname, sys.path))
|
||||
else:
|
||||
# First see if it already in our process - if so, we must use that.
|
||||
import _win32sysloader
|
||||
found = _win32sysloader.GetModuleFilename(filename)
|
||||
if found is None:
|
||||
# We ask Windows to load it next. This is in an attempt to
|
||||
# get the exact same module loaded should pywintypes be imported
|
||||
# first (which is how we are here) or if, eg, win32api was imported
|
||||
# first thereby implicitly loading the DLL.
|
||||
|
||||
# Sadly though, it doesn't quite work - if pywintypesxx.dll
|
||||
# is in system32 *and* the executable's directory, on XP SP2, an
|
||||
# import of win32api will cause Windows to load pywintypes
|
||||
# from system32, where LoadLibrary for that name will
|
||||
# load the one in the exe's dir.
|
||||
# That shouldn't really matter though, so long as we only ever
|
||||
# get one loaded.
|
||||
found = _win32sysloader.LoadModule(filename)
|
||||
if found is None:
|
||||
# Windows can't find it - which although isn't relevent here,
|
||||
# means that we *must* be the first win32 import, as an attempt
|
||||
# to import win32api etc would fail when Windows attempts to
|
||||
# locate the DLL.
|
||||
# This is most likely to happen for "non-admin" installs, where
|
||||
# we can't put the files anywhere else on the global path.
|
||||
|
||||
# If there is a version in our Python directory, use that
|
||||
if os.path.isfile(os.path.join(sys.prefix, filename)):
|
||||
found = os.path.join(sys.prefix, filename)
|
||||
if found is None:
|
||||
# Not in the Python directory? Maybe we were installed via
|
||||
# easy_install...
|
||||
if os.path.isfile(os.path.join(os.path.dirname(__file__), filename)):
|
||||
found = os.path.join(os.path.dirname(__file__), filename)
|
||||
if found is None:
|
||||
# give up in disgust.
|
||||
raise ImportError("No system module '%s' (%s)" % (modname, filename))
|
||||
# py2k and py3k differences:
|
||||
# On py2k, after doing "imp.load_module('pywintypes')", sys.modules
|
||||
# is unchanged - ie, sys.modules['pywintypes'] still refers to *this*
|
||||
# .py module - but the module's __dict__ has *already* need updated
|
||||
# with the new module's contents.
|
||||
# However, on py3k, sys.modules *is* changed - sys.modules['pywintypes']
|
||||
# will be changed to the new module object.
|
||||
# SO: * on py2k don't need to update any globals.
|
||||
# * on py3k we update our module dict with the new module's dict and
|
||||
# copy its globals to ours.
|
||||
old_mod = sys.modules[modname]
|
||||
# Python can load the module
|
||||
mod = imp.load_dynamic(modname, found)
|
||||
# Check the sys.modules[] behaviour we describe above is true...
|
||||
if sys.version_info < (3,0):
|
||||
assert sys.modules[modname] is old_mod
|
||||
assert mod is old_mod
|
||||
else:
|
||||
assert sys.modules[modname] is not old_mod
|
||||
assert sys.modules[modname] is mod
|
||||
# as above - re-reset to the *old* module object then update globs.
|
||||
sys.modules[modname] = old_mod
|
||||
globs.update(mod.__dict__)
|
||||
|
||||
|
||||
__import_pywin32_system_module__("pywintypes", globals())
|
||||
38
Pywin32/lib/x32/win32/lib/rasutil.py
Normal file
@@ -0,0 +1,38 @@
|
||||
import win32ras
|
||||
|
||||
stateStrings = {
|
||||
win32ras.RASCS_OpenPort : "OpenPort",
|
||||
win32ras.RASCS_PortOpened : "PortOpened",
|
||||
win32ras.RASCS_ConnectDevice : "ConnectDevice",
|
||||
win32ras.RASCS_DeviceConnected : "DeviceConnected",
|
||||
win32ras.RASCS_AllDevicesConnected : "AllDevicesConnected",
|
||||
win32ras.RASCS_Authenticate : "Authenticate",
|
||||
win32ras.RASCS_AuthNotify : "AuthNotify",
|
||||
win32ras.RASCS_AuthRetry : "AuthRetry",
|
||||
win32ras.RASCS_AuthCallback : "AuthCallback",
|
||||
win32ras.RASCS_AuthChangePassword : "AuthChangePassword",
|
||||
win32ras.RASCS_AuthProject : "AuthProject",
|
||||
win32ras.RASCS_AuthLinkSpeed : "AuthLinkSpeed",
|
||||
win32ras.RASCS_AuthAck : "AuthAck",
|
||||
win32ras.RASCS_ReAuthenticate : "ReAuthenticate",
|
||||
win32ras.RASCS_Authenticated : "Authenticated",
|
||||
win32ras.RASCS_PrepareForCallback : "PrepareForCallback",
|
||||
win32ras.RASCS_WaitForModemReset : "WaitForModemReset",
|
||||
win32ras.RASCS_WaitForCallback : "WaitForCallback",
|
||||
win32ras.RASCS_Projected : "Projected",
|
||||
win32ras.RASCS_StartAuthentication : "StartAuthentication",
|
||||
win32ras.RASCS_CallbackComplete : "CallbackComplete",
|
||||
win32ras.RASCS_LogonNetwork : "LogonNetwork",
|
||||
win32ras.RASCS_Interactive : "Interactive",
|
||||
win32ras.RASCS_RetryAuthentication : "RetryAuthentication",
|
||||
win32ras.RASCS_CallbackSetByCaller : "CallbackSetByCaller",
|
||||
win32ras.RASCS_PasswordExpired : "PasswordExpired",
|
||||
win32ras.RASCS_Connected : "Connected",
|
||||
win32ras.RASCS_Disconnected : "Disconnected"
|
||||
}
|
||||
|
||||
def TestCallback( hras, msg, state, error, exterror):
|
||||
print("Callback called with ", hras, msg, stateStrings[state], error, exterror)
|
||||
|
||||
def test(rasName = "_ Divert Off"):
|
||||
return win32ras.Dial(None, None, (rasName,),TestCallback)
|
||||
124
Pywin32/lib/x32/win32/lib/regcheck.py
Normal file
@@ -0,0 +1,124 @@
|
||||
# This module is very old and useless in this day and age! It will be
|
||||
# removed in a few years (ie, 2009 or so...)
|
||||
|
||||
import warnings
|
||||
warnings.warn("The regcheck module has been pending deprecation since build 210",
|
||||
category=PendingDeprecationWarning)
|
||||
|
||||
import win32con
|
||||
import regutil
|
||||
import win32api
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def CheckRegisteredExe(exename):
|
||||
try:
|
||||
os.stat(win32api.RegQueryValue(regutil.GetRootKey() , regutil.GetAppPathsKey() + "\\" + exename))
|
||||
# except SystemError:
|
||||
except (os.error,win32api.error):
|
||||
print("Registration of %s - Not registered correctly" % exename)
|
||||
|
||||
def CheckPathString(pathString):
|
||||
for path in pathString.split(";"):
|
||||
if not os.path.isdir(path):
|
||||
return "'%s' is not a valid directory!" % path
|
||||
return None
|
||||
|
||||
def CheckPythonPaths(verbose):
|
||||
if verbose: print("Python Paths:")
|
||||
# Check the core path
|
||||
if verbose: print("\tCore Path:", end=' ')
|
||||
try:
|
||||
appPath = win32api.RegQueryValue(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath")
|
||||
except win32api.error as exc:
|
||||
print("** does not exist - ", exc.strerror)
|
||||
problem = CheckPathString(appPath)
|
||||
if problem:
|
||||
print(problem)
|
||||
else:
|
||||
if verbose: print(appPath)
|
||||
|
||||
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\PythonPath", 0, win32con.KEY_READ)
|
||||
try:
|
||||
keyNo = 0
|
||||
while 1:
|
||||
try:
|
||||
appName = win32api.RegEnumKey(key, keyNo)
|
||||
appPath = win32api.RegQueryValue(key, appName)
|
||||
if verbose: print("\t"+appName+":", end=' ')
|
||||
if appPath:
|
||||
problem = CheckPathString(appPath)
|
||||
if problem:
|
||||
print(problem)
|
||||
else:
|
||||
if verbose: print(appPath)
|
||||
else:
|
||||
if verbose: print("(empty)")
|
||||
keyNo = keyNo + 1
|
||||
except win32api.error:
|
||||
break
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
def CheckHelpFiles(verbose):
|
||||
if verbose: print("Help Files:")
|
||||
try:
|
||||
key = win32api.RegOpenKey(regutil.GetRootKey(), regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
return
|
||||
|
||||
try:
|
||||
keyNo = 0
|
||||
while 1:
|
||||
try:
|
||||
helpDesc = win32api.RegEnumKey(key, keyNo)
|
||||
helpFile = win32api.RegQueryValue(key, helpDesc)
|
||||
if verbose: print("\t"+helpDesc+":", end=' ')
|
||||
# query the os section.
|
||||
try:
|
||||
os.stat(helpFile )
|
||||
if verbose: print(helpFile)
|
||||
except os.error:
|
||||
print("** Help file %s does not exist" % helpFile)
|
||||
keyNo = keyNo + 1
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_NO_MORE_ITEMS:
|
||||
raise
|
||||
break
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
def CheckRegisteredModules(verbose):
|
||||
# Check out all registered modules.
|
||||
k=regutil.BuildDefaultPythonKey() + "\\Modules"
|
||||
try:
|
||||
keyhandle = win32api.RegOpenKey(regutil.GetRootKey(), k)
|
||||
print("WARNING: 'Modules' registry entry is deprectated and evil!")
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
return
|
||||
|
||||
def CheckRegistry(verbose=0):
|
||||
# check the registered modules
|
||||
if verbose and 'pythonpath' in os.environ:
|
||||
print("Warning - PythonPath in environment - please check it!")
|
||||
# Check out all paths on sys.path
|
||||
|
||||
CheckPythonPaths(verbose)
|
||||
CheckHelpFiles(verbose)
|
||||
CheckRegisteredModules(verbose)
|
||||
CheckRegisteredExe("Python.exe")
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>1 and sys.argv[1]=='-q':
|
||||
verbose = 0
|
||||
else:
|
||||
verbose = 1
|
||||
CheckRegistry(verbose)
|
||||
284
Pywin32/lib/x32/win32/lib/regutil.py
Normal file
@@ -0,0 +1,284 @@
|
||||
# Some registry helpers.
|
||||
import win32api
|
||||
import win32con
|
||||
import sys
|
||||
import os
|
||||
|
||||
error = "Registry utility error"
|
||||
|
||||
# A .py file has a CLSID associated with it (why? - dunno!)
|
||||
CLSIDPyFile = "{b51df050-06ae-11cf-ad3b-524153480001}"
|
||||
|
||||
RegistryIDPyFile = "Python.File" # The registry "file type" of a .py file
|
||||
RegistryIDPycFile = "Python.CompiledFile" # The registry "file type" of a .pyc file
|
||||
|
||||
def BuildDefaultPythonKey():
|
||||
"""Builds a string containing the path to the current registry key.
|
||||
|
||||
The Python registry key contains the Python version. This function
|
||||
uses the version of the DLL used by the current process to get the
|
||||
registry key currently in use.
|
||||
"""
|
||||
return "Software\\Python\\PythonCore\\" + sys.winver
|
||||
|
||||
def GetRootKey():
|
||||
"""Retrieves the Registry root in use by Python.
|
||||
"""
|
||||
keyname = BuildDefaultPythonKey()
|
||||
try:
|
||||
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
|
||||
k.close()
|
||||
return win32con.HKEY_CURRENT_USER
|
||||
except win32api.error:
|
||||
return win32con.HKEY_LOCAL_MACHINE
|
||||
|
||||
def GetRegistryDefaultValue(subkey, rootkey = None):
|
||||
"""A helper to return the default value for a key in the registry.
|
||||
"""
|
||||
if rootkey is None: rootkey = GetRootKey()
|
||||
return win32api.RegQueryValue(rootkey, subkey)
|
||||
|
||||
def SetRegistryDefaultValue(subKey, value, rootkey = None):
|
||||
"""A helper to set the default value for a key in the registry
|
||||
"""
|
||||
if rootkey is None: rootkey = GetRootKey()
|
||||
if type(value)==str:
|
||||
typeId = win32con.REG_SZ
|
||||
elif type(value)==int:
|
||||
typeId = win32con.REG_DWORD
|
||||
else:
|
||||
raise TypeError("Value must be string or integer - was passed " + repr(value))
|
||||
|
||||
win32api.RegSetValue(rootkey, subKey, typeId ,value)
|
||||
|
||||
def GetAppPathsKey():
|
||||
return "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"
|
||||
|
||||
def RegisterPythonExe(exeFullPath, exeAlias = None, exeAppPath = None):
|
||||
"""Register a .exe file that uses Python.
|
||||
|
||||
Registers the .exe with the OS. This allows the specified .exe to
|
||||
be run from the command-line or start button without using the full path,
|
||||
and also to setup application specific path (ie, os.environ['PATH']).
|
||||
|
||||
Currently the exeAppPath is not supported, so this function is general
|
||||
purpose, and not specific to Python at all. Later, exeAppPath may provide
|
||||
a reasonable default that is used.
|
||||
|
||||
exeFullPath -- The full path to the .exe
|
||||
exeAlias = None -- An alias for the exe - if none, the base portion
|
||||
of the filename is used.
|
||||
exeAppPath -- Not supported.
|
||||
"""
|
||||
# Note - Dont work on win32s (but we dont care anymore!)
|
||||
if exeAppPath:
|
||||
raise error("Do not support exeAppPath argument currently")
|
||||
if exeAlias is None:
|
||||
exeAlias = os.path.basename(exeFullPath)
|
||||
win32api.RegSetValue(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias, win32con.REG_SZ, exeFullPath)
|
||||
|
||||
def GetRegisteredExe(exeAlias):
|
||||
"""Get a registered .exe
|
||||
"""
|
||||
return win32api.RegQueryValue(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias)
|
||||
|
||||
def UnregisterPythonExe(exeAlias):
|
||||
"""Unregister a .exe file that uses Python.
|
||||
"""
|
||||
try:
|
||||
win32api.RegDeleteKey(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
return
|
||||
|
||||
def RegisterNamedPath(name, path):
|
||||
"""Register a named path - ie, a named PythonPath entry.
|
||||
"""
|
||||
keyStr = BuildDefaultPythonKey() + "\\PythonPath"
|
||||
if name: keyStr = keyStr + "\\" + name
|
||||
win32api.RegSetValue(GetRootKey(), keyStr, win32con.REG_SZ, path)
|
||||
|
||||
def UnregisterNamedPath(name):
|
||||
"""Unregister a named path - ie, a named PythonPath entry.
|
||||
"""
|
||||
keyStr = BuildDefaultPythonKey() + "\\PythonPath\\" + name
|
||||
try:
|
||||
win32api.RegDeleteKey(GetRootKey(), keyStr)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
return
|
||||
|
||||
def GetRegisteredNamedPath(name):
|
||||
"""Get a registered named path, or None if it doesnt exist.
|
||||
"""
|
||||
keyStr = BuildDefaultPythonKey() + "\\PythonPath"
|
||||
if name: keyStr = keyStr + "\\" + name
|
||||
try:
|
||||
return win32api.RegQueryValue(GetRootKey(), keyStr)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
return None
|
||||
|
||||
|
||||
def RegisterModule(modName, modPath):
|
||||
"""Register an explicit module in the registry. This forces the Python import
|
||||
mechanism to locate this module directly, without a sys.path search. Thus
|
||||
a registered module need not appear in sys.path at all.
|
||||
|
||||
modName -- The name of the module, as used by import.
|
||||
modPath -- The full path and file name of the module.
|
||||
"""
|
||||
try:
|
||||
import os
|
||||
os.stat(modPath)
|
||||
except os.error:
|
||||
print("Warning: Registering non-existant module %s" % modPath)
|
||||
win32api.RegSetValue(GetRootKey(),
|
||||
BuildDefaultPythonKey() + "\\Modules\\%s" % modName,
|
||||
win32con.REG_SZ, modPath)
|
||||
|
||||
def UnregisterModule(modName):
|
||||
"""Unregister an explicit module in the registry.
|
||||
|
||||
modName -- The name of the module, as used by import.
|
||||
"""
|
||||
try:
|
||||
win32api.RegDeleteKey(GetRootKey(),
|
||||
BuildDefaultPythonKey() + "\\Modules\\%s" % modName)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
|
||||
def GetRegisteredHelpFile(helpDesc):
|
||||
"""Given a description, return the registered entry.
|
||||
"""
|
||||
try:
|
||||
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc)
|
||||
except win32api.error:
|
||||
try:
|
||||
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc, win32con.HKEY_CURRENT_USER)
|
||||
except win32api.error:
|
||||
pass
|
||||
return None
|
||||
|
||||
def RegisterHelpFile(helpFile, helpPath, helpDesc = None, bCheckFile = 1):
|
||||
"""Register a help file in the registry.
|
||||
|
||||
Note that this used to support writing to the Windows Help
|
||||
key, however this is no longer done, as it seems to be incompatible.
|
||||
|
||||
helpFile -- the base name of the help file.
|
||||
helpPath -- the path to the help file
|
||||
helpDesc -- A description for the help file. If None, the helpFile param is used.
|
||||
bCheckFile -- A flag indicating if the file existence should be checked.
|
||||
"""
|
||||
if helpDesc is None: helpDesc = helpFile
|
||||
fullHelpFile = os.path.join(helpPath, helpFile)
|
||||
try:
|
||||
if bCheckFile: os.stat(fullHelpFile)
|
||||
except os.error:
|
||||
raise ValueError("Help file does not exist")
|
||||
# Now register with Python itself.
|
||||
win32api.RegSetValue(GetRootKey(),
|
||||
BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc, win32con.REG_SZ, fullHelpFile)
|
||||
|
||||
def UnregisterHelpFile(helpFile, helpDesc = None):
|
||||
"""Unregister a help file in the registry.
|
||||
|
||||
helpFile -- the base name of the help file.
|
||||
helpDesc -- A description for the help file. If None, the helpFile param is used.
|
||||
"""
|
||||
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
|
||||
try:
|
||||
try:
|
||||
win32api.RegDeleteValue(key, helpFile)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
# Now de-register with Python itself.
|
||||
if helpDesc is None: helpDesc = helpFile
|
||||
try:
|
||||
win32api.RegDeleteKey(GetRootKey(),
|
||||
BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc)
|
||||
except win32api.error as exc:
|
||||
import winerror
|
||||
if exc.winerror!=winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
|
||||
def RegisterCoreDLL(coredllName = None):
|
||||
"""Registers the core DLL in the registry.
|
||||
|
||||
If no params are passed, the name of the Python DLL used in
|
||||
the current process is used and registered.
|
||||
"""
|
||||
if coredllName is None:
|
||||
coredllName = win32api.GetModuleFileName(sys.dllhandle)
|
||||
# must exist!
|
||||
else:
|
||||
try:
|
||||
os.stat(coredllName)
|
||||
except os.error:
|
||||
print("Warning: Registering non-existant core DLL %s" % coredllName)
|
||||
|
||||
hKey = win32api.RegCreateKey(GetRootKey() , BuildDefaultPythonKey())
|
||||
try:
|
||||
win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName)
|
||||
finally:
|
||||
win32api.RegCloseKey(hKey)
|
||||
# Lastly, setup the current version to point to me.
|
||||
win32api.RegSetValue(GetRootKey(), "Software\\Python\\PythonCore\\CurrentVersion", win32con.REG_SZ, sys.winver)
|
||||
|
||||
def RegisterFileExtensions(defPyIcon, defPycIcon, runCommand):
|
||||
"""Register the core Python file extensions.
|
||||
|
||||
defPyIcon -- The default icon to use for .py files, in 'fname,offset' format.
|
||||
defPycIcon -- The default icon to use for .pyc files, in 'fname,offset' format.
|
||||
runCommand -- The command line to use for running .py files
|
||||
"""
|
||||
# Register the file extensions.
|
||||
pythonFileId = RegistryIDPyFile
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , ".py", win32con.REG_SZ, pythonFileId)
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , pythonFileId , win32con.REG_SZ, "Python File")
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , "%s\\CLSID" % pythonFileId , win32con.REG_SZ, CLSIDPyFile)
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , "%s\\DefaultIcon" % pythonFileId, win32con.REG_SZ, defPyIcon)
|
||||
base = "%s\\Shell" % RegistryIDPyFile
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\Open", win32con.REG_SZ, "Run")
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\Open\\Command", win32con.REG_SZ, runCommand)
|
||||
|
||||
# Register the .PYC.
|
||||
pythonFileId = RegistryIDPycFile
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , ".pyc", win32con.REG_SZ, pythonFileId)
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , pythonFileId , win32con.REG_SZ, "Compiled Python File")
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , "%s\\DefaultIcon" % pythonFileId, win32con.REG_SZ, defPycIcon)
|
||||
base = "%s\\Shell" % pythonFileId
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\Open", win32con.REG_SZ, "Run")
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\Open\\Command", win32con.REG_SZ, runCommand)
|
||||
|
||||
def RegisterShellCommand(shellCommand, exeCommand, shellUserCommand = None):
|
||||
# Last param for "Open" - for a .py file to be executed by the command line
|
||||
# or shell execute (eg, just entering "foo.py"), the Command must be "Open",
|
||||
# but you may associate a different name for the right-click menu.
|
||||
# In our case, normally we have "Open=Run"
|
||||
base = "%s\\Shell" % RegistryIDPyFile
|
||||
if shellUserCommand:
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\%s" % (shellCommand), win32con.REG_SZ, shellUserCommand)
|
||||
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\%s\\Command" % (shellCommand), win32con.REG_SZ, exeCommand)
|
||||
|
||||
def RegisterDDECommand(shellCommand, ddeApp, ddeTopic, ddeCommand):
|
||||
base = "%s\\Shell" % RegistryIDPyFile
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\%s\\ddeexec" % (shellCommand), win32con.REG_SZ, ddeCommand)
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\%s\\ddeexec\\Application" % (shellCommand), win32con.REG_SZ, ddeApp)
|
||||
win32api.RegSetValue(win32con.HKEY_CLASSES_ROOT , base + "\\%s\\ddeexec\\Topic" % (shellCommand), win32con.REG_SZ, ddeTopic)
|
||||
|
||||
226
Pywin32/lib/x32/win32/lib/sspi.py
Normal file
@@ -0,0 +1,226 @@
|
||||
"""
|
||||
Helper classes for SSPI authentication via the win32security module.
|
||||
|
||||
SSPI authentication involves a token-exchange "dance", the exact details
|
||||
of which depends on the authentication provider used. There are also
|
||||
a number of complex flags and constants that need to be used - in most
|
||||
cases, there are reasonable defaults.
|
||||
|
||||
These classes attempt to hide these details from you until you really need
|
||||
to know. They are not designed to handle all cases, just the common ones.
|
||||
If you need finer control than offered here, just use the win32security
|
||||
functions directly.
|
||||
"""
|
||||
# Based on Roger Upole's sspi demos.
|
||||
# $Id$
|
||||
import win32security, sspicon
|
||||
|
||||
error = win32security.error
|
||||
|
||||
class _BaseAuth(object):
|
||||
def __init__(self):
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
"""Reset everything to an unauthorized state"""
|
||||
self.ctxt = None
|
||||
self.authenticated = False
|
||||
# The next seq_num for an encrypt/sign operation
|
||||
self.next_seq_num = 0
|
||||
|
||||
def _get_next_seq_num(self):
|
||||
"""Get the next sequence number for a transmission. Default
|
||||
implementation is to increment a counter
|
||||
"""
|
||||
ret = self.next_seq_num
|
||||
self.next_seq_num = self.next_seq_num + 1
|
||||
return ret
|
||||
|
||||
def encrypt(self, data):
|
||||
"""Encrypt a string, returning a tuple of (encrypted_data, encryption_data).
|
||||
These can be passed to decrypt to get back the original string.
|
||||
"""
|
||||
pkg_size_info=self.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)
|
||||
trailersize=pkg_size_info['SecurityTrailer']
|
||||
|
||||
encbuf=win32security.PySecBufferDescType()
|
||||
encbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA))
|
||||
encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN))
|
||||
encbuf[0].Buffer=data
|
||||
self.ctxt.EncryptMessage(0,encbuf,self._get_next_seq_num())
|
||||
return encbuf[0].Buffer, encbuf[1].Buffer
|
||||
|
||||
def decrypt(self, data, trailer):
|
||||
"""Decrypt a previously encrypted string, returning the orignal data"""
|
||||
encbuf=win32security.PySecBufferDescType()
|
||||
encbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA))
|
||||
encbuf.append(win32security.PySecBufferType(len(trailer), sspicon.SECBUFFER_TOKEN))
|
||||
encbuf[0].Buffer=data
|
||||
encbuf[1].Buffer=trailer
|
||||
self.ctxt.DecryptMessage(encbuf,self._get_next_seq_num())
|
||||
return encbuf[0].Buffer
|
||||
|
||||
def sign(self, data):
|
||||
"""sign a string suitable for transmission, returning the signature.
|
||||
Passing the data and signature to verify will determine if the data
|
||||
is unchanged.
|
||||
"""
|
||||
pkg_size_info=self.ctxt.QueryContextAttributes(sspicon.SECPKG_ATTR_SIZES)
|
||||
sigsize=pkg_size_info['MaxSignature']
|
||||
sigbuf=win32security.PySecBufferDescType()
|
||||
sigbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA))
|
||||
sigbuf.append(win32security.PySecBufferType(sigsize, sspicon.SECBUFFER_TOKEN))
|
||||
sigbuf[0].Buffer=data
|
||||
|
||||
self.ctxt.MakeSignature(0,sigbuf,self._get_next_seq_num())
|
||||
return sigbuf[1].Buffer
|
||||
|
||||
def verify(self, data, sig):
|
||||
"""Verifies data and its signature. If verification fails, an sspi.error
|
||||
will be raised.
|
||||
"""
|
||||
sigbuf=win32security.PySecBufferDescType()
|
||||
sigbuf.append(win32security.PySecBufferType(len(data), sspicon.SECBUFFER_DATA))
|
||||
sigbuf.append(win32security.PySecBufferType(len(sig), sspicon.SECBUFFER_TOKEN))
|
||||
|
||||
sigbuf[0].Buffer=data
|
||||
sigbuf[1].Buffer=sig
|
||||
self.ctxt.VerifySignature(sigbuf,self._get_next_seq_num())
|
||||
|
||||
class ClientAuth(_BaseAuth):
|
||||
"""Manages the client side of an SSPI authentication handshake
|
||||
"""
|
||||
def __init__(self,
|
||||
pkg_name, # Name of the package to used.
|
||||
client_name = None, # User for whom credentials are used.
|
||||
auth_info = None, # or a tuple of (username, domain, password)
|
||||
targetspn = None, # Target security context provider name.
|
||||
scflags=None, # security context flags
|
||||
datarep=sspicon.SECURITY_NETWORK_DREP):
|
||||
if scflags is None:
|
||||
scflags = sspicon.ISC_REQ_INTEGRITY|sspicon.ISC_REQ_SEQUENCE_DETECT|\
|
||||
sspicon.ISC_REQ_REPLAY_DETECT|sspicon.ISC_REQ_CONFIDENTIALITY
|
||||
self.scflags=scflags
|
||||
self.datarep=datarep
|
||||
self.targetspn=targetspn
|
||||
self.pkg_info=win32security.QuerySecurityPackageInfo(pkg_name)
|
||||
self.credentials, \
|
||||
self.credentials_expiry=win32security.AcquireCredentialsHandle(
|
||||
client_name, self.pkg_info['Name'],
|
||||
sspicon.SECPKG_CRED_OUTBOUND,
|
||||
None, auth_info)
|
||||
_BaseAuth.__init__(self)
|
||||
|
||||
# Perform *one* step of the client authentication process.
|
||||
def authorize(self, sec_buffer_in):
|
||||
if sec_buffer_in is not None and type(sec_buffer_in) != win32security.PySecBufferDescType:
|
||||
# User passed us the raw data - wrap it into a SecBufferDesc
|
||||
sec_buffer_new=win32security.PySecBufferDescType()
|
||||
tokenbuf=win32security.PySecBufferType(self.pkg_info['MaxToken'],
|
||||
sspicon.SECBUFFER_TOKEN)
|
||||
tokenbuf.Buffer=sec_buffer_in
|
||||
sec_buffer_new.append(tokenbuf)
|
||||
sec_buffer_in = sec_buffer_new
|
||||
sec_buffer_out=win32security.PySecBufferDescType()
|
||||
tokenbuf=win32security.PySecBufferType(self.pkg_info['MaxToken'], sspicon.SECBUFFER_TOKEN)
|
||||
sec_buffer_out.append(tokenbuf)
|
||||
## input context handle should be NULL on first call
|
||||
ctxtin=self.ctxt
|
||||
if self.ctxt is None:
|
||||
self.ctxt=win32security.PyCtxtHandleType()
|
||||
err, attr, exp=win32security.InitializeSecurityContext(
|
||||
self.credentials,
|
||||
ctxtin,
|
||||
self.targetspn,
|
||||
self.scflags,
|
||||
self.datarep,
|
||||
sec_buffer_in,
|
||||
self.ctxt,
|
||||
sec_buffer_out)
|
||||
# Stash these away incase someone needs to know the state from the
|
||||
# final call.
|
||||
self.ctxt_attr = attr
|
||||
self.ctxt_expiry = exp
|
||||
|
||||
if err in (sspicon.SEC_I_COMPLETE_NEEDED,sspicon.SEC_I_COMPLETE_AND_CONTINUE):
|
||||
self.ctxt.CompleteAuthToken(sec_buffer_out)
|
||||
self.authenticated = err == 0
|
||||
return err, sec_buffer_out
|
||||
|
||||
class ServerAuth(_BaseAuth):
|
||||
"""Manages the server side of an SSPI authentication handshake
|
||||
"""
|
||||
def __init__(self,
|
||||
pkg_name,
|
||||
spn = None,
|
||||
scflags=None,
|
||||
datarep=sspicon.SECURITY_NETWORK_DREP):
|
||||
self.spn=spn
|
||||
self.datarep=datarep
|
||||
|
||||
if scflags is None:
|
||||
scflags = sspicon.ASC_REQ_INTEGRITY|sspicon.ASC_REQ_SEQUENCE_DETECT|\
|
||||
sspicon.ASC_REQ_REPLAY_DETECT|sspicon.ASC_REQ_CONFIDENTIALITY
|
||||
# Should we default to sspicon.KerbAddExtraCredentialsMessage
|
||||
# if pkg_name=='Kerberos'?
|
||||
self.scflags=scflags
|
||||
|
||||
self.pkg_info=win32security.QuerySecurityPackageInfo(pkg_name)
|
||||
|
||||
self.credentials, \
|
||||
self.credentials_expiry=win32security.AcquireCredentialsHandle(spn,
|
||||
self.pkg_info['Name'], sspicon.SECPKG_CRED_INBOUND, None, None)
|
||||
_BaseAuth.__init__(self)
|
||||
|
||||
# Perform *one* step of the server authentication process.
|
||||
def authorize(self, sec_buffer_in):
|
||||
if sec_buffer_in is not None and type(sec_buffer_in) != win32security.PySecBufferDescType:
|
||||
# User passed us the raw data - wrap it into a SecBufferDesc
|
||||
sec_buffer_new=win32security.PySecBufferDescType()
|
||||
tokenbuf=win32security.PySecBufferType(self.pkg_info['MaxToken'],
|
||||
sspicon.SECBUFFER_TOKEN)
|
||||
tokenbuf.Buffer=sec_buffer_in
|
||||
sec_buffer_new.append(tokenbuf)
|
||||
sec_buffer_in = sec_buffer_new
|
||||
|
||||
sec_buffer_out=win32security.PySecBufferDescType()
|
||||
tokenbuf=win32security.PySecBufferType(self.pkg_info['MaxToken'], sspicon.SECBUFFER_TOKEN)
|
||||
sec_buffer_out.append(tokenbuf)
|
||||
## input context handle is None initially, then handle returned from last call thereafter
|
||||
ctxtin=self.ctxt
|
||||
if self.ctxt is None:
|
||||
self.ctxt=win32security.PyCtxtHandleType()
|
||||
err, attr, exp = win32security.AcceptSecurityContext(self.credentials, ctxtin,
|
||||
sec_buffer_in, self.scflags,
|
||||
self.datarep, self.ctxt, sec_buffer_out)
|
||||
|
||||
# Stash these away incase someone needs to know the state from the
|
||||
# final call.
|
||||
self.ctxt_attr = attr
|
||||
self.ctxt_expiry = exp
|
||||
|
||||
if err in (sspicon.SEC_I_COMPLETE_NEEDED,sspicon.SEC_I_COMPLETE_AND_CONTINUE):
|
||||
self.ctxt.CompleteAuthToken(sec_buffer_out)
|
||||
self.authenticated = err == 0
|
||||
return err, sec_buffer_out
|
||||
|
||||
if __name__=='__main__':
|
||||
# Setup the 2 contexts.
|
||||
sspiclient=ClientAuth("NTLM")
|
||||
sspiserver=ServerAuth("NTLM")
|
||||
|
||||
# Perform the authentication dance, each loop exchanging more information
|
||||
# on the way to completing authentication.
|
||||
sec_buffer=None
|
||||
while 1:
|
||||
err, sec_buffer = sspiclient.authorize(sec_buffer)
|
||||
err, sec_buffer = sspiserver.authorize(sec_buffer)
|
||||
if err==0:
|
||||
break
|
||||
data = "hello".encode("ascii") # py3k-friendly
|
||||
sig = sspiclient.sign(data)
|
||||
sspiserver.verify(data, sig)
|
||||
|
||||
data, key = sspiclient.encrypt(data)
|
||||
assert sspiserver.decrypt(data, key) == data
|
||||
print("cool!")
|
||||
479
Pywin32/lib/x32/win32/lib/sspicon.py
Normal file
@@ -0,0 +1,479 @@
|
||||
# Generated by h2py from c:\microsoft sdk\include\sspi.h
|
||||
ISSP_LEVEL = 32
|
||||
ISSP_MODE = 1
|
||||
ISSP_LEVEL = 32
|
||||
ISSP_MODE = 0
|
||||
ISSP_LEVEL = 32
|
||||
ISSP_MODE = 1
|
||||
def SEC_SUCCESS(Status): return ((Status) >= 0)
|
||||
|
||||
SECPKG_FLAG_INTEGRITY = 1
|
||||
SECPKG_FLAG_PRIVACY = 2
|
||||
SECPKG_FLAG_TOKEN_ONLY = 4
|
||||
SECPKG_FLAG_DATAGRAM = 8
|
||||
SECPKG_FLAG_CONNECTION = 16
|
||||
SECPKG_FLAG_MULTI_REQUIRED = 32
|
||||
SECPKG_FLAG_CLIENT_ONLY = 64
|
||||
SECPKG_FLAG_EXTENDED_ERROR = 128
|
||||
SECPKG_FLAG_IMPERSONATION = 256
|
||||
SECPKG_FLAG_ACCEPT_WIN32_NAME = 512
|
||||
SECPKG_FLAG_STREAM = 1024
|
||||
SECPKG_FLAG_NEGOTIABLE = 2048
|
||||
SECPKG_FLAG_GSS_COMPATIBLE = 4096
|
||||
SECPKG_FLAG_LOGON = 8192
|
||||
SECPKG_FLAG_ASCII_BUFFERS = 16384
|
||||
SECPKG_FLAG_FRAGMENT = 32768
|
||||
SECPKG_FLAG_MUTUAL_AUTH = 65536
|
||||
SECPKG_FLAG_DELEGATION = 131072
|
||||
SECPKG_FLAG_READONLY_WITH_CHECKSUM = 262144
|
||||
SECPKG_ID_NONE = 65535
|
||||
|
||||
SECBUFFER_VERSION = 0
|
||||
SECBUFFER_EMPTY = 0
|
||||
SECBUFFER_DATA = 1
|
||||
SECBUFFER_TOKEN = 2
|
||||
SECBUFFER_PKG_PARAMS = 3
|
||||
SECBUFFER_MISSING = 4
|
||||
SECBUFFER_EXTRA = 5
|
||||
SECBUFFER_STREAM_TRAILER = 6
|
||||
SECBUFFER_STREAM_HEADER = 7
|
||||
SECBUFFER_NEGOTIATION_INFO = 8
|
||||
SECBUFFER_PADDING = 9
|
||||
SECBUFFER_STREAM = 10
|
||||
SECBUFFER_MECHLIST = 11
|
||||
SECBUFFER_MECHLIST_SIGNATURE = 12
|
||||
SECBUFFER_TARGET = 13
|
||||
SECBUFFER_CHANNEL_BINDINGS = 14
|
||||
SECBUFFER_ATTRMASK = (-268435456)
|
||||
SECBUFFER_READONLY = (-2147483648)
|
||||
SECBUFFER_READONLY_WITH_CHECKSUM = 268435456
|
||||
SECBUFFER_RESERVED = 1610612736
|
||||
|
||||
SECURITY_NATIVE_DREP = 16
|
||||
SECURITY_NETWORK_DREP = 0
|
||||
|
||||
SECPKG_CRED_INBOUND = 1
|
||||
SECPKG_CRED_OUTBOUND = 2
|
||||
SECPKG_CRED_BOTH = 3
|
||||
SECPKG_CRED_DEFAULT = 4
|
||||
SECPKG_CRED_RESERVED = -268435456
|
||||
|
||||
ISC_REQ_DELEGATE = 1
|
||||
ISC_REQ_MUTUAL_AUTH = 2
|
||||
ISC_REQ_REPLAY_DETECT = 4
|
||||
ISC_REQ_SEQUENCE_DETECT = 8
|
||||
ISC_REQ_CONFIDENTIALITY = 16
|
||||
ISC_REQ_USE_SESSION_KEY = 32
|
||||
ISC_REQ_PROMPT_FOR_CREDS = 64
|
||||
ISC_REQ_USE_SUPPLIED_CREDS = 128
|
||||
ISC_REQ_ALLOCATE_MEMORY = 256
|
||||
ISC_REQ_USE_DCE_STYLE = 512
|
||||
ISC_REQ_DATAGRAM = 1024
|
||||
ISC_REQ_CONNECTION = 2048
|
||||
ISC_REQ_CALL_LEVEL = 4096
|
||||
ISC_REQ_FRAGMENT_SUPPLIED = 8192
|
||||
ISC_REQ_EXTENDED_ERROR = 16384
|
||||
ISC_REQ_STREAM = 32768
|
||||
ISC_REQ_INTEGRITY = 65536
|
||||
ISC_REQ_IDENTIFY = 131072
|
||||
ISC_REQ_NULL_SESSION = 262144
|
||||
ISC_REQ_MANUAL_CRED_VALIDATION = 524288
|
||||
ISC_REQ_RESERVED1 = 1048576
|
||||
ISC_REQ_FRAGMENT_TO_FIT = 2097152
|
||||
ISC_REQ_HTTP = 0x10000000
|
||||
ISC_RET_DELEGATE = 1
|
||||
ISC_RET_MUTUAL_AUTH = 2
|
||||
ISC_RET_REPLAY_DETECT = 4
|
||||
ISC_RET_SEQUENCE_DETECT = 8
|
||||
ISC_RET_CONFIDENTIALITY = 16
|
||||
ISC_RET_USE_SESSION_KEY = 32
|
||||
ISC_RET_USED_COLLECTED_CREDS = 64
|
||||
ISC_RET_USED_SUPPLIED_CREDS = 128
|
||||
ISC_RET_ALLOCATED_MEMORY = 256
|
||||
ISC_RET_USED_DCE_STYLE = 512
|
||||
ISC_RET_DATAGRAM = 1024
|
||||
ISC_RET_CONNECTION = 2048
|
||||
ISC_RET_INTERMEDIATE_RETURN = 4096
|
||||
ISC_RET_CALL_LEVEL = 8192
|
||||
ISC_RET_EXTENDED_ERROR = 16384
|
||||
ISC_RET_STREAM = 32768
|
||||
ISC_RET_INTEGRITY = 65536
|
||||
ISC_RET_IDENTIFY = 131072
|
||||
ISC_RET_NULL_SESSION = 262144
|
||||
ISC_RET_MANUAL_CRED_VALIDATION = 524288
|
||||
ISC_RET_RESERVED1 = 1048576
|
||||
ISC_RET_FRAGMENT_ONLY = 2097152
|
||||
|
||||
ASC_REQ_DELEGATE = 1
|
||||
ASC_REQ_MUTUAL_AUTH = 2
|
||||
ASC_REQ_REPLAY_DETECT = 4
|
||||
ASC_REQ_SEQUENCE_DETECT = 8
|
||||
ASC_REQ_CONFIDENTIALITY = 16
|
||||
ASC_REQ_USE_SESSION_KEY = 32
|
||||
ASC_REQ_ALLOCATE_MEMORY = 256
|
||||
ASC_REQ_USE_DCE_STYLE = 512
|
||||
ASC_REQ_DATAGRAM = 1024
|
||||
ASC_REQ_CONNECTION = 2048
|
||||
ASC_REQ_CALL_LEVEL = 4096
|
||||
ASC_REQ_EXTENDED_ERROR = 32768
|
||||
ASC_REQ_STREAM = 65536
|
||||
ASC_REQ_INTEGRITY = 131072
|
||||
ASC_REQ_LICENSING = 262144
|
||||
ASC_REQ_IDENTIFY = 524288
|
||||
ASC_REQ_ALLOW_NULL_SESSION = 1048576
|
||||
ASC_REQ_ALLOW_NON_USER_LOGONS = 2097152
|
||||
ASC_REQ_ALLOW_CONTEXT_REPLAY = 4194304
|
||||
ASC_REQ_FRAGMENT_TO_FIT = 8388608
|
||||
ASC_REQ_FRAGMENT_SUPPLIED = 8192
|
||||
ASC_REQ_NO_TOKEN = 16777216
|
||||
ASC_RET_DELEGATE = 1
|
||||
ASC_RET_MUTUAL_AUTH = 2
|
||||
ASC_RET_REPLAY_DETECT = 4
|
||||
ASC_RET_SEQUENCE_DETECT = 8
|
||||
ASC_RET_CONFIDENTIALITY = 16
|
||||
ASC_RET_USE_SESSION_KEY = 32
|
||||
ASC_RET_ALLOCATED_MEMORY = 256
|
||||
ASC_RET_USED_DCE_STYLE = 512
|
||||
ASC_RET_DATAGRAM = 1024
|
||||
ASC_RET_CONNECTION = 2048
|
||||
ASC_RET_CALL_LEVEL = 8192
|
||||
ASC_RET_THIRD_LEG_FAILED = 16384
|
||||
ASC_RET_EXTENDED_ERROR = 32768
|
||||
ASC_RET_STREAM = 65536
|
||||
ASC_RET_INTEGRITY = 131072
|
||||
ASC_RET_LICENSING = 262144
|
||||
ASC_RET_IDENTIFY = 524288
|
||||
ASC_RET_NULL_SESSION = 1048576
|
||||
ASC_RET_ALLOW_NON_USER_LOGONS = 2097152
|
||||
ASC_RET_ALLOW_CONTEXT_REPLAY = 4194304
|
||||
ASC_RET_FRAGMENT_ONLY = 8388608
|
||||
|
||||
SECPKG_CRED_ATTR_NAMES = 1
|
||||
SECPKG_ATTR_SIZES = 0
|
||||
SECPKG_ATTR_NAMES = 1
|
||||
SECPKG_ATTR_LIFESPAN = 2
|
||||
SECPKG_ATTR_DCE_INFO = 3
|
||||
SECPKG_ATTR_STREAM_SIZES = 4
|
||||
SECPKG_ATTR_KEY_INFO = 5
|
||||
SECPKG_ATTR_AUTHORITY = 6
|
||||
SECPKG_ATTR_PROTO_INFO = 7
|
||||
SECPKG_ATTR_PASSWORD_EXPIRY = 8
|
||||
SECPKG_ATTR_SESSION_KEY = 9
|
||||
SECPKG_ATTR_PACKAGE_INFO = 10
|
||||
SECPKG_ATTR_USER_FLAGS = 11
|
||||
SECPKG_ATTR_NEGOTIATION_INFO = 12
|
||||
SECPKG_ATTR_NATIVE_NAMES = 13
|
||||
SECPKG_ATTR_FLAGS = 14
|
||||
SECPKG_ATTR_USE_VALIDATED = 15
|
||||
SECPKG_ATTR_CREDENTIAL_NAME = 16
|
||||
SECPKG_ATTR_TARGET_INFORMATION = 17
|
||||
SECPKG_ATTR_ACCESS_TOKEN = 18
|
||||
SECPKG_ATTR_TARGET = 19
|
||||
SECPKG_ATTR_AUTHENTICATION_ID = 20
|
||||
|
||||
## attributes from schannel.h
|
||||
SECPKG_ATTR_REMOTE_CERT_CONTEXT = 83
|
||||
SECPKG_ATTR_LOCAL_CERT_CONTEXT = 84
|
||||
SECPKG_ATTR_ROOT_STORE = 85
|
||||
SECPKG_ATTR_SUPPORTED_ALGS = 86
|
||||
SECPKG_ATTR_CIPHER_STRENGTHS = 87
|
||||
SECPKG_ATTR_SUPPORTED_PROTOCOLS = 88
|
||||
SECPKG_ATTR_ISSUER_LIST_EX = 89
|
||||
SECPKG_ATTR_CONNECTION_INFO = 90
|
||||
SECPKG_ATTR_EAP_KEY_BLOCK = 91
|
||||
SECPKG_ATTR_MAPPED_CRED_ATTR = 92
|
||||
SECPKG_ATTR_SESSION_INFO = 93
|
||||
SECPKG_ATTR_APP_DATA = 94
|
||||
|
||||
SECPKG_NEGOTIATION_COMPLETE = 0
|
||||
SECPKG_NEGOTIATION_OPTIMISTIC = 1
|
||||
SECPKG_NEGOTIATION_IN_PROGRESS = 2
|
||||
SECPKG_NEGOTIATION_DIRECT = 3
|
||||
SECPKG_NEGOTIATION_TRY_MULTICRED = 4
|
||||
SECPKG_CONTEXT_EXPORT_RESET_NEW = 1
|
||||
SECPKG_CONTEXT_EXPORT_DELETE_OLD = 2
|
||||
SECQOP_WRAP_NO_ENCRYPT = (-2147483647)
|
||||
SECURITY_ENTRYPOINT_ANSIW = "InitSecurityInterfaceW"
|
||||
SECURITY_ENTRYPOINT_ANSIA = "InitSecurityInterfaceA"
|
||||
SECURITY_ENTRYPOINT16 = "INITSECURITYINTERFACEA"
|
||||
SECURITY_ENTRYPOINT_ANSI = SECURITY_ENTRYPOINT_ANSIW
|
||||
SECURITY_ENTRYPOINT_ANSI = SECURITY_ENTRYPOINT_ANSIA
|
||||
SECURITY_ENTRYPOINT = SECURITY_ENTRYPOINT16
|
||||
SECURITY_ENTRYPOINT_ANSI = SECURITY_ENTRYPOINT16
|
||||
SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION = 1
|
||||
SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2 = 2
|
||||
SASL_OPTION_SEND_SIZE = 1
|
||||
SASL_OPTION_RECV_SIZE = 2
|
||||
SASL_OPTION_AUTHZ_STRING = 3
|
||||
SASL_OPTION_AUTHZ_PROCESSING = 4
|
||||
SEC_WINNT_AUTH_IDENTITY_ANSI = 1
|
||||
SEC_WINNT_AUTH_IDENTITY_UNICODE = 2
|
||||
SEC_WINNT_AUTH_IDENTITY_VERSION = 512
|
||||
SEC_WINNT_AUTH_IDENTITY_MARSHALLED = 4
|
||||
SEC_WINNT_AUTH_IDENTITY_ONLY = 8
|
||||
SECPKG_OPTIONS_TYPE_UNKNOWN = 0
|
||||
SECPKG_OPTIONS_TYPE_LSA = 1
|
||||
SECPKG_OPTIONS_TYPE_SSPI = 2
|
||||
SECPKG_OPTIONS_PERMANENT = 1
|
||||
|
||||
SEC_E_INSUFFICIENT_MEMORY = -2146893056
|
||||
SEC_E_INVALID_HANDLE = -2146893055
|
||||
SEC_E_UNSUPPORTED_FUNCTION = -2146893054
|
||||
SEC_E_TARGET_UNKNOWN = -2146893053
|
||||
SEC_E_INTERNAL_ERROR = -2146893052
|
||||
SEC_E_SECPKG_NOT_FOUND = -2146893051
|
||||
SEC_E_NOT_OWNER = -2146893050
|
||||
SEC_E_CANNOT_INSTALL = -2146893049
|
||||
SEC_E_INVALID_TOKEN = -2146893048
|
||||
SEC_E_CANNOT_PACK = -2146893047
|
||||
SEC_E_QOP_NOT_SUPPORTED = -2146893046
|
||||
SEC_E_NO_IMPERSONATION = -2146893045
|
||||
SEC_E_LOGON_DENIED = -2146893044
|
||||
SEC_E_UNKNOWN_CREDENTIALS = -2146893043
|
||||
SEC_E_NO_CREDENTIALS = -2146893042
|
||||
SEC_E_MESSAGE_ALTERED = -2146893041
|
||||
SEC_E_OUT_OF_SEQUENCE = -2146893040
|
||||
SEC_E_NO_AUTHENTICATING_AUTHORITY = -2146893039
|
||||
SEC_I_CONTINUE_NEEDED = 590610
|
||||
SEC_I_COMPLETE_NEEDED = 590611
|
||||
SEC_I_COMPLETE_AND_CONTINUE = 590612
|
||||
SEC_I_LOCAL_LOGON = 590613
|
||||
SEC_E_BAD_PKGID = -2146893034
|
||||
SEC_E_CONTEXT_EXPIRED = -2146893033
|
||||
SEC_I_CONTEXT_EXPIRED = 590615
|
||||
SEC_E_INCOMPLETE_MESSAGE = -2146893032
|
||||
SEC_E_INCOMPLETE_CREDENTIALS = -2146893024
|
||||
SEC_E_BUFFER_TOO_SMALL = -2146893023
|
||||
SEC_I_INCOMPLETE_CREDENTIALS = 590624
|
||||
SEC_I_RENEGOTIATE = 590625
|
||||
SEC_E_WRONG_PRINCIPAL = -2146893022
|
||||
SEC_I_NO_LSA_CONTEXT = 590627
|
||||
SEC_E_TIME_SKEW = -2146893020
|
||||
SEC_E_UNTRUSTED_ROOT = -2146893019
|
||||
SEC_E_ILLEGAL_MESSAGE = -2146893018
|
||||
SEC_E_CERT_UNKNOWN = -2146893017
|
||||
SEC_E_CERT_EXPIRED = -2146893016
|
||||
SEC_E_ENCRYPT_FAILURE = -2146893015
|
||||
SEC_E_DECRYPT_FAILURE = -2146893008
|
||||
SEC_E_ALGORITHM_MISMATCH = -2146893007
|
||||
SEC_E_SECURITY_QOS_FAILED = -2146893006
|
||||
SEC_E_UNFINISHED_CONTEXT_DELETED = -2146893005
|
||||
SEC_E_NO_TGT_REPLY = -2146893004
|
||||
SEC_E_NO_IP_ADDRESSES = -2146893003
|
||||
SEC_E_WRONG_CREDENTIAL_HANDLE = -2146893002
|
||||
SEC_E_CRYPTO_SYSTEM_INVALID = -2146893001
|
||||
SEC_E_MAX_REFERRALS_EXCEEDED = -2146893000
|
||||
SEC_E_MUST_BE_KDC = -2146892999
|
||||
SEC_E_STRONG_CRYPTO_NOT_SUPPORTED = -2146892998
|
||||
SEC_E_TOO_MANY_PRINCIPALS = -2146892997
|
||||
SEC_E_NO_PA_DATA = -2146892996
|
||||
SEC_E_PKINIT_NAME_MISMATCH = -2146892995
|
||||
SEC_E_SMARTCARD_LOGON_REQUIRED = -2146892994
|
||||
SEC_E_SHUTDOWN_IN_PROGRESS = -2146892993
|
||||
SEC_E_KDC_INVALID_REQUEST = -2146892992
|
||||
SEC_E_KDC_UNABLE_TO_REFER = -2146892991
|
||||
SEC_E_KDC_UNKNOWN_ETYPE = -2146892990
|
||||
SEC_E_UNSUPPORTED_PREAUTH = -2146892989
|
||||
SEC_E_DELEGATION_REQUIRED = -2146892987
|
||||
SEC_E_BAD_BINDINGS = -2146892986
|
||||
SEC_E_MULTIPLE_ACCOUNTS = -2146892985
|
||||
SEC_E_NO_KERB_KEY = -2146892984
|
||||
|
||||
ERROR_IPSEC_QM_POLICY_EXISTS = 13000
|
||||
ERROR_IPSEC_QM_POLICY_NOT_FOUND = 13001
|
||||
ERROR_IPSEC_QM_POLICY_IN_USE = 13002
|
||||
ERROR_IPSEC_MM_POLICY_EXISTS = 13003
|
||||
ERROR_IPSEC_MM_POLICY_NOT_FOUND = 13004
|
||||
ERROR_IPSEC_MM_POLICY_IN_USE = 13005
|
||||
ERROR_IPSEC_MM_FILTER_EXISTS = 13006
|
||||
ERROR_IPSEC_MM_FILTER_NOT_FOUND = 13007
|
||||
ERROR_IPSEC_TRANSPORT_FILTER_EXISTS = 13008
|
||||
ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND = 13009
|
||||
ERROR_IPSEC_MM_AUTH_EXISTS = 13010
|
||||
ERROR_IPSEC_MM_AUTH_NOT_FOUND = 13011
|
||||
ERROR_IPSEC_MM_AUTH_IN_USE = 13012
|
||||
ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND = 13013
|
||||
ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND = 13014
|
||||
ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND = 13015
|
||||
ERROR_IPSEC_TUNNEL_FILTER_EXISTS = 13016
|
||||
ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND = 13017
|
||||
ERROR_IPSEC_MM_FILTER_PENDING_DELETION = 13018
|
||||
ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION = 13019
|
||||
ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION = 13020
|
||||
ERROR_IPSEC_MM_POLICY_PENDING_DELETION = 13021
|
||||
ERROR_IPSEC_MM_AUTH_PENDING_DELETION = 13022
|
||||
ERROR_IPSEC_QM_POLICY_PENDING_DELETION = 13023
|
||||
WARNING_IPSEC_MM_POLICY_PRUNED = 13024
|
||||
WARNING_IPSEC_QM_POLICY_PRUNED = 13025
|
||||
ERROR_IPSEC_IKE_NEG_STATUS_BEGIN = 13800
|
||||
ERROR_IPSEC_IKE_AUTH_FAIL = 13801
|
||||
ERROR_IPSEC_IKE_ATTRIB_FAIL = 13802
|
||||
ERROR_IPSEC_IKE_NEGOTIATION_PENDING = 13803
|
||||
ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR = 13804
|
||||
ERROR_IPSEC_IKE_TIMED_OUT = 13805
|
||||
ERROR_IPSEC_IKE_NO_CERT = 13806
|
||||
ERROR_IPSEC_IKE_SA_DELETED = 13807
|
||||
ERROR_IPSEC_IKE_SA_REAPED = 13808
|
||||
ERROR_IPSEC_IKE_MM_ACQUIRE_DROP = 13809
|
||||
ERROR_IPSEC_IKE_QM_ACQUIRE_DROP = 13810
|
||||
ERROR_IPSEC_IKE_QUEUE_DROP_MM = 13811
|
||||
ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM = 13812
|
||||
ERROR_IPSEC_IKE_DROP_NO_RESPONSE = 13813
|
||||
ERROR_IPSEC_IKE_MM_DELAY_DROP = 13814
|
||||
ERROR_IPSEC_IKE_QM_DELAY_DROP = 13815
|
||||
ERROR_IPSEC_IKE_ERROR = 13816
|
||||
ERROR_IPSEC_IKE_CRL_FAILED = 13817
|
||||
ERROR_IPSEC_IKE_INVALID_KEY_USAGE = 13818
|
||||
ERROR_IPSEC_IKE_INVALID_CERT_TYPE = 13819
|
||||
ERROR_IPSEC_IKE_NO_PRIVATE_KEY = 13820
|
||||
ERROR_IPSEC_IKE_DH_FAIL = 13822
|
||||
ERROR_IPSEC_IKE_INVALID_HEADER = 13824
|
||||
ERROR_IPSEC_IKE_NO_POLICY = 13825
|
||||
ERROR_IPSEC_IKE_INVALID_SIGNATURE = 13826
|
||||
ERROR_IPSEC_IKE_KERBEROS_ERROR = 13827
|
||||
ERROR_IPSEC_IKE_NO_PUBLIC_KEY = 13828
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR = 13829
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_SA = 13830
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_PROP = 13831
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_TRANS = 13832
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_KE = 13833
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_ID = 13834
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_CERT = 13835
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ = 13836
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_HASH = 13837
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_SIG = 13838
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_NONCE = 13839
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY = 13840
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_DELETE = 13841
|
||||
ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR = 13842
|
||||
ERROR_IPSEC_IKE_INVALID_PAYLOAD = 13843
|
||||
ERROR_IPSEC_IKE_LOAD_SOFT_SA = 13844
|
||||
ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN = 13845
|
||||
ERROR_IPSEC_IKE_INVALID_COOKIE = 13846
|
||||
ERROR_IPSEC_IKE_NO_PEER_CERT = 13847
|
||||
ERROR_IPSEC_IKE_PEER_CRL_FAILED = 13848
|
||||
ERROR_IPSEC_IKE_POLICY_CHANGE = 13849
|
||||
ERROR_IPSEC_IKE_NO_MM_POLICY = 13850
|
||||
ERROR_IPSEC_IKE_NOTCBPRIV = 13851
|
||||
ERROR_IPSEC_IKE_SECLOADFAIL = 13852
|
||||
ERROR_IPSEC_IKE_FAILSSPINIT = 13853
|
||||
ERROR_IPSEC_IKE_FAILQUERYSSP = 13854
|
||||
ERROR_IPSEC_IKE_SRVACQFAIL = 13855
|
||||
ERROR_IPSEC_IKE_SRVQUERYCRED = 13856
|
||||
ERROR_IPSEC_IKE_GETSPIFAIL = 13857
|
||||
ERROR_IPSEC_IKE_INVALID_FILTER = 13858
|
||||
ERROR_IPSEC_IKE_OUT_OF_MEMORY = 13859
|
||||
ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED = 13860
|
||||
ERROR_IPSEC_IKE_INVALID_POLICY = 13861
|
||||
ERROR_IPSEC_IKE_UNKNOWN_DOI = 13862
|
||||
ERROR_IPSEC_IKE_INVALID_SITUATION = 13863
|
||||
ERROR_IPSEC_IKE_DH_FAILURE = 13864
|
||||
ERROR_IPSEC_IKE_INVALID_GROUP = 13865
|
||||
ERROR_IPSEC_IKE_ENCRYPT = 13866
|
||||
ERROR_IPSEC_IKE_DECRYPT = 13867
|
||||
ERROR_IPSEC_IKE_POLICY_MATCH = 13868
|
||||
ERROR_IPSEC_IKE_UNSUPPORTED_ID = 13869
|
||||
ERROR_IPSEC_IKE_INVALID_HASH = 13870
|
||||
ERROR_IPSEC_IKE_INVALID_HASH_ALG = 13871
|
||||
ERROR_IPSEC_IKE_INVALID_HASH_SIZE = 13872
|
||||
ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG = 13873
|
||||
ERROR_IPSEC_IKE_INVALID_AUTH_ALG = 13874
|
||||
ERROR_IPSEC_IKE_INVALID_SIG = 13875
|
||||
ERROR_IPSEC_IKE_LOAD_FAILED = 13876
|
||||
ERROR_IPSEC_IKE_RPC_DELETE = 13877
|
||||
ERROR_IPSEC_IKE_BENIGN_REINIT = 13878
|
||||
ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY = 13879
|
||||
ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN = 13881
|
||||
ERROR_IPSEC_IKE_MM_LIMIT = 13882
|
||||
ERROR_IPSEC_IKE_NEGOTIATION_DISABLED = 13883
|
||||
ERROR_IPSEC_IKE_NEG_STATUS_END = 13884
|
||||
CRYPT_E_MSG_ERROR = ((-2146889727))
|
||||
CRYPT_E_UNKNOWN_ALGO = ((-2146889726))
|
||||
CRYPT_E_OID_FORMAT = ((-2146889725))
|
||||
CRYPT_E_INVALID_MSG_TYPE = ((-2146889724))
|
||||
CRYPT_E_UNEXPECTED_ENCODING = ((-2146889723))
|
||||
CRYPT_E_AUTH_ATTR_MISSING = ((-2146889722))
|
||||
CRYPT_E_HASH_VALUE = ((-2146889721))
|
||||
CRYPT_E_INVALID_INDEX = ((-2146889720))
|
||||
CRYPT_E_ALREADY_DECRYPTED = ((-2146889719))
|
||||
CRYPT_E_NOT_DECRYPTED = ((-2146889718))
|
||||
CRYPT_E_RECIPIENT_NOT_FOUND = ((-2146889717))
|
||||
CRYPT_E_CONTROL_TYPE = ((-2146889716))
|
||||
CRYPT_E_ISSUER_SERIALNUMBER = ((-2146889715))
|
||||
CRYPT_E_SIGNER_NOT_FOUND = ((-2146889714))
|
||||
CRYPT_E_ATTRIBUTES_MISSING = ((-2146889713))
|
||||
CRYPT_E_STREAM_MSG_NOT_READY = ((-2146889712))
|
||||
CRYPT_E_STREAM_INSUFFICIENT_DATA = ((-2146889711))
|
||||
CRYPT_I_NEW_PROTECTION_REQUIRED = (593938)
|
||||
CRYPT_E_BAD_LEN = ((-2146885631))
|
||||
CRYPT_E_BAD_ENCODE = ((-2146885630))
|
||||
CRYPT_E_FILE_ERROR = ((-2146885629))
|
||||
CRYPT_E_NOT_FOUND = ((-2146885628))
|
||||
CRYPT_E_EXISTS = ((-2146885627))
|
||||
CRYPT_E_NO_PROVIDER = ((-2146885626))
|
||||
CRYPT_E_SELF_SIGNED = ((-2146885625))
|
||||
CRYPT_E_DELETED_PREV = ((-2146885624))
|
||||
CRYPT_E_NO_MATCH = ((-2146885623))
|
||||
CRYPT_E_UNEXPECTED_MSG_TYPE = ((-2146885622))
|
||||
CRYPT_E_NO_KEY_PROPERTY = ((-2146885621))
|
||||
CRYPT_E_NO_DECRYPT_CERT = ((-2146885620))
|
||||
CRYPT_E_BAD_MSG = ((-2146885619))
|
||||
CRYPT_E_NO_SIGNER = ((-2146885618))
|
||||
CRYPT_E_PENDING_CLOSE = ((-2146885617))
|
||||
CRYPT_E_REVOKED = ((-2146885616))
|
||||
CRYPT_E_NO_REVOCATION_DLL = ((-2146885615))
|
||||
CRYPT_E_NO_REVOCATION_CHECK = ((-2146885614))
|
||||
CRYPT_E_REVOCATION_OFFLINE = ((-2146885613))
|
||||
CRYPT_E_NOT_IN_REVOCATION_DATABASE = ((-2146885612))
|
||||
CRYPT_E_INVALID_NUMERIC_STRING = ((-2146885600))
|
||||
CRYPT_E_INVALID_PRINTABLE_STRING = ((-2146885599))
|
||||
CRYPT_E_INVALID_IA5_STRING = ((-2146885598))
|
||||
CRYPT_E_INVALID_X500_STRING = ((-2146885597))
|
||||
CRYPT_E_NOT_CHAR_STRING = ((-2146885596))
|
||||
CRYPT_E_FILERESIZED = ((-2146885595))
|
||||
CRYPT_E_SECURITY_SETTINGS = ((-2146885594))
|
||||
CRYPT_E_NO_VERIFY_USAGE_DLL = ((-2146885593))
|
||||
CRYPT_E_NO_VERIFY_USAGE_CHECK = ((-2146885592))
|
||||
CRYPT_E_VERIFY_USAGE_OFFLINE = ((-2146885591))
|
||||
CRYPT_E_NOT_IN_CTL = ((-2146885590))
|
||||
CRYPT_E_NO_TRUSTED_SIGNER = ((-2146885589))
|
||||
CRYPT_E_MISSING_PUBKEY_PARA = ((-2146885588))
|
||||
CRYPT_E_OSS_ERROR = ((-2146881536))
|
||||
|
||||
## Kerberos message types for LsaCallAuthenticationPackage (from ntsecapi.h)
|
||||
KerbDebugRequestMessage = 0
|
||||
KerbQueryTicketCacheMessage = 1
|
||||
KerbChangeMachinePasswordMessage = 2
|
||||
KerbVerifyPacMessage = 3
|
||||
KerbRetrieveTicketMessage = 4
|
||||
KerbUpdateAddressesMessage = 5
|
||||
KerbPurgeTicketCacheMessage = 6
|
||||
KerbChangePasswordMessage = 7
|
||||
KerbRetrieveEncodedTicketMessage = 8
|
||||
KerbDecryptDataMessage = 9
|
||||
KerbAddBindingCacheEntryMessage = 10
|
||||
KerbSetPasswordMessage = 11
|
||||
KerbSetPasswordExMessage = 12
|
||||
KerbVerifyCredentialsMessage = 13
|
||||
KerbQueryTicketCacheExMessage = 14
|
||||
KerbPurgeTicketCacheExMessage = 15
|
||||
KerbRefreshSmartcardCredentialsMessage = 16
|
||||
KerbAddExtraCredentialsMessage = 17
|
||||
KerbQuerySupplementalCredentialsMessage = 18
|
||||
|
||||
## messages used with msv1_0 from ntsecapi.h
|
||||
MsV1_0Lm20ChallengeRequest = 0
|
||||
MsV1_0Lm20GetChallengeResponse = 1
|
||||
MsV1_0EnumerateUsers = 2
|
||||
MsV1_0GetUserInfo = 3
|
||||
MsV1_0ReLogonUsers = 4
|
||||
MsV1_0ChangePassword = 5
|
||||
MsV1_0ChangeCachedPassword = 6
|
||||
MsV1_0GenericPassthrough = 7
|
||||
MsV1_0CacheLogon = 8
|
||||
MsV1_0SubAuth = 9
|
||||
MsV1_0DeriveCredential = 10
|
||||
MsV1_0CacheLookup = 11
|
||||
MsV1_0SetProcessOption = 12
|
||||
|
||||
SEC_E_OK = 0
|
||||
5033
Pywin32/lib/x32/win32/lib/win32con.py
Normal file
1671
Pywin32/lib/x32/win32/lib/win32cryptcon.py
Normal file
152
Pywin32/lib/x32/win32/lib/win32evtlogutil.py
Normal file
@@ -0,0 +1,152 @@
|
||||
"""Event Log Utilities - helper for win32evtlog.pyd
|
||||
"""
|
||||
|
||||
import win32api, win32con, winerror, win32evtlog
|
||||
|
||||
error = win32api.error # The error the evtlog module raises.
|
||||
|
||||
langid = win32api.MAKELANGID(win32con.LANG_NEUTRAL, win32con.SUBLANG_NEUTRAL)
|
||||
|
||||
def AddSourceToRegistry(appName, msgDLL = None, eventLogType = "Application", eventLogFlags = None):
|
||||
"""Add a source of messages to the event log.
|
||||
|
||||
Allows Python program to register a custom source of messages in the
|
||||
registry. You must also provide the DLL name that has the message table, so the
|
||||
full message text appears in the event log.
|
||||
|
||||
Note that the win32evtlog.pyd file has a number of string entries with just "%1"
|
||||
built in, so many Python programs can simply use this DLL. Disadvantages are that
|
||||
you do not get language translation, and the full text is stored in the event log,
|
||||
blowing the size of the log up.
|
||||
"""
|
||||
|
||||
# When an application uses the RegisterEventSource or OpenEventLog
|
||||
# function to get a handle of an event log, the event loggging service
|
||||
# searches for the specified source name in the registry. You can add a
|
||||
# new source name to the registry by opening a new registry subkey
|
||||
# under the Application key and adding registry values to the new
|
||||
# subkey.
|
||||
|
||||
if msgDLL is None:
|
||||
msgDLL = win32evtlog.__file__
|
||||
|
||||
# Create a new key for our application
|
||||
hkey = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, \
|
||||
"SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
|
||||
|
||||
# Add the Event-ID message-file name to the subkey.
|
||||
win32api.RegSetValueEx(hkey,
|
||||
"EventMessageFile", # value name \
|
||||
0, # reserved \
|
||||
win32con.REG_EXPAND_SZ,# value type \
|
||||
msgDLL)
|
||||
|
||||
# Set the supported types flags and add it to the subkey.
|
||||
if eventLogFlags is None:
|
||||
eventLogFlags = win32evtlog.EVENTLOG_ERROR_TYPE | win32evtlog.EVENTLOG_WARNING_TYPE | win32evtlog.EVENTLOG_INFORMATION_TYPE
|
||||
win32api.RegSetValueEx(hkey, # subkey handle \
|
||||
"TypesSupported", # value name \
|
||||
0, # reserved \
|
||||
win32con.REG_DWORD, # value type \
|
||||
eventLogFlags)
|
||||
win32api.RegCloseKey(hkey)
|
||||
|
||||
def RemoveSourceFromRegistry(appName, eventLogType = "Application"):
|
||||
"""Removes a source of messages from the event log.
|
||||
"""
|
||||
|
||||
# Delete our key
|
||||
try:
|
||||
win32api.RegDeleteKey(win32con.HKEY_LOCAL_MACHINE, \
|
||||
"SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (eventLogType, appName))
|
||||
except win32api.error as exc:
|
||||
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
|
||||
raise
|
||||
|
||||
|
||||
def ReportEvent(appName, eventID, eventCategory = 0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings = None, data = None, sid=None):
|
||||
"""Report an event for a previously added event source.
|
||||
"""
|
||||
# Get a handle to the Application event log
|
||||
hAppLog = win32evtlog.RegisterEventSource(None, appName)
|
||||
|
||||
# Now report the event, which will add this event to the event log */
|
||||
win32evtlog.ReportEvent(hAppLog, # event-log handle \
|
||||
eventType,
|
||||
eventCategory,
|
||||
eventID,
|
||||
sid,
|
||||
strings,
|
||||
data)
|
||||
|
||||
win32evtlog.DeregisterEventSource(hAppLog);
|
||||
|
||||
def FormatMessage( eventLogRecord, logType="Application" ):
|
||||
"""Given a tuple from ReadEventLog, and optionally where the event
|
||||
record came from, load the message, and process message inserts.
|
||||
|
||||
Note that this function may raise win32api.error. See also the
|
||||
function SafeFormatMessage which will return None if the message can
|
||||
not be processed.
|
||||
"""
|
||||
|
||||
# From the event log source name, we know the name of the registry
|
||||
# key to look under for the name of the message DLL that contains
|
||||
# the messages we need to extract with FormatMessage. So first get
|
||||
# the event log source name...
|
||||
keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (logType, eventLogRecord.SourceName)
|
||||
|
||||
# Now open this key and get the EventMessageFile value, which is
|
||||
# the name of the message DLL.
|
||||
handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
|
||||
try:
|
||||
dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";")
|
||||
# Win2k etc appear to allow multiple DLL names
|
||||
data = None
|
||||
for dllName in dllNames:
|
||||
try:
|
||||
# Expand environment variable strings in the message DLL path name,
|
||||
# in case any are there.
|
||||
dllName = win32api.ExpandEnvironmentStrings(dllName)
|
||||
|
||||
dllHandle = win32api.LoadLibraryEx(dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE)
|
||||
try:
|
||||
data = win32api.FormatMessageW(win32con.FORMAT_MESSAGE_FROM_HMODULE,
|
||||
dllHandle, eventLogRecord.EventID, langid, eventLogRecord.StringInserts)
|
||||
finally:
|
||||
win32api.FreeLibrary(dllHandle)
|
||||
except win32api.error:
|
||||
pass # Not in this DLL - try the next
|
||||
if data is not None:
|
||||
break
|
||||
finally:
|
||||
win32api.RegCloseKey(handle)
|
||||
return data or '' # Don't want "None" ever being returned.
|
||||
|
||||
def SafeFormatMessage( eventLogRecord, logType=None ):
|
||||
"""As for FormatMessage, except returns an error message if
|
||||
the message can not be processed.
|
||||
"""
|
||||
if logType is None: logType = "Application"
|
||||
try:
|
||||
return FormatMessage(eventLogRecord, logType)
|
||||
except win32api.error:
|
||||
if eventLogRecord.StringInserts is None:
|
||||
desc = ""
|
||||
else:
|
||||
desc = ", ".join(eventLogRecord.StringInserts)
|
||||
return "<The description for Event ID ( %d ) in Source ( %r ) could not be found. It contains the following insertion string(s):%r.>" % (winerror.HRESULT_CODE(eventLogRecord.EventID), eventLogRecord.SourceName, desc)
|
||||
|
||||
def FeedEventLogRecords(feeder, machineName = None, logName = "Application", readFlags = None):
|
||||
if readFlags is None:
|
||||
readFlags = win32evtlog.EVENTLOG_BACKWARDS_READ|win32evtlog.EVENTLOG_SEQUENTIAL_READ
|
||||
|
||||
h=win32evtlog.OpenEventLog(machineName, logName)
|
||||
try:
|
||||
while 1:
|
||||
objects = win32evtlog.ReadEventLog(h, readFlags, 0)
|
||||
if not objects:
|
||||
break
|
||||
map(lambda item, feeder = feeder: feeder(*(item,)), objects)
|
||||
finally:
|
||||
win32evtlog.CloseEventLog(h)
|
||||
729
Pywin32/lib/x32/win32/lib/win32gui_struct.py
Normal file
@@ -0,0 +1,729 @@
|
||||
# This is a work in progress - see Demos/win32gui_menu.py
|
||||
|
||||
# win32gui_struct.py - helpers for working with various win32gui structures.
|
||||
# As win32gui is "light-weight", it does not define objects for all possible
|
||||
# win32 structures - in general, "buffer" objects are passed around - it is
|
||||
# the callers responsibility to pack the buffer in the correct format.
|
||||
#
|
||||
# This module defines some helpers for the commonly used structures.
|
||||
#
|
||||
# In general, each structure has 3 functions:
|
||||
#
|
||||
# buffer, extras = PackSTRUCTURE(items, ...)
|
||||
# item, ... = UnpackSTRUCTURE(buffer)
|
||||
# buffer, extras = EmtpySTRUCTURE(...)
|
||||
#
|
||||
# 'extras' is always items that must be held along with the buffer, as the
|
||||
# buffer refers to these object's memory.
|
||||
# For structures that support a 'mask', this mask is hidden from the user - if
|
||||
# 'None' is passed, the mask flag will not be set, or on return, None will
|
||||
# be returned for the value if the mask is not set.
|
||||
#
|
||||
# NOTE: I considered making these structures look like real classes, and
|
||||
# support 'attributes' etc - however, ctypes already has a good structure
|
||||
# mechanism - I think it makes more sense to support ctype structures
|
||||
# at the win32gui level, then there will be no need for this module at all.
|
||||
# XXX - the above makes sense in terms of what is built and passed to
|
||||
# win32gui (ie, the Pack* functions) - but doesn't make as much sense for
|
||||
# the Unpack* functions, where the aim is user convenience.
|
||||
|
||||
import sys
|
||||
import win32gui
|
||||
import win32con
|
||||
import struct
|
||||
import array
|
||||
import commctrl
|
||||
import pywintypes
|
||||
|
||||
is64bit = "64 bit" in sys.version
|
||||
|
||||
try:
|
||||
from collections import namedtuple
|
||||
def _MakeResult(names_str, values):
|
||||
names = names_str.split()
|
||||
nt = namedtuple(names[0], names[1:])
|
||||
return nt(*values)
|
||||
except ImportError:
|
||||
# no namedtuple support - just return the values as a normal tuple.
|
||||
def _MakeResult(names_str, values):
|
||||
return values
|
||||
|
||||
_nmhdr_fmt = "PPi"
|
||||
if is64bit:
|
||||
# When the item past the NMHDR gets aligned (eg, when it is a struct)
|
||||
# we need this many bytes padding.
|
||||
_nmhdr_align_padding = "xxxx"
|
||||
else:
|
||||
_nmhdr_align_padding = ""
|
||||
|
||||
# Encode a string suitable for passing in a win32gui related structure
|
||||
# If win32gui is built with UNICODE defined (ie, py3k), then functions
|
||||
# like InsertMenuItem are actually calling InsertMenuItemW etc, so all
|
||||
# strings will need to be unicode.
|
||||
if win32gui.UNICODE:
|
||||
def _make_text_buffer(text):
|
||||
# XXX - at this stage win32gui.UNICODE is only True in py3k,
|
||||
# and in py3k is makes sense to reject bytes.
|
||||
if not isinstance(text, str):
|
||||
raise TypeError('MENUITEMINFO text must be unicode')
|
||||
data = (text+'\0').encode("unicode-internal")
|
||||
return array.array("b", data)
|
||||
|
||||
else:
|
||||
def _make_text_buffer(text):
|
||||
if isinstance(text, str):
|
||||
text = text.encode("mbcs")
|
||||
return array.array("b", text+'\0')
|
||||
|
||||
# make an 'empty' buffer, ready for filling with cch characters.
|
||||
def _make_empty_text_buffer(cch):
|
||||
return _make_text_buffer("\0" * cch)
|
||||
|
||||
if sys.version_info < (3,0):
|
||||
def _make_memory(ob):
|
||||
return str(buffer(ob))
|
||||
|
||||
def _make_bytes(sval):
|
||||
return sval
|
||||
else:
|
||||
def _make_memory(ob):
|
||||
return bytes(memoryview(ob))
|
||||
|
||||
def _make_bytes(sval):
|
||||
return sval.encode('ascii')
|
||||
|
||||
# Generic WM_NOTIFY unpacking
|
||||
def UnpackWMNOTIFY(lparam):
|
||||
format = "PPi"
|
||||
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
|
||||
return _MakeResult("WMNOTIFY hwndFrom idFrom code", struct.unpack(format, buf))
|
||||
|
||||
def UnpackNMITEMACTIVATE(lparam):
|
||||
format = _nmhdr_fmt + _nmhdr_align_padding
|
||||
if is64bit:
|
||||
# the struct module doesn't handle this correctly as some of the items
|
||||
# are actually structs in structs, which get individually aligned.
|
||||
format = format + "iiiiiiixxxxP"
|
||||
else:
|
||||
format = format + "iiiiiiiP"
|
||||
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
|
||||
return _MakeResult("NMITEMACTIVATE hwndFrom idFrom code iItem iSubItem uNewState uOldState uChanged actionx actiony lParam",
|
||||
struct.unpack(format, buf))
|
||||
|
||||
# MENUITEMINFO struct
|
||||
# http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/Resources/Menus/MenuReference/MenuStructures/MENUITEMINFO.asp
|
||||
# We use the struct module to pack and unpack strings as MENUITEMINFO
|
||||
# structures. We also have special handling for the 'fMask' item in that
|
||||
# structure to avoid the caller needing to explicitly check validity
|
||||
# (None is used if the mask excludes/should exclude the value)
|
||||
_menuiteminfo_fmt = '5i5PiP'
|
||||
|
||||
def PackMENUITEMINFO(fType=None, fState=None, wID=None, hSubMenu=None,
|
||||
hbmpChecked=None, hbmpUnchecked=None, dwItemData=None,
|
||||
text=None, hbmpItem=None, dwTypeData=None):
|
||||
# 'extras' are objects the caller must keep a reference to (as their
|
||||
# memory is used) for the lifetime of the INFO item.
|
||||
extras = []
|
||||
# ack - dwItemData and dwTypeData were confused for a while...
|
||||
assert dwItemData is None or dwTypeData is None, \
|
||||
"sorry - these were confused - you probably want dwItemData"
|
||||
# if we are a long way past 209, then we can nuke the above...
|
||||
if dwTypeData is not None:
|
||||
import warnings
|
||||
warnings.warn("PackMENUITEMINFO: please use dwItemData instead of dwTypeData")
|
||||
if dwItemData is None:
|
||||
dwItemData = dwTypeData or 0
|
||||
|
||||
fMask = 0
|
||||
if fType is None: fType = 0
|
||||
else: fMask |= win32con.MIIM_FTYPE
|
||||
if fState is None: fState = 0
|
||||
else: fMask |= win32con.MIIM_STATE
|
||||
if wID is None: wID = 0
|
||||
else: fMask |= win32con.MIIM_ID
|
||||
if hSubMenu is None: hSubMenu = 0
|
||||
else: fMask |= win32con.MIIM_SUBMENU
|
||||
if hbmpChecked is None:
|
||||
assert hbmpUnchecked is None, \
|
||||
"neither or both checkmark bmps must be given"
|
||||
hbmpChecked = hbmpUnchecked = 0
|
||||
else:
|
||||
assert hbmpUnchecked is not None, \
|
||||
"neither or both checkmark bmps must be given"
|
||||
fMask |= win32con.MIIM_CHECKMARKS
|
||||
if dwItemData is None: dwItemData = 0
|
||||
else: fMask |= win32con.MIIM_DATA
|
||||
if hbmpItem is None: hbmpItem = 0
|
||||
else: fMask |= win32con.MIIM_BITMAP
|
||||
if text is not None:
|
||||
fMask |= win32con.MIIM_STRING
|
||||
str_buf = _make_text_buffer(text)
|
||||
cch = len(text)
|
||||
# We are taking address of strbuf - it must not die until windows
|
||||
# has finished with our structure.
|
||||
lptext = str_buf.buffer_info()[0]
|
||||
extras.append(str_buf)
|
||||
else:
|
||||
lptext = 0
|
||||
cch = 0
|
||||
# Create the struct.
|
||||
# 'P' format does not accept PyHANDLE's !
|
||||
item = struct.pack(
|
||||
_menuiteminfo_fmt,
|
||||
struct.calcsize(_menuiteminfo_fmt), # cbSize
|
||||
fMask,
|
||||
fType,
|
||||
fState,
|
||||
wID,
|
||||
int(hSubMenu),
|
||||
int(hbmpChecked),
|
||||
int(hbmpUnchecked),
|
||||
dwItemData,
|
||||
lptext,
|
||||
cch,
|
||||
int(hbmpItem)
|
||||
)
|
||||
# Now copy the string to a writable buffer, so that the result
|
||||
# could be passed to a 'Get' function
|
||||
return array.array("b", item), extras
|
||||
|
||||
def UnpackMENUITEMINFO(s):
|
||||
(cb,
|
||||
fMask,
|
||||
fType,
|
||||
fState,
|
||||
wID,
|
||||
hSubMenu,
|
||||
hbmpChecked,
|
||||
hbmpUnchecked,
|
||||
dwItemData,
|
||||
lptext,
|
||||
cch,
|
||||
hbmpItem) = struct.unpack(_menuiteminfo_fmt, s)
|
||||
assert cb==len(s)
|
||||
if fMask & win32con.MIIM_FTYPE==0: fType = None
|
||||
if fMask & win32con.MIIM_STATE==0: fState = None
|
||||
if fMask & win32con.MIIM_ID==0: wID = None
|
||||
if fMask & win32con.MIIM_SUBMENU==0: hSubMenu = None
|
||||
if fMask & win32con.MIIM_CHECKMARKS==0: hbmpChecked = hbmpUnchecked = None
|
||||
if fMask & win32con.MIIM_DATA==0: dwItemData = None
|
||||
if fMask & win32con.MIIM_BITMAP==0: hbmpItem = None
|
||||
if fMask & win32con.MIIM_STRING:
|
||||
text = win32gui.PyGetString(lptext, cch)
|
||||
else:
|
||||
text = None
|
||||
return _MakeResult("MENUITEMINFO fType fState wID hSubMenu hbmpChecked "
|
||||
"hbmpUnchecked dwItemData text hbmpItem",
|
||||
(fType, fState, wID, hSubMenu, hbmpChecked, hbmpUnchecked, \
|
||||
dwItemData, text, hbmpItem))
|
||||
|
||||
def EmptyMENUITEMINFO(mask = None, text_buf_size=512):
|
||||
# text_buf_size is number of *characters* - not necessarily no of bytes.
|
||||
extra = []
|
||||
if mask is None:
|
||||
mask = win32con.MIIM_BITMAP | win32con.MIIM_CHECKMARKS | \
|
||||
win32con.MIIM_DATA | win32con.MIIM_FTYPE | \
|
||||
win32con.MIIM_ID | win32con.MIIM_STATE | \
|
||||
win32con.MIIM_STRING | win32con.MIIM_SUBMENU
|
||||
# Note: No MIIM_TYPE - this screws win2k/98.
|
||||
|
||||
if mask & win32con.MIIM_STRING:
|
||||
text_buffer = _make_empty_text_buffer(text_buf_size)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
else:
|
||||
text_addr = text_buf_size = 0
|
||||
|
||||
# Now copy the string to a writable buffer, so that the result
|
||||
# could be passed to a 'Get' function
|
||||
buf = struct.pack(
|
||||
_menuiteminfo_fmt,
|
||||
struct.calcsize(_menuiteminfo_fmt), # cbSize
|
||||
mask,
|
||||
0, #fType,
|
||||
0, #fState,
|
||||
0, #wID,
|
||||
0, #hSubMenu,
|
||||
0, #hbmpChecked,
|
||||
0, #hbmpUnchecked,
|
||||
0, #dwItemData,
|
||||
text_addr,
|
||||
text_buf_size,
|
||||
0, #hbmpItem
|
||||
)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
# MENUINFO struct
|
||||
_menuinfo_fmt = 'iiiiPiP'
|
||||
|
||||
def PackMENUINFO(dwStyle = None, cyMax = None,
|
||||
hbrBack = None, dwContextHelpID = None, dwMenuData = None,
|
||||
fMask = 0):
|
||||
if dwStyle is None: dwStyle = 0
|
||||
else: fMask |= win32con.MIM_STYLE
|
||||
if cyMax is None: cyMax = 0
|
||||
else: fMask |= win32con.MIM_MAXHEIGHT
|
||||
if hbrBack is None: hbrBack = 0
|
||||
else: fMask |= win32con.MIM_BACKGROUND
|
||||
if dwContextHelpID is None: dwContextHelpID = 0
|
||||
else: fMask |= win32con.MIM_HELPID
|
||||
if dwMenuData is None: dwMenuData = 0
|
||||
else: fMask |= win32con.MIM_MENUDATA
|
||||
# Create the struct.
|
||||
item = struct.pack(
|
||||
_menuinfo_fmt,
|
||||
struct.calcsize(_menuinfo_fmt), # cbSize
|
||||
fMask,
|
||||
dwStyle,
|
||||
cyMax,
|
||||
hbrBack,
|
||||
dwContextHelpID,
|
||||
dwMenuData)
|
||||
return array.array("b", item)
|
||||
|
||||
def UnpackMENUINFO(s):
|
||||
(cb,
|
||||
fMask,
|
||||
dwStyle,
|
||||
cyMax,
|
||||
hbrBack,
|
||||
dwContextHelpID,
|
||||
dwMenuData) = struct.unpack(_menuinfo_fmt, s)
|
||||
assert cb==len(s)
|
||||
if fMask & win32con.MIM_STYLE==0: dwStyle = None
|
||||
if fMask & win32con.MIM_MAXHEIGHT==0: cyMax = None
|
||||
if fMask & win32con.MIM_BACKGROUND==0: hbrBack = None
|
||||
if fMask & win32con.MIM_HELPID==0: dwContextHelpID = None
|
||||
if fMask & win32con.MIM_MENUDATA==0: dwMenuData = None
|
||||
return _MakeResult("MENUINFO dwStyle cyMax hbrBack dwContextHelpID dwMenuData",
|
||||
(dwStyle, cyMax, hbrBack, dwContextHelpID, dwMenuData))
|
||||
|
||||
def EmptyMENUINFO(mask = None):
|
||||
if mask is None:
|
||||
mask = win32con.MIM_STYLE | win32con.MIM_MAXHEIGHT| \
|
||||
win32con.MIM_BACKGROUND | win32con.MIM_HELPID | \
|
||||
win32con.MIM_MENUDATA
|
||||
|
||||
buf = struct.pack(
|
||||
_menuinfo_fmt,
|
||||
struct.calcsize(_menuinfo_fmt), # cbSize
|
||||
mask,
|
||||
0, #dwStyle
|
||||
0, #cyMax
|
||||
0, #hbrBack,
|
||||
0, #dwContextHelpID,
|
||||
0, #dwMenuData,
|
||||
)
|
||||
return array.array("b", buf)
|
||||
|
||||
##########################################################################
|
||||
#
|
||||
# Tree View structure support - TVITEM, TVINSERTSTRUCT and TVDISPINFO
|
||||
#
|
||||
##########################################################################
|
||||
|
||||
# XXX - Note that the following implementation of TreeView structures is ripped
|
||||
# XXX - from the SpamBayes project. It may not quite work correctly yet - I
|
||||
# XXX - intend checking them later - but having them is better than not at all!
|
||||
|
||||
_tvitem_fmt = "iPiiPiiiiP"
|
||||
# Helpers for the ugly win32 structure packing/unpacking
|
||||
# XXX - Note that functions using _GetMaskAndVal run 3x faster if they are
|
||||
# 'inlined' into the function - see PackLVITEM. If the profiler points at
|
||||
# _GetMaskAndVal(), you should nuke it (patches welcome once they have been
|
||||
# tested)
|
||||
def _GetMaskAndVal(val, default, mask, flag):
|
||||
if val is None:
|
||||
return mask, default
|
||||
else:
|
||||
if flag is not None:
|
||||
mask |= flag
|
||||
return mask, val
|
||||
|
||||
def PackTVINSERTSTRUCT(parent, insertAfter, tvitem):
|
||||
tvitem_buf, extra = PackTVITEM(*tvitem)
|
||||
tvitem_buf = tvitem_buf.tostring()
|
||||
format = "PP%ds" % len(tvitem_buf)
|
||||
return struct.pack(format, parent, insertAfter, tvitem_buf), extra
|
||||
|
||||
def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param):
|
||||
extra = [] # objects we must keep references to
|
||||
mask = 0
|
||||
mask, hitem = _GetMaskAndVal(hitem, 0, mask, commctrl.TVIF_HANDLE)
|
||||
mask, state = _GetMaskAndVal(state, 0, mask, commctrl.TVIF_STATE)
|
||||
if not mask & commctrl.TVIF_STATE:
|
||||
stateMask = 0
|
||||
mask, text = _GetMaskAndVal(text, None, mask, commctrl.TVIF_TEXT)
|
||||
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.TVIF_IMAGE)
|
||||
mask, selimage = _GetMaskAndVal(selimage, 0, mask, commctrl.TVIF_SELECTEDIMAGE)
|
||||
mask, citems = _GetMaskAndVal(citems, 0, mask, commctrl.TVIF_CHILDREN)
|
||||
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.TVIF_PARAM)
|
||||
if text is None:
|
||||
text_addr = text_len = 0
|
||||
else:
|
||||
text_buffer = _make_text_buffer(text)
|
||||
text_len = len(text)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
buf = struct.pack(_tvitem_fmt,
|
||||
mask, hitem,
|
||||
state, stateMask,
|
||||
text_addr, text_len, # text
|
||||
image, selimage,
|
||||
citems, param)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
# Make a new buffer suitable for querying hitem's attributes.
|
||||
def EmptyTVITEM(hitem, mask = None, text_buf_size=512):
|
||||
extra = [] # objects we must keep references to
|
||||
if mask is None:
|
||||
mask = commctrl.TVIF_HANDLE | commctrl.TVIF_STATE | commctrl.TVIF_TEXT | \
|
||||
commctrl.TVIF_IMAGE | commctrl.TVIF_SELECTEDIMAGE | \
|
||||
commctrl.TVIF_CHILDREN | commctrl.TVIF_PARAM
|
||||
if mask & commctrl.TVIF_TEXT:
|
||||
text_buffer = _make_empty_text_buffer(text_buf_size)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
else:
|
||||
text_addr = text_buf_size = 0
|
||||
buf = struct.pack(_tvitem_fmt,
|
||||
mask, hitem,
|
||||
0, 0,
|
||||
text_addr, text_buf_size, # text
|
||||
0, 0,
|
||||
0, 0)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
def UnpackTVITEM(buffer):
|
||||
item_mask, item_hItem, item_state, item_stateMask, \
|
||||
item_textptr, item_cchText, item_image, item_selimage, \
|
||||
item_cChildren, item_param = struct.unpack(_tvitem_fmt, buffer)
|
||||
# ensure only items listed by the mask are valid (except we assume the
|
||||
# handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a
|
||||
# mask that doesn't include the handle, but the docs explicity say it is.)
|
||||
if not (item_mask & commctrl.TVIF_TEXT): item_textptr = item_cchText = None
|
||||
if not (item_mask & commctrl.TVIF_CHILDREN): item_cChildren = None
|
||||
if not (item_mask & commctrl.TVIF_IMAGE): item_image = None
|
||||
if not (item_mask & commctrl.TVIF_PARAM): item_param = None
|
||||
if not (item_mask & commctrl.TVIF_SELECTEDIMAGE): item_selimage = None
|
||||
if not (item_mask & commctrl.TVIF_STATE): item_state = item_stateMask = None
|
||||
|
||||
if item_textptr:
|
||||
text = win32gui.PyGetString(item_textptr)
|
||||
else:
|
||||
text = None
|
||||
return _MakeResult("TVITEM item_hItem item_state item_stateMask "
|
||||
"text item_image item_selimage item_cChildren item_param",
|
||||
(item_hItem, item_state, item_stateMask, text,
|
||||
item_image, item_selimage, item_cChildren, item_param))
|
||||
|
||||
# Unpack the lparm from a "TVNOTIFY" message
|
||||
def UnpackTVNOTIFY(lparam):
|
||||
item_size = struct.calcsize(_tvitem_fmt)
|
||||
format = _nmhdr_fmt + _nmhdr_align_padding
|
||||
if is64bit:
|
||||
format = format + "ixxxx"
|
||||
else:
|
||||
format = format + "i"
|
||||
format = format + "%ds%ds" % (item_size, item_size)
|
||||
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
|
||||
hwndFrom, id, code, action, buf_old, buf_new \
|
||||
= struct.unpack(format, buf)
|
||||
item_old = UnpackTVITEM(buf_old)
|
||||
item_new = UnpackTVITEM(buf_new)
|
||||
return _MakeResult("TVNOTIFY hwndFrom id code action item_old item_new",
|
||||
(hwndFrom, id, code, action, item_old, item_new))
|
||||
|
||||
def UnpackTVDISPINFO(lparam):
|
||||
item_size = struct.calcsize(_tvitem_fmt)
|
||||
format = "PPi%ds" % (item_size,)
|
||||
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
|
||||
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
|
||||
item = UnpackTVITEM(buf_item)
|
||||
return _MakeResult("TVDISPINFO hwndFrom id code item",
|
||||
(hwndFrom, id, code, item))
|
||||
|
||||
#
|
||||
# List view items
|
||||
_lvitem_fmt = "iiiiiPiiPi"
|
||||
|
||||
def PackLVITEM(item=None, subItem=None, state=None, stateMask=None, text=None, image=None, param=None, indent=None):
|
||||
extra = [] # objects we must keep references to
|
||||
mask = 0
|
||||
# _GetMaskAndVal adds quite a bit of overhead to this function.
|
||||
if item is None: item = 0 # No mask for item
|
||||
if subItem is None: subItem = 0 # No mask for sibItem
|
||||
if state is None:
|
||||
state = 0
|
||||
stateMask = 0
|
||||
else:
|
||||
mask |= commctrl.LVIF_STATE
|
||||
if stateMask is None: stateMask = state
|
||||
|
||||
if image is None: image = 0
|
||||
else: mask |= commctrl.LVIF_IMAGE
|
||||
if param is None: param = 0
|
||||
else: mask |= commctrl.LVIF_PARAM
|
||||
if indent is None: indent = 0
|
||||
else: mask |= commctrl.LVIF_INDENT
|
||||
|
||||
if text is None:
|
||||
text_addr = text_len = 0
|
||||
else:
|
||||
mask |= commctrl.LVIF_TEXT
|
||||
text_buffer = _make_text_buffer(text)
|
||||
text_len = len(text)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
buf = struct.pack(_lvitem_fmt,
|
||||
mask, item, subItem,
|
||||
state, stateMask,
|
||||
text_addr, text_len, # text
|
||||
image, param, indent)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
def UnpackLVITEM(buffer):
|
||||
item_mask, item_item, item_subItem, \
|
||||
item_state, item_stateMask, \
|
||||
item_textptr, item_cchText, item_image, \
|
||||
item_param, item_indent = struct.unpack(_lvitem_fmt, buffer)
|
||||
# ensure only items listed by the mask are valid
|
||||
if not (item_mask & commctrl.LVIF_TEXT): item_textptr = item_cchText = None
|
||||
if not (item_mask & commctrl.LVIF_IMAGE): item_image = None
|
||||
if not (item_mask & commctrl.LVIF_PARAM): item_param = None
|
||||
if not (item_mask & commctrl.LVIF_INDENT): item_indent = None
|
||||
if not (item_mask & commctrl.LVIF_STATE): item_state = item_stateMask = None
|
||||
|
||||
if item_textptr:
|
||||
text = win32gui.PyGetString(item_textptr)
|
||||
else:
|
||||
text = None
|
||||
return _MakeResult("LVITEM item_item item_subItem item_state "
|
||||
"item_stateMask text item_image item_param item_indent",
|
||||
(item_item, item_subItem, item_state, item_stateMask,
|
||||
text, item_image, item_param, item_indent))
|
||||
|
||||
# Unpack an "LVNOTIFY" message
|
||||
def UnpackLVDISPINFO(lparam):
|
||||
item_size = struct.calcsize(_lvitem_fmt)
|
||||
format = _nmhdr_fmt + _nmhdr_align_padding + ("%ds" % (item_size,))
|
||||
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
|
||||
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
|
||||
item = UnpackLVITEM(buf_item)
|
||||
return _MakeResult("LVDISPINFO hwndFrom id code item",
|
||||
(hwndFrom, id, code, item))
|
||||
|
||||
def UnpackLVNOTIFY(lparam):
|
||||
format = _nmhdr_fmt + _nmhdr_align_padding + "7i"
|
||||
if is64bit:
|
||||
format = format + "xxxx" # point needs padding.
|
||||
format = format + "P"
|
||||
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
|
||||
hwndFrom, id, code, item, subitem, newstate, oldstate, \
|
||||
changed, pt_x, pt_y, lparam = struct.unpack(format, buf)
|
||||
return _MakeResult("UnpackLVNOTIFY hwndFrom id code item subitem "
|
||||
"newstate oldstate changed pt lparam",
|
||||
(hwndFrom, id, code, item, subitem, newstate, oldstate,
|
||||
changed, (pt_x, pt_y), lparam))
|
||||
|
||||
|
||||
# Make a new buffer suitable for querying an items attributes.
|
||||
def EmptyLVITEM(item, subitem, mask = None, text_buf_size=512):
|
||||
extra = [] # objects we must keep references to
|
||||
if mask is None:
|
||||
mask = commctrl.LVIF_IMAGE | commctrl.LVIF_INDENT | commctrl.LVIF_TEXT | \
|
||||
commctrl.LVIF_PARAM | commctrl.LVIF_STATE
|
||||
if mask & commctrl.LVIF_TEXT:
|
||||
text_buffer = _make_empty_text_buffer(text_buf_size)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
else:
|
||||
text_addr = text_buf_size = 0
|
||||
buf = struct.pack(_lvitem_fmt,
|
||||
mask, item, subitem,
|
||||
0, 0,
|
||||
text_addr, text_buf_size, # text
|
||||
0, 0, 0)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
|
||||
# List view column structure
|
||||
_lvcolumn_fmt = "iiiPiiii"
|
||||
def PackLVCOLUMN(fmt=None, cx=None, text=None, subItem=None, image=None, order=None):
|
||||
extra = [] # objects we must keep references to
|
||||
mask = 0
|
||||
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.LVCF_FMT)
|
||||
mask, cx = _GetMaskAndVal(cx, 0, mask, commctrl.LVCF_WIDTH)
|
||||
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
|
||||
mask, subItem = _GetMaskAndVal(subItem, 0, mask, commctrl.LVCF_SUBITEM)
|
||||
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.LVCF_IMAGE)
|
||||
mask, order= _GetMaskAndVal(order, 0, mask, commctrl.LVCF_ORDER)
|
||||
if text is None:
|
||||
text_addr = text_len = 0
|
||||
else:
|
||||
text_buffer = _make_text_buffer(text)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
text_len = len(text)
|
||||
buf = struct.pack(_lvcolumn_fmt,
|
||||
mask, fmt, cx,
|
||||
text_addr, text_len, # text
|
||||
subItem, image, order)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
def UnpackLVCOLUMN(lparam):
|
||||
mask, fmt, cx, text_addr, text_size, subItem, image, order = \
|
||||
struct.unpack(_lvcolumn_fmt, lparam)
|
||||
# ensure only items listed by the mask are valid
|
||||
if not (mask & commctrl.LVCF_FMT): fmt = None
|
||||
if not (mask & commctrl.LVCF_WIDTH): cx = None
|
||||
if not (mask & commctrl.LVCF_TEXT): text_addr = text_size = None
|
||||
if not (mask & commctrl.LVCF_SUBITEM): subItem = None
|
||||
if not (mask & commctrl.LVCF_IMAGE): image = None
|
||||
if not (mask & commctrl.LVCF_ORDER): order = None
|
||||
if text_addr:
|
||||
text = win32gui.PyGetString(text_addr)
|
||||
else:
|
||||
text = None
|
||||
return _MakeResult("LVCOLUMN fmt cx text subItem image order",
|
||||
(fmt, cx, text, subItem, image, order))
|
||||
|
||||
|
||||
# Make a new buffer suitable for querying an items attributes.
|
||||
def EmptyLVCOLUMN(mask = None, text_buf_size=512):
|
||||
extra = [] # objects we must keep references to
|
||||
if mask is None:
|
||||
mask = commctrl.LVCF_FMT | commctrl.LVCF_WIDTH | commctrl.LVCF_TEXT | \
|
||||
commctrl.LVCF_SUBITEM | commctrl.LVCF_IMAGE | commctrl.LVCF_ORDER
|
||||
if mask & commctrl.LVCF_TEXT:
|
||||
text_buffer = _make_empty_text_buffer(text_buf_size)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
else:
|
||||
text_addr = text_buf_size = 0
|
||||
buf = struct.pack(_lvcolumn_fmt,
|
||||
mask, 0, 0,
|
||||
text_addr, text_buf_size, # text
|
||||
0, 0, 0)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
# List view hit-test.
|
||||
def PackLVHITTEST(pt):
|
||||
format = "iiiii"
|
||||
buf = struct.pack(format,
|
||||
pt[0], pt[1],
|
||||
0, 0, 0)
|
||||
return array.array("b", buf), None
|
||||
|
||||
def UnpackLVHITTEST(buf):
|
||||
format = "iiiii"
|
||||
x, y, flags, item, subitem = struct.unpack(format, buf)
|
||||
return _MakeResult("LVHITTEST pt flags item subitem",
|
||||
((x,y), flags, item, subitem))
|
||||
|
||||
def PackHDITEM(cxy = None, text = None, hbm = None, fmt = None,
|
||||
param = None, image = None, order = None):
|
||||
extra = [] # objects we must keep references to
|
||||
mask = 0
|
||||
mask, cxy = _GetMaskAndVal(cxy, 0, mask, commctrl.HDI_HEIGHT)
|
||||
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
|
||||
mask, hbm = _GetMaskAndVal(hbm, 0, mask, commctrl.HDI_BITMAP)
|
||||
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.HDI_FORMAT)
|
||||
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.HDI_LPARAM)
|
||||
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.HDI_IMAGE)
|
||||
mask, order = _GetMaskAndVal(order, 0, mask, commctrl.HDI_ORDER)
|
||||
|
||||
if text is None:
|
||||
text_addr = text_len = 0
|
||||
else:
|
||||
text_buffer = _make_text_buffer(text)
|
||||
extra.append(text_buffer)
|
||||
text_addr, _ = text_buffer.buffer_info()
|
||||
text_len = len(text)
|
||||
|
||||
format = "iiPPiiPiiii"
|
||||
buf = struct.pack(format,
|
||||
mask, cxy, text_addr, hbm, text_len,
|
||||
fmt, param, image, order, 0, 0)
|
||||
return array.array("b", buf), extra
|
||||
|
||||
# Device notification stuff
|
||||
|
||||
# Generic function for packing a DEV_BROADCAST_* structure - generally used
|
||||
# by the other PackDEV_BROADCAST_* functions in this module.
|
||||
def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes('')):
|
||||
# It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]'
|
||||
# field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must
|
||||
# be 44.
|
||||
extra_data += _make_bytes('\0' * (4-len(extra_data)%4))
|
||||
format = "iii" + rest_fmt
|
||||
full_size = struct.calcsize(format) + len(extra_data)
|
||||
data = (full_size, devicetype, 0) + rest_data
|
||||
return struct.pack(format, *data) + extra_data
|
||||
|
||||
def PackDEV_BROADCAST_HANDLE(handle, hdevnotify=0, guid=_make_bytes("\0"*16), name_offset=0, data=_make_bytes("\0")):
|
||||
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_HANDLE, "PP16sl",
|
||||
(int(handle), int(hdevnotify), _make_memory(guid), name_offset),
|
||||
data)
|
||||
|
||||
def PackDEV_BROADCAST_VOLUME(unitmask, flags):
|
||||
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_VOLUME, "II",
|
||||
(unitmask, flags))
|
||||
|
||||
def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""):
|
||||
if win32gui.UNICODE:
|
||||
# This really means "is py3k?" - so not accepting bytes is OK
|
||||
if not isinstance(name, str):
|
||||
raise TypeError("Must provide unicode for the name")
|
||||
name = name.encode('unicode-internal')
|
||||
else:
|
||||
# py2k was passed a unicode object - encode as mbcs.
|
||||
if isinstance(name, str):
|
||||
name = name.encode('mbcs')
|
||||
|
||||
# 16 bytes for the IID followed by \0 term'd string.
|
||||
rest_fmt = "16s%ds" % len(name)
|
||||
# _make_memory(iid) hoops necessary to get the raw IID bytes.
|
||||
rest_data = (_make_memory(pywintypes.IID(classguid)), name)
|
||||
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data)
|
||||
|
||||
# An object returned by UnpackDEV_BROADCAST.
|
||||
class DEV_BROADCAST_INFO:
|
||||
def __init__(self, devicetype, **kw):
|
||||
self.devicetype = devicetype
|
||||
self.__dict__.update(kw)
|
||||
def __str__(self):
|
||||
return "DEV_BROADCAST_INFO:" + str(self.__dict__)
|
||||
|
||||
# Support for unpacking the 'lparam'
|
||||
def UnpackDEV_BROADCAST(lparam):
|
||||
if lparam == 0:
|
||||
return None
|
||||
hdr_format = "iii"
|
||||
hdr_size = struct.calcsize(hdr_format)
|
||||
hdr_buf = win32gui.PyGetMemory(lparam, hdr_size)
|
||||
size, devtype, reserved = struct.unpack("iii", hdr_buf)
|
||||
# Due to x64 alignment issues, we need to use the full format string over
|
||||
# the entire buffer. ie, on x64:
|
||||
# calcsize('iiiP') != calcsize('iii')+calcsize('P')
|
||||
buf = win32gui.PyGetMemory(lparam, size)
|
||||
|
||||
extra = x = {}
|
||||
if devtype == win32con.DBT_DEVTYP_HANDLE:
|
||||
# 2 handles, a GUID, a LONG and possibly an array following...
|
||||
fmt = hdr_format + "PP16sl"
|
||||
_, _, _, x['handle'], x['hdevnotify'], guid_bytes, x['nameoffset'] = \
|
||||
struct.unpack(fmt, buf[:struct.calcsize(fmt)])
|
||||
x['eventguid'] = pywintypes.IID(guid_bytes, True)
|
||||
elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
|
||||
fmt = hdr_format + "16s"
|
||||
_, _, _, guid_bytes = struct.unpack(fmt, buf[:struct.calcsize(fmt)])
|
||||
x['classguid'] = pywintypes.IID(guid_bytes, True)
|
||||
x['name'] = win32gui.PyGetString(lparam + struct.calcsize(fmt))
|
||||
elif devtype == win32con.DBT_DEVTYP_VOLUME:
|
||||
# int mask and flags
|
||||
fmt = hdr_format + "II"
|
||||
_, _, _, x['unitmask'], x['flags'] = struct.unpack(fmt, buf[:struct.calcsize(fmt)])
|
||||
else:
|
||||
raise NotImplementedError("unknown device type %d" % (devtype,))
|
||||
return DEV_BROADCAST_INFO(devtype, **extra)
|
||||
1103
Pywin32/lib/x32/win32/lib/win32inetcon.py
Normal file
655
Pywin32/lib/x32/win32/lib/win32netcon.py
Normal file
@@ -0,0 +1,655 @@
|
||||
# Generated by h2py from lmaccess.h
|
||||
|
||||
# Included from lmcons.h
|
||||
CNLEN = 15
|
||||
LM20_CNLEN = 15
|
||||
DNLEN = CNLEN
|
||||
LM20_DNLEN = LM20_CNLEN
|
||||
UNCLEN = (CNLEN+2)
|
||||
LM20_UNCLEN = (LM20_CNLEN+2)
|
||||
NNLEN = 80
|
||||
LM20_NNLEN = 12
|
||||
RMLEN = (UNCLEN+1+NNLEN)
|
||||
LM20_RMLEN = (LM20_UNCLEN+1+LM20_NNLEN)
|
||||
SNLEN = 80
|
||||
LM20_SNLEN = 15
|
||||
STXTLEN = 256
|
||||
LM20_STXTLEN = 63
|
||||
PATHLEN = 256
|
||||
LM20_PATHLEN = 256
|
||||
DEVLEN = 80
|
||||
LM20_DEVLEN = 8
|
||||
EVLEN = 16
|
||||
UNLEN = 256
|
||||
LM20_UNLEN = 20
|
||||
GNLEN = UNLEN
|
||||
LM20_GNLEN = LM20_UNLEN
|
||||
PWLEN = 256
|
||||
LM20_PWLEN = 14
|
||||
SHPWLEN = 8
|
||||
CLTYPE_LEN = 12
|
||||
MAXCOMMENTSZ = 256
|
||||
LM20_MAXCOMMENTSZ = 48
|
||||
QNLEN = NNLEN
|
||||
LM20_QNLEN = LM20_NNLEN
|
||||
ALERTSZ = 128
|
||||
NETBIOS_NAME_LEN = 16
|
||||
CRYPT_KEY_LEN = 7
|
||||
CRYPT_TXT_LEN = 8
|
||||
ENCRYPTED_PWLEN = 16
|
||||
SESSION_PWLEN = 24
|
||||
SESSION_CRYPT_KLEN = 21
|
||||
PARMNUM_ALL = 0
|
||||
PARM_ERROR_NONE = 0
|
||||
PARMNUM_BASE_INFOLEVEL = 1000
|
||||
NULL = 0
|
||||
PLATFORM_ID_DOS = 300
|
||||
PLATFORM_ID_OS2 = 400
|
||||
PLATFORM_ID_NT = 500
|
||||
PLATFORM_ID_OSF = 600
|
||||
PLATFORM_ID_VMS = 700
|
||||
MAX_LANMAN_MESSAGE_ID = 5799
|
||||
UF_SCRIPT = 1
|
||||
UF_ACCOUNTDISABLE = 2
|
||||
UF_HOMEDIR_REQUIRED = 8
|
||||
UF_LOCKOUT = 16
|
||||
UF_PASSWD_NOTREQD = 32
|
||||
UF_PASSWD_CANT_CHANGE = 64
|
||||
UF_TEMP_DUPLICATE_ACCOUNT = 256
|
||||
UF_NORMAL_ACCOUNT = 512
|
||||
UF_INTERDOMAIN_TRUST_ACCOUNT = 2048
|
||||
UF_WORKSTATION_TRUST_ACCOUNT = 4096
|
||||
UF_SERVER_TRUST_ACCOUNT = 8192
|
||||
UF_MACHINE_ACCOUNT_MASK = ( UF_INTERDOMAIN_TRUST_ACCOUNT | \
|
||||
UF_WORKSTATION_TRUST_ACCOUNT | \
|
||||
UF_SERVER_TRUST_ACCOUNT )
|
||||
UF_ACCOUNT_TYPE_MASK = ( \
|
||||
UF_TEMP_DUPLICATE_ACCOUNT | \
|
||||
UF_NORMAL_ACCOUNT | \
|
||||
UF_INTERDOMAIN_TRUST_ACCOUNT | \
|
||||
UF_WORKSTATION_TRUST_ACCOUNT | \
|
||||
UF_SERVER_TRUST_ACCOUNT \
|
||||
)
|
||||
UF_DONT_EXPIRE_PASSWD = 65536
|
||||
UF_MNS_LOGON_ACCOUNT = 131072
|
||||
UF_SETTABLE_BITS = ( \
|
||||
UF_SCRIPT | \
|
||||
UF_ACCOUNTDISABLE | \
|
||||
UF_LOCKOUT | \
|
||||
UF_HOMEDIR_REQUIRED | \
|
||||
UF_PASSWD_NOTREQD | \
|
||||
UF_PASSWD_CANT_CHANGE | \
|
||||
UF_ACCOUNT_TYPE_MASK | \
|
||||
UF_DONT_EXPIRE_PASSWD | \
|
||||
UF_MNS_LOGON_ACCOUNT \
|
||||
)
|
||||
FILTER_TEMP_DUPLICATE_ACCOUNT = (1)
|
||||
FILTER_NORMAL_ACCOUNT = (2)
|
||||
FILTER_INTERDOMAIN_TRUST_ACCOUNT = (8)
|
||||
FILTER_WORKSTATION_TRUST_ACCOUNT = (16)
|
||||
FILTER_SERVER_TRUST_ACCOUNT = (32)
|
||||
LG_INCLUDE_INDIRECT = (1)
|
||||
AF_OP_PRINT = 1
|
||||
AF_OP_COMM = 2
|
||||
AF_OP_SERVER = 4
|
||||
AF_OP_ACCOUNTS = 8
|
||||
AF_SETTABLE_BITS = (AF_OP_PRINT | AF_OP_COMM | \
|
||||
AF_OP_SERVER | AF_OP_ACCOUNTS)
|
||||
UAS_ROLE_STANDALONE = 0
|
||||
UAS_ROLE_MEMBER = 1
|
||||
UAS_ROLE_BACKUP = 2
|
||||
UAS_ROLE_PRIMARY = 3
|
||||
USER_NAME_PARMNUM = 1
|
||||
USER_PASSWORD_PARMNUM = 3
|
||||
USER_PASSWORD_AGE_PARMNUM = 4
|
||||
USER_PRIV_PARMNUM = 5
|
||||
USER_HOME_DIR_PARMNUM = 6
|
||||
USER_COMMENT_PARMNUM = 7
|
||||
USER_FLAGS_PARMNUM = 8
|
||||
USER_SCRIPT_PATH_PARMNUM = 9
|
||||
USER_AUTH_FLAGS_PARMNUM = 10
|
||||
USER_FULL_NAME_PARMNUM = 11
|
||||
USER_USR_COMMENT_PARMNUM = 12
|
||||
USER_PARMS_PARMNUM = 13
|
||||
USER_WORKSTATIONS_PARMNUM = 14
|
||||
USER_LAST_LOGON_PARMNUM = 15
|
||||
USER_LAST_LOGOFF_PARMNUM = 16
|
||||
USER_ACCT_EXPIRES_PARMNUM = 17
|
||||
USER_MAX_STORAGE_PARMNUM = 18
|
||||
USER_UNITS_PER_WEEK_PARMNUM = 19
|
||||
USER_LOGON_HOURS_PARMNUM = 20
|
||||
USER_PAD_PW_COUNT_PARMNUM = 21
|
||||
USER_NUM_LOGONS_PARMNUM = 22
|
||||
USER_LOGON_SERVER_PARMNUM = 23
|
||||
USER_COUNTRY_CODE_PARMNUM = 24
|
||||
USER_CODE_PAGE_PARMNUM = 25
|
||||
USER_PRIMARY_GROUP_PARMNUM = 51
|
||||
USER_PROFILE = 52
|
||||
USER_PROFILE_PARMNUM = 52
|
||||
USER_HOME_DIR_DRIVE_PARMNUM = 53
|
||||
USER_NAME_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_NAME_PARMNUM)
|
||||
USER_PASSWORD_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_PARMNUM)
|
||||
USER_PASSWORD_AGE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PASSWORD_AGE_PARMNUM)
|
||||
USER_PRIV_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PRIV_PARMNUM)
|
||||
USER_HOME_DIR_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_PARMNUM)
|
||||
USER_COMMENT_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_COMMENT_PARMNUM)
|
||||
USER_FLAGS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_FLAGS_PARMNUM)
|
||||
USER_SCRIPT_PATH_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_SCRIPT_PATH_PARMNUM)
|
||||
USER_AUTH_FLAGS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_AUTH_FLAGS_PARMNUM)
|
||||
USER_FULL_NAME_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_FULL_NAME_PARMNUM)
|
||||
USER_USR_COMMENT_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_USR_COMMENT_PARMNUM)
|
||||
USER_PARMS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PARMS_PARMNUM)
|
||||
USER_WORKSTATIONS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_WORKSTATIONS_PARMNUM)
|
||||
USER_LAST_LOGON_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGON_PARMNUM)
|
||||
USER_LAST_LOGOFF_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_LAST_LOGOFF_PARMNUM)
|
||||
USER_ACCT_EXPIRES_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_ACCT_EXPIRES_PARMNUM)
|
||||
USER_MAX_STORAGE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_MAX_STORAGE_PARMNUM)
|
||||
USER_UNITS_PER_WEEK_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_UNITS_PER_WEEK_PARMNUM)
|
||||
USER_LOGON_HOURS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_LOGON_HOURS_PARMNUM)
|
||||
USER_PAD_PW_COUNT_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PAD_PW_COUNT_PARMNUM)
|
||||
USER_NUM_LOGONS_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_NUM_LOGONS_PARMNUM)
|
||||
USER_LOGON_SERVER_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_LOGON_SERVER_PARMNUM)
|
||||
USER_COUNTRY_CODE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_COUNTRY_CODE_PARMNUM)
|
||||
USER_CODE_PAGE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_CODE_PAGE_PARMNUM)
|
||||
USER_PRIMARY_GROUP_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_PRIMARY_GROUP_PARMNUM)
|
||||
USER_HOME_DIR_DRIVE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + USER_HOME_DIR_DRIVE_PARMNUM)
|
||||
NULL_USERSETINFO_PASSWD = " "
|
||||
UNITS_PER_DAY = 24
|
||||
UNITS_PER_WEEK = UNITS_PER_DAY * 7
|
||||
USER_PRIV_MASK = 3
|
||||
USER_PRIV_GUEST = 0
|
||||
USER_PRIV_USER = 1
|
||||
USER_PRIV_ADMIN = 2
|
||||
MAX_PASSWD_LEN = PWLEN
|
||||
DEF_MIN_PWLEN = 6
|
||||
DEF_PWUNIQUENESS = 5
|
||||
DEF_MAX_PWHIST = 8
|
||||
DEF_MAX_BADPW = 0
|
||||
VALIDATED_LOGON = 0
|
||||
PASSWORD_EXPIRED = 2
|
||||
NON_VALIDATED_LOGON = 3
|
||||
VALID_LOGOFF = 1
|
||||
MODALS_MIN_PASSWD_LEN_PARMNUM = 1
|
||||
MODALS_MAX_PASSWD_AGE_PARMNUM = 2
|
||||
MODALS_MIN_PASSWD_AGE_PARMNUM = 3
|
||||
MODALS_FORCE_LOGOFF_PARMNUM = 4
|
||||
MODALS_PASSWD_HIST_LEN_PARMNUM = 5
|
||||
MODALS_ROLE_PARMNUM = 6
|
||||
MODALS_PRIMARY_PARMNUM = 7
|
||||
MODALS_DOMAIN_NAME_PARMNUM = 8
|
||||
MODALS_DOMAIN_ID_PARMNUM = 9
|
||||
MODALS_LOCKOUT_DURATION_PARMNUM = 10
|
||||
MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM = 11
|
||||
MODALS_LOCKOUT_THRESHOLD_PARMNUM = 12
|
||||
MODALS_MIN_PASSWD_LEN_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_LEN_PARMNUM)
|
||||
MODALS_MAX_PASSWD_AGE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_MAX_PASSWD_AGE_PARMNUM)
|
||||
MODALS_MIN_PASSWD_AGE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_MIN_PASSWD_AGE_PARMNUM)
|
||||
MODALS_FORCE_LOGOFF_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_FORCE_LOGOFF_PARMNUM)
|
||||
MODALS_PASSWD_HIST_LEN_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_PASSWD_HIST_LEN_PARMNUM)
|
||||
MODALS_ROLE_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_ROLE_PARMNUM)
|
||||
MODALS_PRIMARY_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_PRIMARY_PARMNUM)
|
||||
MODALS_DOMAIN_NAME_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_NAME_PARMNUM)
|
||||
MODALS_DOMAIN_ID_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + MODALS_DOMAIN_ID_PARMNUM)
|
||||
GROUPIDMASK = 32768
|
||||
GROUP_ALL_PARMNUM = 0
|
||||
GROUP_NAME_PARMNUM = 1
|
||||
GROUP_COMMENT_PARMNUM = 2
|
||||
GROUP_ATTRIBUTES_PARMNUM = 3
|
||||
GROUP_ALL_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + GROUP_ALL_PARMNUM)
|
||||
GROUP_NAME_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + GROUP_NAME_PARMNUM)
|
||||
GROUP_COMMENT_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + GROUP_COMMENT_PARMNUM)
|
||||
GROUP_ATTRIBUTES_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + GROUP_ATTRIBUTES_PARMNUM)
|
||||
LOCALGROUP_NAME_PARMNUM = 1
|
||||
LOCALGROUP_COMMENT_PARMNUM = 2
|
||||
MAXPERMENTRIES = 64
|
||||
ACCESS_NONE = 0
|
||||
ACCESS_READ = 1
|
||||
ACCESS_WRITE = 2
|
||||
ACCESS_CREATE = 4
|
||||
ACCESS_EXEC = 8
|
||||
ACCESS_DELETE = 16
|
||||
ACCESS_ATRIB = 32
|
||||
ACCESS_PERM = 64
|
||||
ACCESS_GROUP = 32768
|
||||
ACCESS_AUDIT = 1
|
||||
ACCESS_SUCCESS_OPEN = 16
|
||||
ACCESS_SUCCESS_WRITE = 32
|
||||
ACCESS_SUCCESS_DELETE = 64
|
||||
ACCESS_SUCCESS_ACL = 128
|
||||
ACCESS_SUCCESS_MASK = 240
|
||||
ACCESS_FAIL_OPEN = 256
|
||||
ACCESS_FAIL_WRITE = 512
|
||||
ACCESS_FAIL_DELETE = 1024
|
||||
ACCESS_FAIL_ACL = 2048
|
||||
ACCESS_FAIL_MASK = 3840
|
||||
ACCESS_FAIL_SHIFT = 4
|
||||
ACCESS_RESOURCE_NAME_PARMNUM = 1
|
||||
ACCESS_ATTR_PARMNUM = 2
|
||||
ACCESS_COUNT_PARMNUM = 3
|
||||
ACCESS_ACCESS_LIST_PARMNUM = 4
|
||||
ACCESS_RESOURCE_NAME_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + ACCESS_RESOURCE_NAME_PARMNUM)
|
||||
ACCESS_ATTR_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + ACCESS_ATTR_PARMNUM)
|
||||
ACCESS_COUNT_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + ACCESS_COUNT_PARMNUM)
|
||||
ACCESS_ACCESS_LIST_INFOLEVEL = \
|
||||
(PARMNUM_BASE_INFOLEVEL + ACCESS_ACCESS_LIST_PARMNUM)
|
||||
ACCESS_LETTERS = "RWCXDAP "
|
||||
NETLOGON_CONTROL_QUERY = 1
|
||||
NETLOGON_CONTROL_REPLICATE = 2
|
||||
NETLOGON_CONTROL_SYNCHRONIZE = 3
|
||||
NETLOGON_CONTROL_PDC_REPLICATE = 4
|
||||
NETLOGON_CONTROL_REDISCOVER = 5
|
||||
NETLOGON_CONTROL_TC_QUERY = 6
|
||||
NETLOGON_CONTROL_TRANSPORT_NOTIFY = 7
|
||||
NETLOGON_CONTROL_FIND_USER = 8
|
||||
NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL = 65531
|
||||
NETLOGON_CONTROL_BACKUP_CHANGE_LOG = 65532
|
||||
NETLOGON_CONTROL_TRUNCATE_LOG = 65533
|
||||
NETLOGON_CONTROL_SET_DBFLAG = 65534
|
||||
NETLOGON_CONTROL_BREAKPOINT = 65535
|
||||
NETLOGON_REPLICATION_NEEDED = 1
|
||||
NETLOGON_REPLICATION_IN_PROGRESS = 2
|
||||
NETLOGON_FULL_SYNC_REPLICATION = 4
|
||||
NETLOGON_REDO_NEEDED = 8
|
||||
|
||||
######################
|
||||
# Manual stuff
|
||||
|
||||
TEXT=lambda x:x
|
||||
|
||||
MAX_PREFERRED_LENGTH = -1
|
||||
PARM_ERROR_UNKNOWN = -1
|
||||
MESSAGE_FILENAME = TEXT("NETMSG")
|
||||
OS2MSG_FILENAME = TEXT("BASE")
|
||||
HELP_MSG_FILENAME = TEXT("NETH")
|
||||
BACKUP_MSG_FILENAME = TEXT("BAK.MSG")
|
||||
TIMEQ_FOREVER = -1
|
||||
USER_MAXSTORAGE_UNLIMITED = -1
|
||||
USER_NO_LOGOFF = -1
|
||||
DEF_MAX_PWAGE = TIMEQ_FOREVER
|
||||
DEF_MIN_PWAGE = 0
|
||||
DEF_FORCE_LOGOFF = -1
|
||||
ONE_DAY = 1*24*3600
|
||||
GROUP_SPECIALGRP_USERS = "USERS"
|
||||
GROUP_SPECIALGRP_ADMINS = "ADMINS"
|
||||
GROUP_SPECIALGRP_GUESTS = "GUESTS"
|
||||
GROUP_SPECIALGRP_LOCAL = "LOCAL"
|
||||
ACCESS_ALL = ( ACCESS_READ | ACCESS_WRITE | ACCESS_CREATE | ACCESS_EXEC | ACCESS_DELETE | ACCESS_ATRIB | ACCESS_PERM )
|
||||
|
||||
# From lmserver.h
|
||||
SV_PLATFORM_ID_OS2 = 400
|
||||
SV_PLATFORM_ID_NT = 500
|
||||
MAJOR_VERSION_MASK = 15
|
||||
SV_TYPE_WORKSTATION = 1
|
||||
SV_TYPE_SERVER = 2
|
||||
SV_TYPE_SQLSERVER = 4
|
||||
SV_TYPE_DOMAIN_CTRL = 8
|
||||
SV_TYPE_DOMAIN_BAKCTRL = 16
|
||||
SV_TYPE_TIME_SOURCE = 32
|
||||
SV_TYPE_AFP = 64
|
||||
SV_TYPE_NOVELL = 128
|
||||
SV_TYPE_DOMAIN_MEMBER = 256
|
||||
SV_TYPE_PRINTQ_SERVER = 512
|
||||
SV_TYPE_DIALIN_SERVER = 1024
|
||||
SV_TYPE_XENIX_SERVER = 2048
|
||||
SV_TYPE_SERVER_UNIX = SV_TYPE_XENIX_SERVER
|
||||
SV_TYPE_NT = 4096
|
||||
SV_TYPE_WFW = 8192
|
||||
SV_TYPE_SERVER_MFPN = 16384
|
||||
SV_TYPE_SERVER_NT = 32768
|
||||
SV_TYPE_POTENTIAL_BROWSER = 65536
|
||||
SV_TYPE_BACKUP_BROWSER = 131072
|
||||
SV_TYPE_MASTER_BROWSER = 262144
|
||||
SV_TYPE_DOMAIN_MASTER = 524288
|
||||
SV_TYPE_SERVER_OSF = 1048576
|
||||
SV_TYPE_SERVER_VMS = 2097152
|
||||
SV_TYPE_WINDOWS = 4194304
|
||||
SV_TYPE_DFS = 8388608
|
||||
SV_TYPE_CLUSTER_NT = 16777216
|
||||
SV_TYPE_DCE = 268435456
|
||||
SV_TYPE_ALTERNATE_XPORT = 536870912
|
||||
SV_TYPE_LOCAL_LIST_ONLY = 1073741824
|
||||
SV_TYPE_DOMAIN_ENUM = -2147483648
|
||||
SV_TYPE_ALL = -1
|
||||
SV_NODISC = -1
|
||||
SV_USERSECURITY = 1
|
||||
SV_SHARESECURITY = 0
|
||||
SV_HIDDEN = 1
|
||||
SV_VISIBLE = 0
|
||||
SV_PLATFORM_ID_PARMNUM = 101
|
||||
SV_NAME_PARMNUM = 102
|
||||
SV_VERSION_MAJOR_PARMNUM = 103
|
||||
SV_VERSION_MINOR_PARMNUM = 104
|
||||
SV_TYPE_PARMNUM = 105
|
||||
SV_COMMENT_PARMNUM = 5
|
||||
SV_USERS_PARMNUM = 107
|
||||
SV_DISC_PARMNUM = 10
|
||||
SV_HIDDEN_PARMNUM = 16
|
||||
SV_ANNOUNCE_PARMNUM = 17
|
||||
SV_ANNDELTA_PARMNUM = 18
|
||||
SV_USERPATH_PARMNUM = 112
|
||||
SV_ULIST_MTIME_PARMNUM = 401
|
||||
SV_GLIST_MTIME_PARMNUM = 402
|
||||
SV_ALIST_MTIME_PARMNUM = 403
|
||||
SV_ALERTS_PARMNUM = 11
|
||||
SV_SECURITY_PARMNUM = 405
|
||||
SV_NUMADMIN_PARMNUM = 406
|
||||
SV_LANMASK_PARMNUM = 407
|
||||
SV_GUESTACC_PARMNUM = 408
|
||||
SV_CHDEVQ_PARMNUM = 410
|
||||
SV_CHDEVJOBS_PARMNUM = 411
|
||||
SV_CONNECTIONS_PARMNUM = 412
|
||||
SV_SHARES_PARMNUM = 413
|
||||
SV_OPENFILES_PARMNUM = 414
|
||||
SV_SESSREQS_PARMNUM = 417
|
||||
SV_ACTIVELOCKS_PARMNUM = 419
|
||||
SV_NUMREQBUF_PARMNUM = 420
|
||||
SV_NUMBIGBUF_PARMNUM = 422
|
||||
SV_NUMFILETASKS_PARMNUM = 423
|
||||
SV_ALERTSCHED_PARMNUM = 37
|
||||
SV_ERRORALERT_PARMNUM = 38
|
||||
SV_LOGONALERT_PARMNUM = 39
|
||||
SV_ACCESSALERT_PARMNUM = 40
|
||||
SV_DISKALERT_PARMNUM = 41
|
||||
SV_NETIOALERT_PARMNUM = 42
|
||||
SV_MAXAUDITSZ_PARMNUM = 43
|
||||
SV_SRVHEURISTICS_PARMNUM = 431
|
||||
SV_SESSOPENS_PARMNUM = 501
|
||||
SV_SESSVCS_PARMNUM = 502
|
||||
SV_OPENSEARCH_PARMNUM = 503
|
||||
SV_SIZREQBUF_PARMNUM = 504
|
||||
SV_INITWORKITEMS_PARMNUM = 505
|
||||
SV_MAXWORKITEMS_PARMNUM = 506
|
||||
SV_RAWWORKITEMS_PARMNUM = 507
|
||||
SV_IRPSTACKSIZE_PARMNUM = 508
|
||||
SV_MAXRAWBUFLEN_PARMNUM = 509
|
||||
SV_SESSUSERS_PARMNUM = 510
|
||||
SV_SESSCONNS_PARMNUM = 511
|
||||
SV_MAXNONPAGEDMEMORYUSAGE_PARMNUM = 512
|
||||
SV_MAXPAGEDMEMORYUSAGE_PARMNUM = 513
|
||||
SV_ENABLESOFTCOMPAT_PARMNUM = 514
|
||||
SV_ENABLEFORCEDLOGOFF_PARMNUM = 515
|
||||
SV_TIMESOURCE_PARMNUM = 516
|
||||
SV_ACCEPTDOWNLEVELAPIS_PARMNUM = 517
|
||||
SV_LMANNOUNCE_PARMNUM = 518
|
||||
SV_DOMAIN_PARMNUM = 519
|
||||
SV_MAXCOPYREADLEN_PARMNUM = 520
|
||||
SV_MAXCOPYWRITELEN_PARMNUM = 521
|
||||
SV_MINKEEPSEARCH_PARMNUM = 522
|
||||
SV_MAXKEEPSEARCH_PARMNUM = 523
|
||||
SV_MINKEEPCOMPLSEARCH_PARMNUM = 524
|
||||
SV_MAXKEEPCOMPLSEARCH_PARMNUM = 525
|
||||
SV_THREADCOUNTADD_PARMNUM = 526
|
||||
SV_NUMBLOCKTHREADS_PARMNUM = 527
|
||||
SV_SCAVTIMEOUT_PARMNUM = 528
|
||||
SV_MINRCVQUEUE_PARMNUM = 529
|
||||
SV_MINFREEWORKITEMS_PARMNUM = 530
|
||||
SV_XACTMEMSIZE_PARMNUM = 531
|
||||
SV_THREADPRIORITY_PARMNUM = 532
|
||||
SV_MAXMPXCT_PARMNUM = 533
|
||||
SV_OPLOCKBREAKWAIT_PARMNUM = 534
|
||||
SV_OPLOCKBREAKRESPONSEWAIT_PARMNUM = 535
|
||||
SV_ENABLEOPLOCKS_PARMNUM = 536
|
||||
SV_ENABLEOPLOCKFORCECLOSE_PARMNUM = 537
|
||||
SV_ENABLEFCBOPENS_PARMNUM = 538
|
||||
SV_ENABLERAW_PARMNUM = 539
|
||||
SV_ENABLESHAREDNETDRIVES_PARMNUM = 540
|
||||
SV_MINFREECONNECTIONS_PARMNUM = 541
|
||||
SV_MAXFREECONNECTIONS_PARMNUM = 542
|
||||
SV_INITSESSTABLE_PARMNUM = 543
|
||||
SV_INITCONNTABLE_PARMNUM = 544
|
||||
SV_INITFILETABLE_PARMNUM = 545
|
||||
SV_INITSEARCHTABLE_PARMNUM = 546
|
||||
SV_ALERTSCHEDULE_PARMNUM = 547
|
||||
SV_ERRORTHRESHOLD_PARMNUM = 548
|
||||
SV_NETWORKERRORTHRESHOLD_PARMNUM = 549
|
||||
SV_DISKSPACETHRESHOLD_PARMNUM = 550
|
||||
SV_MAXLINKDELAY_PARMNUM = 552
|
||||
SV_MINLINKTHROUGHPUT_PARMNUM = 553
|
||||
SV_LINKINFOVALIDTIME_PARMNUM = 554
|
||||
SV_SCAVQOSINFOUPDATETIME_PARMNUM = 555
|
||||
SV_MAXWORKITEMIDLETIME_PARMNUM = 556
|
||||
SV_MAXRAWWORKITEMS_PARMNUM = 557
|
||||
SV_PRODUCTTYPE_PARMNUM = 560
|
||||
SV_SERVERSIZE_PARMNUM = 561
|
||||
SV_CONNECTIONLESSAUTODISC_PARMNUM = 562
|
||||
SV_SHARINGVIOLATIONRETRIES_PARMNUM = 563
|
||||
SV_SHARINGVIOLATIONDELAY_PARMNUM = 564
|
||||
SV_MAXGLOBALOPENSEARCH_PARMNUM = 565
|
||||
SV_REMOVEDUPLICATESEARCHES_PARMNUM = 566
|
||||
SV_LOCKVIOLATIONRETRIES_PARMNUM = 567
|
||||
SV_LOCKVIOLATIONOFFSET_PARMNUM = 568
|
||||
SV_LOCKVIOLATIONDELAY_PARMNUM = 569
|
||||
SV_MDLREADSWITCHOVER_PARMNUM = 570
|
||||
SV_CACHEDOPENLIMIT_PARMNUM = 571
|
||||
SV_CRITICALTHREADS_PARMNUM = 572
|
||||
SV_RESTRICTNULLSESSACCESS_PARMNUM = 573
|
||||
SV_ENABLEWFW311DIRECTIPX_PARMNUM = 574
|
||||
SV_OTHERQUEUEAFFINITY_PARMNUM = 575
|
||||
SV_QUEUESAMPLESECS_PARMNUM = 576
|
||||
SV_BALANCECOUNT_PARMNUM = 577
|
||||
SV_PREFERREDAFFINITY_PARMNUM = 578
|
||||
SV_MAXFREERFCBS_PARMNUM = 579
|
||||
SV_MAXFREEMFCBS_PARMNUM = 580
|
||||
SV_MAXFREELFCBS_PARMNUM = 581
|
||||
SV_MAXFREEPAGEDPOOLCHUNKS_PARMNUM = 582
|
||||
SV_MINPAGEDPOOLCHUNKSIZE_PARMNUM = 583
|
||||
SV_MAXPAGEDPOOLCHUNKSIZE_PARMNUM = 584
|
||||
SV_SENDSFROMPREFERREDPROCESSOR_PARMNUM = 585
|
||||
SV_MAXTHREADSPERQUEUE_PARMNUM = 586
|
||||
SV_CACHEDDIRECTORYLIMIT_PARMNUM = 587
|
||||
SV_MAXCOPYLENGTH_PARMNUM = 588
|
||||
SV_ENABLEBULKTRANSFER_PARMNUM = 589
|
||||
SV_ENABLECOMPRESSION_PARMNUM = 590
|
||||
SV_AUTOSHAREWKS_PARMNUM = 591
|
||||
SV_AUTOSHARESERVER_PARMNUM = 592
|
||||
SV_ENABLESECURITYSIGNATURE_PARMNUM = 593
|
||||
SV_REQUIRESECURITYSIGNATURE_PARMNUM = 594
|
||||
SV_MINCLIENTBUFFERSIZE_PARMNUM = 595
|
||||
SV_CONNECTIONNOSESSIONSTIMEOUT_PARMNUM = 596
|
||||
SVI1_NUM_ELEMENTS = 5
|
||||
SVI2_NUM_ELEMENTS = 40
|
||||
SVI3_NUM_ELEMENTS = 44
|
||||
SW_AUTOPROF_LOAD_MASK = 1
|
||||
SW_AUTOPROF_SAVE_MASK = 2
|
||||
SV_MAX_SRV_HEUR_LEN = 32
|
||||
SV_USERS_PER_LICENSE = 5
|
||||
SVTI2_REMAP_PIPE_NAMES = 2
|
||||
|
||||
# Generated by h2py from lmshare.h
|
||||
SHARE_NETNAME_PARMNUM = 1
|
||||
SHARE_TYPE_PARMNUM = 3
|
||||
SHARE_REMARK_PARMNUM = 4
|
||||
SHARE_PERMISSIONS_PARMNUM = 5
|
||||
SHARE_MAX_USES_PARMNUM = 6
|
||||
SHARE_CURRENT_USES_PARMNUM = 7
|
||||
SHARE_PATH_PARMNUM = 8
|
||||
SHARE_PASSWD_PARMNUM = 9
|
||||
SHARE_FILE_SD_PARMNUM = 501
|
||||
SHI1_NUM_ELEMENTS = 4
|
||||
SHI2_NUM_ELEMENTS = 10
|
||||
STYPE_DISKTREE = 0
|
||||
STYPE_PRINTQ = 1
|
||||
STYPE_DEVICE = 2
|
||||
STYPE_IPC = 3
|
||||
STYPE_SPECIAL = -2147483648
|
||||
SHI1005_FLAGS_DFS = 1
|
||||
SHI1005_FLAGS_DFS_ROOT = 2
|
||||
COW_PERMACHINE = 4
|
||||
COW_PERUSER = 8
|
||||
CSC_CACHEABLE = 16
|
||||
CSC_NOFLOWOPS = 32
|
||||
CSC_AUTO_INWARD = 64
|
||||
CSC_AUTO_OUTWARD = 128
|
||||
SHI1005_VALID_FLAGS_SET = ( CSC_CACHEABLE | \
|
||||
CSC_NOFLOWOPS | \
|
||||
CSC_AUTO_INWARD | \
|
||||
CSC_AUTO_OUTWARD| \
|
||||
COW_PERMACHINE | \
|
||||
COW_PERUSER )
|
||||
SHI1007_VALID_FLAGS_SET = SHI1005_VALID_FLAGS_SET
|
||||
SESS_GUEST = 1
|
||||
SESS_NOENCRYPTION = 2
|
||||
SESI1_NUM_ELEMENTS = 8
|
||||
SESI2_NUM_ELEMENTS = 9
|
||||
PERM_FILE_READ = 1
|
||||
PERM_FILE_WRITE = 2
|
||||
PERM_FILE_CREATE = 4
|
||||
|
||||
# Generated by h2py from d:\mssdk\include\winnetwk.h
|
||||
WNNC_NET_MSNET = 65536
|
||||
WNNC_NET_LANMAN = 131072
|
||||
WNNC_NET_NETWARE = 196608
|
||||
WNNC_NET_VINES = 262144
|
||||
WNNC_NET_10NET = 327680
|
||||
WNNC_NET_LOCUS = 393216
|
||||
WNNC_NET_SUN_PC_NFS = 458752
|
||||
WNNC_NET_LANSTEP = 524288
|
||||
WNNC_NET_9TILES = 589824
|
||||
WNNC_NET_LANTASTIC = 655360
|
||||
WNNC_NET_AS400 = 720896
|
||||
WNNC_NET_FTP_NFS = 786432
|
||||
WNNC_NET_PATHWORKS = 851968
|
||||
WNNC_NET_LIFENET = 917504
|
||||
WNNC_NET_POWERLAN = 983040
|
||||
WNNC_NET_BWNFS = 1048576
|
||||
WNNC_NET_COGENT = 1114112
|
||||
WNNC_NET_FARALLON = 1179648
|
||||
WNNC_NET_APPLETALK = 1245184
|
||||
WNNC_NET_INTERGRAPH = 1310720
|
||||
WNNC_NET_SYMFONET = 1376256
|
||||
WNNC_NET_CLEARCASE = 1441792
|
||||
WNNC_NET_FRONTIER = 1507328
|
||||
WNNC_NET_BMC = 1572864
|
||||
WNNC_NET_DCE = 1638400
|
||||
WNNC_NET_DECORB = 2097152
|
||||
WNNC_NET_PROTSTOR = 2162688
|
||||
WNNC_NET_FJ_REDIR = 2228224
|
||||
WNNC_NET_DISTINCT = 2293760
|
||||
WNNC_NET_TWINS = 2359296
|
||||
WNNC_NET_RDR2SAMPLE = 2424832
|
||||
RESOURCE_CONNECTED = 1
|
||||
RESOURCE_GLOBALNET = 2
|
||||
RESOURCE_REMEMBERED = 3
|
||||
RESOURCE_RECENT = 4
|
||||
RESOURCE_CONTEXT = 5
|
||||
RESOURCETYPE_ANY = 0
|
||||
RESOURCETYPE_DISK = 1
|
||||
RESOURCETYPE_PRINT = 2
|
||||
RESOURCETYPE_RESERVED = 8
|
||||
RESOURCETYPE_UNKNOWN = -1
|
||||
RESOURCEUSAGE_CONNECTABLE = 1
|
||||
RESOURCEUSAGE_CONTAINER = 2
|
||||
RESOURCEUSAGE_NOLOCALDEVICE = 4
|
||||
RESOURCEUSAGE_SIBLING = 8
|
||||
RESOURCEUSAGE_ATTACHED = 16
|
||||
RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED)
|
||||
RESOURCEUSAGE_RESERVED = -2147483648
|
||||
RESOURCEDISPLAYTYPE_GENERIC = 0
|
||||
RESOURCEDISPLAYTYPE_DOMAIN = 1
|
||||
RESOURCEDISPLAYTYPE_SERVER = 2
|
||||
RESOURCEDISPLAYTYPE_SHARE = 3
|
||||
RESOURCEDISPLAYTYPE_FILE = 4
|
||||
RESOURCEDISPLAYTYPE_GROUP = 5
|
||||
RESOURCEDISPLAYTYPE_NETWORK = 6
|
||||
RESOURCEDISPLAYTYPE_ROOT = 7
|
||||
RESOURCEDISPLAYTYPE_SHAREADMIN = 8
|
||||
RESOURCEDISPLAYTYPE_DIRECTORY = 9
|
||||
RESOURCEDISPLAYTYPE_TREE = 10
|
||||
RESOURCEDISPLAYTYPE_NDSCONTAINER = 11
|
||||
NETPROPERTY_PERSISTENT = 1
|
||||
CONNECT_UPDATE_PROFILE = 1
|
||||
CONNECT_UPDATE_RECENT = 2
|
||||
CONNECT_TEMPORARY = 4
|
||||
CONNECT_INTERACTIVE = 8
|
||||
CONNECT_PROMPT = 16
|
||||
CONNECT_NEED_DRIVE = 32
|
||||
CONNECT_REFCOUNT = 64
|
||||
CONNECT_REDIRECT = 128
|
||||
CONNECT_LOCALDRIVE = 256
|
||||
CONNECT_CURRENT_MEDIA = 512
|
||||
CONNECT_DEFERRED = 1024
|
||||
CONNECT_RESERVED = -16777216
|
||||
CONNDLG_RO_PATH = 1
|
||||
CONNDLG_CONN_POINT = 2
|
||||
CONNDLG_USE_MRU = 4
|
||||
CONNDLG_HIDE_BOX = 8
|
||||
CONNDLG_PERSIST = 16
|
||||
CONNDLG_NOT_PERSIST = 32
|
||||
DISC_UPDATE_PROFILE = 1
|
||||
DISC_NO_FORCE = 64
|
||||
UNIVERSAL_NAME_INFO_LEVEL = 1
|
||||
REMOTE_NAME_INFO_LEVEL = 2
|
||||
WNFMT_MULTILINE = 1
|
||||
WNFMT_ABBREVIATED = 2
|
||||
WNFMT_INENUM = 16
|
||||
WNFMT_CONNECTION = 32
|
||||
NETINFO_DLL16 = 1
|
||||
NETINFO_DISKRED = 4
|
||||
NETINFO_PRINTERRED = 8
|
||||
RP_LOGON = 1
|
||||
RP_INIFILE = 2
|
||||
PP_DISPLAYERRORS = 1
|
||||
WNCON_FORNETCARD = 1
|
||||
WNCON_NOTROUTED = 2
|
||||
WNCON_SLOWLINK = 4
|
||||
WNCON_DYNAMIC = 8
|
||||
|
||||
## NETSETUP_NAME_TYPE, used with NetValidateName
|
||||
NetSetupUnknown = 0
|
||||
NetSetupMachine = 1
|
||||
NetSetupWorkgroup = 2
|
||||
NetSetupDomain = 3
|
||||
NetSetupNonExistentDomain = 4
|
||||
NetSetupDnsMachine = 5
|
||||
|
||||
## NETSETUP_JOIN_STATUS, use with NetGetJoinInformation
|
||||
NetSetupUnknownStatus = 0
|
||||
NetSetupUnjoined = 1
|
||||
NetSetupWorkgroupName = 2
|
||||
NetSetupDomainName = 3
|
||||
|
||||
NetValidateAuthentication = 1
|
||||
NetValidatePasswordChange = 2
|
||||
NetValidatePasswordReset = 3
|
||||
515
Pywin32/lib/x32/win32/lib/win32pdhquery.py
Normal file
@@ -0,0 +1,515 @@
|
||||
'''
|
||||
Performance Data Helper (PDH) Query Classes
|
||||
|
||||
Wrapper classes for end-users and high-level access to the PDH query
|
||||
mechanisms. PDH is a win32-specific mechanism for accessing the
|
||||
performance data made available by the system. The Python for Windows
|
||||
PDH module does not implement the "Registry" interface, implementing
|
||||
the more straightforward Query-based mechanism.
|
||||
|
||||
The basic idea of a PDH Query is an object which can query the system
|
||||
about the status of any number of "counters." The counters are paths
|
||||
to a particular piece of performance data. For instance, the path
|
||||
'\\Memory\\Available Bytes' describes just about exactly what it says
|
||||
it does, the amount of free memory on the default computer expressed
|
||||
in Bytes. These paths can be considerably more complex than this,
|
||||
but part of the point of this wrapper module is to hide that
|
||||
complexity from the end-user/programmer.
|
||||
|
||||
EXAMPLE: A more complex Path
|
||||
'\\\\RAISTLIN\\PhysicalDisk(_Total)\\Avg. Disk Bytes/Read'
|
||||
Raistlin --> Computer Name
|
||||
PhysicalDisk --> Object Name
|
||||
_Total --> The particular Instance (in this case, all instances, i.e. all drives)
|
||||
Avg. Disk Bytes/Read --> The piece of data being monitored.
|
||||
|
||||
EXAMPLE: Collecting Data with a Query
|
||||
As an example, the following code implements a logger which allows the
|
||||
user to choose what counters they would like to log, and logs those
|
||||
counters for 30 seconds, at two-second intervals.
|
||||
|
||||
query = Query()
|
||||
query.addcounterbybrowsing()
|
||||
query.collectdatafor(30,2)
|
||||
|
||||
The data is now stored in a list of lists as:
|
||||
query.curresults
|
||||
|
||||
The counters(paths) which were used to collect the data are:
|
||||
query.curpaths
|
||||
|
||||
You can use the win32pdh.ParseCounterPath(path) utility function
|
||||
to turn the paths into more easily read values for your task, or
|
||||
write the data to a file, or do whatever you want with it.
|
||||
|
||||
OTHER NOTABLE METHODS:
|
||||
query.collectdatawhile(period) # start a logging thread for collecting data
|
||||
query.collectdatawhile_stop() # signal the logging thread to stop logging
|
||||
query.collectdata() # run the query only once
|
||||
query.addperfcounter(object, counter, machine=None) # add a standard performance counter
|
||||
query.addinstcounter(object, counter,machine=None,objtype = 'Process',volatile=1,format = win32pdh.PDH_FMT_LONG) # add a possibly volatile counter
|
||||
|
||||
### Known bugs and limitations ###
|
||||
Due to a problem with threading under the PythonWin interpreter, there
|
||||
will be no data logged if the PythonWin window is not the foreground
|
||||
application. Workaround: scripts using threading should be run in the
|
||||
python.exe interpreter.
|
||||
|
||||
The volatile-counter handlers are possibly buggy, they haven't been
|
||||
tested to any extent. The wrapper Query makes it safe to pass invalid
|
||||
paths (a -1 will be returned, or the Query will be totally ignored,
|
||||
depending on the missing element), so you should be able to work around
|
||||
the error by including all possible paths and filtering out the -1's.
|
||||
|
||||
There is no way I know of to stop a thread which is currently sleeping,
|
||||
so you have to wait until the thread in collectdatawhile is activated
|
||||
again. This might become a problem in situations where the collection
|
||||
period is multiple minutes (or hours, or whatever).
|
||||
|
||||
Should make the win32pdh.ParseCounter function available to the Query
|
||||
classes as a method or something similar, so that it can be accessed
|
||||
by programmes that have just picked up an instance from somewhere.
|
||||
|
||||
Should explicitly mention where QueryErrors can be raised, and create a
|
||||
full test set to see if there are any uncaught win32api.error's still
|
||||
hanging around.
|
||||
|
||||
When using the python.exe interpreter, the addcounterbybrowsing-
|
||||
generated browser window is often hidden behind other windows. No known
|
||||
workaround other than Alt-tabing to reach the browser window.
|
||||
|
||||
### Other References ###
|
||||
The win32pdhutil module (which should be in the %pythonroot%/win32/lib
|
||||
directory) provides quick-and-dirty utilities for one-off access to
|
||||
variables from the PDH. Almost everything in that module can be done
|
||||
with a Query object, but it provides task-oriented functions for a
|
||||
number of common one-off tasks.
|
||||
|
||||
If you can access the MS Developers Network Library, you can find
|
||||
information about the PDH API as MS describes it. For a background article,
|
||||
try:
|
||||
http://msdn.microsoft.com/library/en-us/dnperfmo/html/msdn_pdhlib.asp
|
||||
|
||||
The reference guide for the PDH API was last spotted at:
|
||||
http://msdn.microsoft.com/library/en-us/perfmon/base/using_the_pdh_interface.asp
|
||||
|
||||
|
||||
In general the Python version of the API is just a wrapper around the
|
||||
Query-based version of this API (as far as I can see), so you can learn what
|
||||
you need to from there. From what I understand, the MSDN Online
|
||||
resources are available for the price of signing up for them. I can't
|
||||
guarantee how long that's supposed to last. (Or anything for that
|
||||
matter).
|
||||
http://premium.microsoft.com/isapi/devonly/prodinfo/msdnprod/msdnlib.idc?theURL=/msdn/library/sdkdoc/perfdata_4982.htm
|
||||
|
||||
The eventual plan is for my (Mike Fletcher's) Starship account to include
|
||||
a section on NT Administration, and the Query is the first project
|
||||
in this plan. There should be an article describing the creation of
|
||||
a simple logger there, but the example above is 90% of the work of
|
||||
that project, so don't sweat it if you don't find anything there.
|
||||
(currently the account hasn't been set up).
|
||||
http://starship.skyport.net/crew/mcfletch/
|
||||
|
||||
If you need to contact me immediately, (why I can't imagine), you can
|
||||
email me at mcfletch@golden.net, or just post your question to the
|
||||
Python newsgroup with a catchy subject line.
|
||||
news:comp.lang.python
|
||||
|
||||
### Other Stuff ###
|
||||
The Query classes are by Mike Fletcher, with the working code
|
||||
being corruptions of Mark Hammonds win32pdhutil module.
|
||||
|
||||
Use at your own risk, no warranties, no guarantees, no assurances,
|
||||
if you use it, you accept the risk of using it, etceteras.
|
||||
|
||||
'''
|
||||
# Feb 12, 98 - MH added "rawaddcounter" so caller can get exception details.
|
||||
|
||||
import win32pdh, win32api,time, _thread,copy
|
||||
|
||||
class BaseQuery:
|
||||
'''
|
||||
Provides wrapped access to the Performance Data Helper query
|
||||
objects, generally you should use the child class Query
|
||||
unless you have need of doing weird things :)
|
||||
|
||||
This class supports two major working paradigms. In the first,
|
||||
you open the query, and run it as many times as you need, closing
|
||||
the query when you're done with it. This is suitable for static
|
||||
queries (ones where processes being monitored don't disappear).
|
||||
|
||||
In the second, you allow the query to be opened each time and
|
||||
closed afterward. This causes the base query object to be
|
||||
destroyed after each call. Suitable for dynamic queries (ones
|
||||
which watch processes which might be closed while watching.)
|
||||
'''
|
||||
def __init__(self,paths=None):
|
||||
'''
|
||||
The PDH Query object is initialised with a single, optional
|
||||
list argument, that must be properly formatted PDH Counter
|
||||
paths. Generally this list will only be provided by the class
|
||||
when it is being unpickled (removed from storage). Normal
|
||||
use is to call the class with no arguments and use the various
|
||||
addcounter functions (particularly, for end user's, the use of
|
||||
addcounterbybrowsing is the most common approach) You might
|
||||
want to provide the list directly if you want to hard-code the
|
||||
elements with which your query deals (and thereby avoid the
|
||||
overhead of unpickling the class).
|
||||
'''
|
||||
self.counters = []
|
||||
if paths:
|
||||
self.paths = paths
|
||||
else:
|
||||
self.paths = []
|
||||
self._base = None
|
||||
self.active = 0
|
||||
self.curpaths = []
|
||||
def addcounterbybrowsing(self, flags = win32pdh.PERF_DETAIL_WIZARD, windowtitle="Python Browser"):
|
||||
'''
|
||||
Adds possibly multiple paths to the paths attribute of the query,
|
||||
does this by calling the standard counter browsing dialogue. Within
|
||||
this dialogue, find the counter you want to log, and click: Add,
|
||||
repeat for every path you want to log, then click on close. The
|
||||
paths are appended to the non-volatile paths list for this class,
|
||||
subclasses may create a function which parses the paths and decides
|
||||
(via heuristics) whether to add the path to the volatile or non-volatile
|
||||
path list.
|
||||
e.g.:
|
||||
query.addcounter()
|
||||
'''
|
||||
win32pdh.BrowseCounters(None,0, self.paths.append, flags, windowtitle)
|
||||
def rawaddcounter(self,object, counter, instance = None, inum=-1, machine=None):
|
||||
'''
|
||||
Adds a single counter path, without catching any exceptions.
|
||||
|
||||
See addcounter for details.
|
||||
'''
|
||||
path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
|
||||
self.paths.append(path)
|
||||
|
||||
def addcounter(self,object, counter, instance = None, inum=-1, machine=None):
|
||||
'''
|
||||
Adds a single counter path to the paths attribute. Normally
|
||||
this will be called by a child class' speciality functions,
|
||||
rather than being called directly by the user. (Though it isn't
|
||||
hard to call manually, since almost everything is given a default)
|
||||
This method is only functional when the query is closed (or hasn't
|
||||
yet been opened). This is to prevent conflict in multi-threaded
|
||||
query applications).
|
||||
e.g.:
|
||||
query.addcounter('Memory','Available Bytes')
|
||||
'''
|
||||
if not self.active:
|
||||
try:
|
||||
self.rawaddcounter(object, counter, instance, inum, machine)
|
||||
return 0
|
||||
except win32api.error:
|
||||
return -1
|
||||
else:
|
||||
return -1
|
||||
|
||||
def open(self):
|
||||
'''
|
||||
Build the base query object for this wrapper,
|
||||
then add all of the counters required for the query.
|
||||
Raise a QueryError if we can't complete the functions.
|
||||
If we are already open, then do nothing.
|
||||
'''
|
||||
if not self.active: # to prevent having multiple open queries
|
||||
# curpaths are made accessible here because of the possibility of volatile paths
|
||||
# which may be dynamically altered by subclasses.
|
||||
self.curpaths = copy.copy(self.paths)
|
||||
try:
|
||||
base = win32pdh.OpenQuery()
|
||||
for path in self.paths:
|
||||
try:
|
||||
self.counters.append(win32pdh.AddCounter(base, path))
|
||||
except win32api.error: # we passed a bad path
|
||||
self.counters.append(0)
|
||||
pass
|
||||
self._base = base
|
||||
self.active = 1
|
||||
return 0 # open succeeded
|
||||
except: # if we encounter any errors, kill the Query
|
||||
try:
|
||||
self.killbase(base)
|
||||
except NameError: # failed in creating query
|
||||
pass
|
||||
self.active = 0
|
||||
self.curpaths = []
|
||||
raise QueryError(self)
|
||||
return 1 # already open
|
||||
|
||||
def killbase(self,base=None):
|
||||
'''
|
||||
### This is not a public method
|
||||
Mission critical function to kill the win32pdh objects held
|
||||
by this object. User's should generally use the close method
|
||||
instead of this method, in case a sub-class has overridden
|
||||
close to provide some special functionality.
|
||||
'''
|
||||
# Kill Pythonic references to the objects in this object's namespace
|
||||
self._base = None
|
||||
counters = self.counters
|
||||
self.counters = []
|
||||
# we don't kill the curpaths for convenience, this allows the
|
||||
# user to close a query and still access the last paths
|
||||
self.active = 0
|
||||
# Now call the delete functions on all of the objects
|
||||
try:
|
||||
map(win32pdh.RemoveCounter,counters)
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
win32pdh.CloseQuery(base)
|
||||
except:
|
||||
pass
|
||||
del(counters)
|
||||
del(base)
|
||||
def close(self):
|
||||
'''
|
||||
Makes certain that the underlying query object has been closed,
|
||||
and that all counters have been removed from it. This is
|
||||
important for reference counting.
|
||||
You should only need to call close if you have previously called
|
||||
open. The collectdata methods all can handle opening and
|
||||
closing the query. Calling close multiple times is acceptable.
|
||||
'''
|
||||
try:
|
||||
self.killbase(self._base)
|
||||
except AttributeError:
|
||||
self.killbase()
|
||||
__del__ = close
|
||||
def collectdata(self,format = win32pdh.PDH_FMT_LONG):
|
||||
'''
|
||||
Returns the formatted current values for the Query
|
||||
'''
|
||||
if self._base: # we are currently open, don't change this
|
||||
return self.collectdataslave(format)
|
||||
else: # need to open and then close the _base, should be used by one-offs and elements tracking application instances
|
||||
self.open() # will raise QueryError if couldn't open the query
|
||||
temp = self.collectdataslave(format)
|
||||
self.close() # will always close
|
||||
return temp
|
||||
def collectdataslave(self,format = win32pdh.PDH_FMT_LONG):
|
||||
'''
|
||||
### Not a public method
|
||||
Called only when the Query is known to be open, runs over
|
||||
the whole set of counters, appending results to the temp,
|
||||
returns the values as a list.
|
||||
'''
|
||||
try:
|
||||
win32pdh.CollectQueryData(self._base)
|
||||
temp = []
|
||||
for counter in self.counters:
|
||||
ok = 0
|
||||
try:
|
||||
if counter:
|
||||
temp.append(win32pdh.GetFormattedCounterValue(counter, format)[1])
|
||||
ok = 1
|
||||
except win32api.error:
|
||||
pass
|
||||
if not ok:
|
||||
temp.append(-1) # a better way to signal failure???
|
||||
return temp
|
||||
except win32api.error: # will happen if, for instance, no counters are part of the query and we attempt to collect data for it.
|
||||
return [-1] * len(self.counters)
|
||||
# pickle functions
|
||||
def __getinitargs__(self):
|
||||
'''
|
||||
### Not a public method
|
||||
'''
|
||||
return (self.paths,)
|
||||
|
||||
class Query(BaseQuery):
|
||||
'''
|
||||
Performance Data Helper(PDH) Query object:
|
||||
|
||||
Provides a wrapper around the native PDH query object which
|
||||
allows for query reuse, query storage, and general maintenance
|
||||
functions (adding counter paths in various ways being the most
|
||||
obvious ones).
|
||||
'''
|
||||
def __init__(self,*args,**namedargs):
|
||||
'''
|
||||
The PDH Query object is initialised with a single, optional
|
||||
list argument, that must be properly formatted PDH Counter
|
||||
paths. Generally this list will only be provided by the class
|
||||
when it is being unpickled (removed from storage). Normal
|
||||
use is to call the class with no arguments and use the various
|
||||
addcounter functions (particularly, for end user's, the use of
|
||||
addcounterbybrowsing is the most common approach) You might
|
||||
want to provide the list directly if you want to hard-code the
|
||||
elements with which your query deals (and thereby avoid the
|
||||
overhead of unpickling the class).
|
||||
'''
|
||||
self.volatilecounters = []
|
||||
BaseQuery.__init__(*(self,)+args, **namedargs)
|
||||
def addperfcounter(self, object, counter, machine=None):
|
||||
'''
|
||||
A "Performance Counter" is a stable, known, common counter,
|
||||
such as Memory, or Processor. The use of addperfcounter by
|
||||
end-users is deprecated, since the use of
|
||||
addcounterbybrowsing is considerably more flexible and general.
|
||||
It is provided here to allow the easy development of scripts
|
||||
which need to access variables so common we know them by name
|
||||
(such as Memory|Available Bytes), and to provide symmetry with
|
||||
the add inst counter method.
|
||||
usage:
|
||||
query.addperfcounter('Memory', 'Available Bytes')
|
||||
It is just as easy to access addcounter directly, the following
|
||||
has an identicle effect.
|
||||
query.addcounter('Memory', 'Available Bytes')
|
||||
'''
|
||||
BaseQuery.addcounter(self, object=object, counter=counter, machine=machine)
|
||||
def addinstcounter(self, object, counter,machine=None,objtype = 'Process',volatile=1,format = win32pdh.PDH_FMT_LONG):
|
||||
'''
|
||||
The purpose of using an instcounter is to track particular
|
||||
instances of a counter object (e.g. a single processor, a single
|
||||
running copy of a process). For instance, to track all python.exe
|
||||
instances, you would need merely to ask:
|
||||
query.addinstcounter('python','Virtual Bytes')
|
||||
You can find the names of the objects and their available counters
|
||||
by doing an addcounterbybrowsing() call on a query object (or by
|
||||
looking in performance monitor's add dialog.)
|
||||
|
||||
Beyond merely rearranging the call arguments to make more sense,
|
||||
if the volatile flag is true, the instcounters also recalculate
|
||||
the paths of the available instances on every call to open the
|
||||
query.
|
||||
'''
|
||||
if volatile:
|
||||
self.volatilecounters.append((object,counter,machine,objtype,format))
|
||||
else:
|
||||
self.paths[len(self.paths):] = self.getinstpaths(object,counter,machine,objtype,format)
|
||||
|
||||
def getinstpaths(self,object,counter,machine=None,objtype='Process',format = win32pdh.PDH_FMT_LONG):
|
||||
'''
|
||||
### Not an end-user function
|
||||
Calculate the paths for an instance object. Should alter
|
||||
to allow processing for lists of object-counter pairs.
|
||||
'''
|
||||
items, instances = win32pdh.EnumObjectItems(None,None,objtype, -1)
|
||||
# find out how many instances of this element we have...
|
||||
instances.sort()
|
||||
try:
|
||||
cur = instances.index(object)
|
||||
except ValueError:
|
||||
return [] # no instances of this object
|
||||
temp = [object]
|
||||
try:
|
||||
while instances[cur+1] == object:
|
||||
temp.append(object)
|
||||
cur = cur+1
|
||||
except IndexError: # if we went over the end
|
||||
pass
|
||||
paths = []
|
||||
for ind in range(len(temp)):
|
||||
# can this raise an error?
|
||||
paths.append(win32pdh.MakeCounterPath( (machine,'Process',object,None,ind,counter) ) )
|
||||
return paths # should also return the number of elements for naming purposes
|
||||
|
||||
def open(self,*args,**namedargs):
|
||||
'''
|
||||
Explicitly open a query:
|
||||
When you are needing to make multiple calls to the same query,
|
||||
it is most efficient to open the query, run all of the calls,
|
||||
then close the query, instead of having the collectdata method
|
||||
automatically open and close the query each time it runs.
|
||||
There are currently no arguments to open.
|
||||
'''
|
||||
# do all the normal opening stuff, self._base is now the query object
|
||||
BaseQuery.open(*(self,)+args, **namedargs)
|
||||
# should rewrite getinstpaths to take a single tuple
|
||||
paths = []
|
||||
for tup in self.volatilecounters:
|
||||
paths[len(paths):] = self.getinstpaths(*tup)
|
||||
for path in paths:
|
||||
try:
|
||||
self.counters.append(win32pdh.AddCounter(self._base, path))
|
||||
self.curpaths.append(path) # if we fail on the line above, this path won't be in the table or the counters
|
||||
except win32api.error:
|
||||
pass # again, what to do with a malformed path???
|
||||
def collectdatafor(self, totalperiod, period=1):
|
||||
'''
|
||||
Non-threaded collection of performance data:
|
||||
This method allows you to specify the total period for which you would
|
||||
like to run the Query, and the time interval between individual
|
||||
runs. The collected data is stored in query.curresults at the
|
||||
_end_ of the run. The pathnames for the query are stored in
|
||||
query.curpaths.
|
||||
e.g.:
|
||||
query.collectdatafor(30,2)
|
||||
Will collect data for 30seconds at 2 second intervals
|
||||
'''
|
||||
tempresults = []
|
||||
try:
|
||||
self.open()
|
||||
for ind in range(totalperiod/period):
|
||||
tempresults.append(self.collectdata())
|
||||
time.sleep(period)
|
||||
self.curresults = tempresults
|
||||
finally:
|
||||
self.close()
|
||||
def collectdatawhile(self, period=1):
|
||||
'''
|
||||
Threaded collection of performance data:
|
||||
This method sets up a simple semaphor system for signalling
|
||||
when you would like to start and stop a threaded data collection
|
||||
method. The collection runs every period seconds until the
|
||||
semaphor attribute is set to a non-true value (which normally
|
||||
should be done by calling query.collectdatawhile_stop() .)
|
||||
e.g.:
|
||||
query.collectdatawhile(2)
|
||||
# starts the query running, returns control to the caller immediately
|
||||
# is collecting data every two seconds.
|
||||
# do whatever you want to do while the thread runs, then call:
|
||||
query.collectdatawhile_stop()
|
||||
# when you want to deal with the data. It is generally a good idea
|
||||
# to sleep for period seconds yourself, since the query will not copy
|
||||
# the required data until the next iteration:
|
||||
time.sleep(2)
|
||||
# now you can access the data from the attributes of the query
|
||||
query.curresults
|
||||
query.curpaths
|
||||
'''
|
||||
self.collectdatawhile_active = 1
|
||||
_thread.start_new_thread(self.collectdatawhile_slave,(period,))
|
||||
def collectdatawhile_stop(self):
|
||||
'''
|
||||
Signals the collectdatawhile slave thread to stop collecting data
|
||||
on the next logging iteration.
|
||||
'''
|
||||
self.collectdatawhile_active = 0
|
||||
def collectdatawhile_slave(self, period):
|
||||
'''
|
||||
### Not a public function
|
||||
Does the threaded work of collecting the data and storing it
|
||||
in an attribute of the class.
|
||||
'''
|
||||
tempresults = []
|
||||
try:
|
||||
self.open() # also sets active, so can't be changed.
|
||||
while self.collectdatawhile_active:
|
||||
tempresults.append(self.collectdata())
|
||||
time.sleep(period)
|
||||
self.curresults = tempresults
|
||||
finally:
|
||||
self.close()
|
||||
|
||||
# pickle functions
|
||||
def __getinitargs__(self):
|
||||
return (self.paths,)
|
||||
def __getstate__(self):
|
||||
return self.volatilecounters
|
||||
def __setstate__(self, volatilecounters):
|
||||
self.volatilecounters = volatilecounters
|
||||
|
||||
|
||||
class QueryError:
|
||||
def __init__(self, query):
|
||||
self.query = query
|
||||
def __repr__(self):
|
||||
return '<Query Error in %s>'%repr(self.query)
|
||||
__str__ = __repr__
|
||||
|
||||
168
Pywin32/lib/x32/win32/lib/win32pdhutil.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""Utilities for the win32 Performance Data Helper module
|
||||
|
||||
Example:
|
||||
To get a single bit of data:
|
||||
>>> import win32pdhutil
|
||||
>>> win32pdhutil.GetPerformanceAttributes("Memory", "Available Bytes")
|
||||
6053888
|
||||
>>> win32pdhutil.FindPerformanceAttributesByName("python", counter="Virtual Bytes")
|
||||
[22278144]
|
||||
|
||||
First example returns data which is not associated with any specific instance.
|
||||
|
||||
The second example reads data for a specific instance - hence the list return -
|
||||
it would return one result for each instance of Python running.
|
||||
|
||||
In general, it can be tricky finding exactly the "name" of the data you wish to query.
|
||||
Although you can use <om win32pdh.EnumObjectItems>(None,None,(eg)"Memory", -1) to do this,
|
||||
the easiest way is often to simply use PerfMon to find out the names.
|
||||
"""
|
||||
|
||||
import win32pdh, time
|
||||
|
||||
error = win32pdh.error
|
||||
|
||||
# Handle some localization issues.
|
||||
# see http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q287/1/59.asp&NoWebContent=1
|
||||
# Build a map of english_counter_name: counter_id
|
||||
counter_english_map = {}
|
||||
|
||||
def find_pdh_counter_localized_name(english_name, machine_name = None):
|
||||
if not counter_english_map:
|
||||
import win32api, win32con
|
||||
counter_reg_value = win32api.RegQueryValueEx(win32con.HKEY_PERFORMANCE_DATA,
|
||||
"Counter 009")
|
||||
counter_list = counter_reg_value[0]
|
||||
for i in range(0, len(counter_list) - 1, 2):
|
||||
try:
|
||||
counter_id = int(counter_list[i])
|
||||
except ValueError:
|
||||
continue
|
||||
counter_english_map[counter_list[i+1].lower()] = counter_id
|
||||
return win32pdh.LookupPerfNameByIndex(machine_name, counter_english_map[english_name.lower()])
|
||||
|
||||
def GetPerformanceAttributes(object, counter, instance = None, inum=-1,
|
||||
format = win32pdh.PDH_FMT_LONG, machine=None):
|
||||
# NOTE: Many counters require 2 samples to give accurate results,
|
||||
# including "% Processor Time" (as by definition, at any instant, a
|
||||
# thread's CPU usage is either 0 or 100). To read counters like this,
|
||||
# you should copy this function, but keep the counter open, and call
|
||||
# CollectQueryData() each time you need to know.
|
||||
# See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938
|
||||
# and http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
|
||||
# My older explanation for this was that the "AddCounter" process forced
|
||||
# the CPU to 100%, but the above makes more sense :)
|
||||
path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
|
||||
hq = win32pdh.OpenQuery()
|
||||
try:
|
||||
hc = win32pdh.AddCounter(hq, path)
|
||||
try:
|
||||
win32pdh.CollectQueryData(hq)
|
||||
type, val = win32pdh.GetFormattedCounterValue(hc, format)
|
||||
return val
|
||||
finally:
|
||||
win32pdh.RemoveCounter(hc)
|
||||
finally:
|
||||
win32pdh.CloseQuery(hq)
|
||||
|
||||
def FindPerformanceAttributesByName(instanceName, object = None,
|
||||
counter = None,
|
||||
format = win32pdh.PDH_FMT_LONG,
|
||||
machine = None, bRefresh=0):
|
||||
"""Find peformance attributes by (case insensitive) instance name.
|
||||
|
||||
Given a process name, return a list with the requested attributes.
|
||||
Most useful for returning a tuple of PIDs given a process name.
|
||||
"""
|
||||
if object is None: object = find_pdh_counter_localized_name("Process", machine)
|
||||
if counter is None: counter = find_pdh_counter_localized_name("ID Process", machine)
|
||||
if bRefresh: # PDH docs say this is how you do a refresh.
|
||||
win32pdh.EnumObjects(None, machine, 0, 1)
|
||||
instanceName = instanceName.lower()
|
||||
items, instances = win32pdh.EnumObjectItems(None,None,object, -1)
|
||||
# Track multiple instances.
|
||||
instance_dict = {}
|
||||
for instance in instances:
|
||||
try:
|
||||
instance_dict[instance] = instance_dict[instance] + 1
|
||||
except KeyError:
|
||||
instance_dict[instance] = 0
|
||||
|
||||
ret = []
|
||||
for instance, max_instances in instance_dict.items():
|
||||
for inum in range(max_instances+1):
|
||||
if instance.lower() == instanceName:
|
||||
ret.append(GetPerformanceAttributes(object, counter,
|
||||
instance, inum, format,
|
||||
machine))
|
||||
return ret
|
||||
|
||||
def ShowAllProcesses():
|
||||
object = find_pdh_counter_localized_name("Process")
|
||||
items, instances = win32pdh.EnumObjectItems(None,None,object,
|
||||
win32pdh.PERF_DETAIL_WIZARD)
|
||||
# Need to track multiple instances of the same name.
|
||||
instance_dict = {}
|
||||
for instance in instances:
|
||||
try:
|
||||
instance_dict[instance] = instance_dict[instance] + 1
|
||||
except KeyError:
|
||||
instance_dict[instance] = 0
|
||||
|
||||
# Bit of a hack to get useful info.
|
||||
items = [find_pdh_counter_localized_name("ID Process")] + items[:5]
|
||||
print("Process Name", ",".join(items))
|
||||
for instance, max_instances in instance_dict.items():
|
||||
for inum in range(max_instances+1):
|
||||
hq = win32pdh.OpenQuery()
|
||||
hcs = []
|
||||
for item in items:
|
||||
path = win32pdh.MakeCounterPath( (None,object,instance,
|
||||
None, inum, item) )
|
||||
hcs.append(win32pdh.AddCounter(hq, path))
|
||||
win32pdh.CollectQueryData(hq)
|
||||
# as per http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938, some "%" based
|
||||
# counters need two collections
|
||||
time.sleep(0.01)
|
||||
win32pdh.CollectQueryData(hq)
|
||||
print("%-15s\t" % (instance[:15]), end=' ')
|
||||
for hc in hcs:
|
||||
type, val = win32pdh.GetFormattedCounterValue(hc, win32pdh.PDH_FMT_LONG)
|
||||
print("%5d" % (val), end=' ')
|
||||
win32pdh.RemoveCounter(hc)
|
||||
print()
|
||||
win32pdh.CloseQuery(hq)
|
||||
|
||||
# NOTE: This BrowseCallback doesn't seem to work on Vista for markh.
|
||||
# XXX - look at why!?
|
||||
# Some counters on Vista require elevation, and callback would previously
|
||||
# clear exceptions without printing them.
|
||||
def BrowseCallBackDemo(counters):
|
||||
## BrowseCounters can now return multiple counter paths
|
||||
for counter in counters:
|
||||
machine, object, instance, parentInstance, index, counterName = \
|
||||
win32pdh.ParseCounterPath(counter)
|
||||
|
||||
result = GetPerformanceAttributes(object, counterName, instance, index,
|
||||
win32pdh.PDH_FMT_DOUBLE, machine)
|
||||
print("Value of '%s' is" % counter, result)
|
||||
print("Added '%s' on object '%s' (machine %s), instance %s(%d)-parent of %s" \
|
||||
% (counterName, object, machine, instance, index, parentInstance))
|
||||
return 0
|
||||
|
||||
def browse(callback = BrowseCallBackDemo, title="Python Browser",
|
||||
level=win32pdh.PERF_DETAIL_WIZARD):
|
||||
win32pdh.BrowseCounters(None,0, callback, level, title, ReturnMultiple=True)
|
||||
|
||||
if __name__=='__main__':
|
||||
ShowAllProcesses()
|
||||
# Show how to get a couple of attributes by name.
|
||||
counter = find_pdh_counter_localized_name("Virtual Bytes")
|
||||
print("Virtual Bytes = ", FindPerformanceAttributesByName("python",
|
||||
counter=counter))
|
||||
print("Available Bytes = ", GetPerformanceAttributes(
|
||||
find_pdh_counter_localized_name("Memory"),
|
||||
find_pdh_counter_localized_name("Available Bytes")))
|
||||
# And a browser.
|
||||
print("Browsing for counters...")
|
||||
browse()
|
||||
602
Pywin32/lib/x32/win32/lib/win32rcparser.py
Normal file
@@ -0,0 +1,602 @@
|
||||
# Windows dialog .RC file parser, by Adam Walker.
|
||||
|
||||
# This module was adapted from the spambayes project, and is Copyright
|
||||
# 2003/2004 The Python Software Foundation and is covered by the Python
|
||||
# Software Foundation license.
|
||||
"""
|
||||
This is a parser for Windows .rc files, which are text files which define
|
||||
dialogs and other Windows UI resources.
|
||||
"""
|
||||
__author__="Adam Walker"
|
||||
__version__="0.11"
|
||||
|
||||
import sys, os, shlex, stat
|
||||
import pprint
|
||||
import win32con
|
||||
import commctrl
|
||||
|
||||
_controlMap = {"DEFPUSHBUTTON":0x80,
|
||||
"PUSHBUTTON":0x80,
|
||||
"Button":0x80,
|
||||
"GROUPBOX":0x80,
|
||||
"Static":0x82,
|
||||
"CTEXT":0x82,
|
||||
"RTEXT":0x82,
|
||||
"LTEXT":0x82,
|
||||
"LISTBOX":0x83,
|
||||
"SCROLLBAR":0x84,
|
||||
"COMBOBOX":0x85,
|
||||
"EDITTEXT":0x81,
|
||||
"ICON":0x82,
|
||||
"RICHEDIT":"RichEdit20A"
|
||||
}
|
||||
|
||||
# These are "default styles" for certain controls - ie, Visual Studio assumes
|
||||
# the styles will be applied, and emits a "NOT {STYLE_NAME}" if it is to be
|
||||
# disabled. These defaults have been determined by experimentation, so may
|
||||
# not be completely accurate (most notably, some styles and/or control-types
|
||||
# may be missing.
|
||||
_addDefaults = {"EDITTEXT":win32con.WS_BORDER | win32con.WS_TABSTOP,
|
||||
"GROUPBOX":win32con.BS_GROUPBOX,
|
||||
"LTEXT":win32con.SS_LEFT,
|
||||
"DEFPUSHBUTTON":win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
|
||||
"PUSHBUTTON": win32con.WS_TABSTOP,
|
||||
"CTEXT":win32con.SS_CENTER,
|
||||
"RTEXT":win32con.SS_RIGHT,
|
||||
"ICON":win32con.SS_ICON,
|
||||
"LISTBOX":win32con.LBS_NOTIFY,
|
||||
}
|
||||
|
||||
defaultControlStyle = win32con.WS_CHILD | win32con.WS_VISIBLE
|
||||
defaultControlStyleEx = 0
|
||||
|
||||
class DialogDef:
|
||||
name = ""
|
||||
id = 0
|
||||
style = 0
|
||||
styleEx = None
|
||||
caption = ""
|
||||
font = "MS Sans Serif"
|
||||
fontSize = 8
|
||||
x = 0
|
||||
y = 0
|
||||
w = 0
|
||||
h = 0
|
||||
template = None
|
||||
def __init__(self, n, i):
|
||||
self.name = n
|
||||
self.id = i
|
||||
self.styles = []
|
||||
self.stylesEx = []
|
||||
self.controls = []
|
||||
#print "dialog def for ",self.name, self.id
|
||||
def createDialogTemplate(self):
|
||||
t = None
|
||||
self.template = [[self.caption,
|
||||
(self.x,self.y,self.w,self.h),
|
||||
self.style, self.styleEx,
|
||||
(self.fontSize, self.font)]
|
||||
]
|
||||
# Add the controls
|
||||
for control in self.controls:
|
||||
self.template.append(control.createDialogTemplate())
|
||||
return self.template
|
||||
|
||||
class ControlDef:
|
||||
id = ""
|
||||
controlType = ""
|
||||
subType = ""
|
||||
idNum = 0
|
||||
style = defaultControlStyle
|
||||
styleEx = defaultControlStyleEx
|
||||
label = ""
|
||||
x = 0
|
||||
y = 0
|
||||
w = 0
|
||||
h = 0
|
||||
def __init__(self):
|
||||
self.styles = []
|
||||
self.stylesEx = []
|
||||
def toString(self):
|
||||
s = "<Control id:"+self.id+" controlType:"+self.controlType+" subType:"+self.subType\
|
||||
+" idNum:"+str(self.idNum)+" style:"+str(self.style)+" styles:"+str(self.styles)+" label:"+self.label\
|
||||
+" x:"+str(self.x)+" y:"+str(self.y)+" w:"+str(self.w)+" h:"+str(self.h)+">"
|
||||
return s
|
||||
def createDialogTemplate(self):
|
||||
ct = self.controlType
|
||||
if "CONTROL"==ct:
|
||||
ct = self.subType
|
||||
if ct in _controlMap:
|
||||
ct = _controlMap[ct]
|
||||
t = [ct, self.label, self.idNum, (self.x, self.y, self.w, self.h), self.style, self.styleEx]
|
||||
#print t
|
||||
return t
|
||||
|
||||
class StringDef:
|
||||
def __init__(self, id, idNum, value):
|
||||
self.id = id
|
||||
self.idNum = idNum
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return "StringDef(%r, %r, %r)" % (self.id, self.idNum, self.value)
|
||||
|
||||
class RCParser:
|
||||
next_id = 1001
|
||||
dialogs = {}
|
||||
_dialogs = {}
|
||||
debugEnabled = False
|
||||
token = ""
|
||||
|
||||
def __init__(self):
|
||||
self.ungot = False
|
||||
self.ids = {"IDC_STATIC": -1}
|
||||
self.names = {-1:"IDC_STATIC"}
|
||||
self.bitmaps = {}
|
||||
self.stringTable = {}
|
||||
self.icons = {}
|
||||
|
||||
def debug(self, *args):
|
||||
if self.debugEnabled:
|
||||
print(args)
|
||||
|
||||
def getToken(self):
|
||||
if self.ungot:
|
||||
self.ungot = False
|
||||
self.debug("getToken returns (ungot):", self.token)
|
||||
return self.token
|
||||
self.token = self.lex.get_token()
|
||||
self.debug("getToken returns:", self.token)
|
||||
if self.token=="":
|
||||
self.token = None
|
||||
return self.token
|
||||
|
||||
def ungetToken(self):
|
||||
self.ungot = True
|
||||
|
||||
def getCheckToken(self, expected):
|
||||
tok = self.getToken()
|
||||
assert tok == expected, "Expected token '%s', but got token '%s'!" % (expected, tok)
|
||||
return tok
|
||||
|
||||
def getCommaToken(self):
|
||||
return self.getCheckToken(",")
|
||||
|
||||
# Return the *current* token as a number, only consuming a token
|
||||
# if it is the negative-sign.
|
||||
def currentNumberToken(self):
|
||||
mult = 1
|
||||
if self.token=='-':
|
||||
mult = -1
|
||||
self.getToken()
|
||||
return int(self.token) * mult
|
||||
|
||||
# Return the *current* token as a string literal (ie, self.token will be a
|
||||
# quote. consumes all tokens until the end of the string
|
||||
def currentQuotedString(self):
|
||||
# Handle quoted strings - pity shlex doesn't handle it.
|
||||
assert self.token.startswith('"'), self.token
|
||||
bits = [self.token]
|
||||
while 1:
|
||||
tok = self.getToken()
|
||||
if not tok.startswith('"'):
|
||||
self.ungetToken()
|
||||
break
|
||||
bits.append(tok)
|
||||
sval = "".join(bits)[1:-1] # Remove end quotes.
|
||||
# Fixup quotes in the body, and all (some?) quoted characters back
|
||||
# to their raw value.
|
||||
for i, o in ('""', '"'), ("\\r", "\r"), ("\\n", "\n"), ("\\t", "\t"):
|
||||
sval = sval.replace(i, o)
|
||||
return sval
|
||||
|
||||
def load(self, rcstream):
|
||||
"""
|
||||
RCParser.loadDialogs(rcFileName) -> None
|
||||
Load the dialog information into the parser. Dialog Definations can then be accessed
|
||||
using the "dialogs" dictionary member (name->DialogDef). The "ids" member contains the dictionary of id->name.
|
||||
The "names" member contains the dictionary of name->id
|
||||
"""
|
||||
self.open(rcstream)
|
||||
self.getToken()
|
||||
while self.token!=None:
|
||||
self.parse()
|
||||
self.getToken()
|
||||
|
||||
def open(self, rcstream):
|
||||
self.lex = shlex.shlex(rcstream)
|
||||
self.lex.commenters = "//#"
|
||||
|
||||
def parseH(self, file):
|
||||
lex = shlex.shlex(file)
|
||||
lex.commenters = "//"
|
||||
token = " "
|
||||
while token is not None:
|
||||
token = lex.get_token()
|
||||
if token == "" or token is None:
|
||||
token = None
|
||||
else:
|
||||
if token=='define':
|
||||
n = lex.get_token()
|
||||
i = int(lex.get_token())
|
||||
self.ids[n] = i
|
||||
if i in self.names:
|
||||
# Dupe ID really isn't a problem - most consumers
|
||||
# want to go from name->id, and this is OK.
|
||||
# It means you can't go from id->name though.
|
||||
pass
|
||||
# ignore AppStudio special ones
|
||||
#if not n.startswith("_APS_"):
|
||||
# print "Duplicate id",i,"for",n,"is", self.names[i]
|
||||
else:
|
||||
self.names[i] = n
|
||||
if self.next_id<=i:
|
||||
self.next_id = i+1
|
||||
|
||||
def parse(self):
|
||||
noid_parsers = {
|
||||
"STRINGTABLE": self.parse_stringtable,
|
||||
}
|
||||
|
||||
id_parsers = {
|
||||
"DIALOG" : self.parse_dialog,
|
||||
"DIALOGEX": self.parse_dialog,
|
||||
# "TEXTINCLUDE": self.parse_textinclude,
|
||||
"BITMAP": self.parse_bitmap,
|
||||
"ICON": self.parse_icon,
|
||||
}
|
||||
deep = 0
|
||||
base_token = self.token
|
||||
rp = noid_parsers.get(base_token)
|
||||
if rp is not None:
|
||||
rp()
|
||||
else:
|
||||
# Not something we parse that isn't prefixed by an ID
|
||||
# See if it is an ID prefixed item - if it is, our token
|
||||
# is the resource ID.
|
||||
resource_id = self.token
|
||||
self.getToken()
|
||||
if self.token is None:
|
||||
return
|
||||
|
||||
if "BEGIN" == self.token:
|
||||
# A 'BEGIN' for a structure we don't understand - skip to the
|
||||
# matching 'END'
|
||||
deep = 1
|
||||
while deep!=0 and self.token is not None:
|
||||
self.getToken()
|
||||
self.debug("Zooming over", self.token)
|
||||
if "BEGIN" == self.token:
|
||||
deep += 1
|
||||
elif "END" == self.token:
|
||||
deep -= 1
|
||||
else:
|
||||
rp = id_parsers.get(self.token)
|
||||
if rp is not None:
|
||||
self.debug("Dispatching '%s'" % (self.token,))
|
||||
rp(resource_id)
|
||||
else:
|
||||
# We don't know what the resource type is, but we
|
||||
# have already consumed the next, which can cause problems,
|
||||
# so push it back.
|
||||
self.debug("Skipping top-level '%s'" % base_token)
|
||||
self.ungetToken()
|
||||
|
||||
def addId(self, id_name):
|
||||
if id_name in self.ids:
|
||||
id = self.ids[id_name]
|
||||
else:
|
||||
# IDOK, IDCANCEL etc are special - if a real resource has this value
|
||||
for n in ["IDOK","IDCANCEL","IDYES","IDNO", "IDABORT"]:
|
||||
if id_name == n:
|
||||
v = getattr(win32con, n)
|
||||
self.ids[n] = v
|
||||
self.names[v] = n
|
||||
return v
|
||||
id = self.next_id
|
||||
self.next_id += 1
|
||||
self.ids[id_name] = id
|
||||
self.names[id] = id_name
|
||||
return id
|
||||
|
||||
def lang(self):
|
||||
while self.token[0:4]=="LANG" or self.token[0:7]=="SUBLANG" or self.token==',':
|
||||
self.getToken();
|
||||
|
||||
def parse_textinclude(self, res_id):
|
||||
while self.getToken() != "BEGIN":
|
||||
pass
|
||||
while 1:
|
||||
if self.token == "END":
|
||||
break
|
||||
s = self.getToken()
|
||||
|
||||
def parse_stringtable(self):
|
||||
while self.getToken() != "BEGIN":
|
||||
pass
|
||||
while 1:
|
||||
self.getToken()
|
||||
if self.token == "END":
|
||||
break
|
||||
sid = self.token
|
||||
self.getToken()
|
||||
sd = StringDef(sid, self.addId(sid), self.currentQuotedString())
|
||||
self.stringTable[sid] = sd
|
||||
|
||||
def parse_bitmap(self, name):
|
||||
return self.parse_bitmap_or_icon(name, self.bitmaps)
|
||||
|
||||
def parse_icon(self, name):
|
||||
return self.parse_bitmap_or_icon(name, self.icons)
|
||||
|
||||
def parse_bitmap_or_icon(self, name, dic):
|
||||
self.getToken()
|
||||
while not self.token.startswith('"'):
|
||||
self.getToken()
|
||||
bmf = self.token[1:-1] # quotes
|
||||
dic[name] = bmf
|
||||
|
||||
def parse_dialog(self, name):
|
||||
dlg = DialogDef(name,self.addId(name))
|
||||
assert len(dlg.controls)==0
|
||||
self._dialogs[name] = dlg
|
||||
extras = []
|
||||
self.getToken()
|
||||
while not self.token.isdigit():
|
||||
self.debug("extra", self.token)
|
||||
extras.append(self.token)
|
||||
self.getToken()
|
||||
dlg.x = int(self.token)
|
||||
self.getCommaToken()
|
||||
self.getToken() # number
|
||||
dlg.y = int(self.token)
|
||||
self.getCommaToken()
|
||||
self.getToken() # number
|
||||
dlg.w = int(self.token)
|
||||
self.getCommaToken()
|
||||
self.getToken() # number
|
||||
dlg.h = int(self.token)
|
||||
self.getToken()
|
||||
while not (self.token==None or self.token=="" or self.token=="END"):
|
||||
if self.token=="STYLE":
|
||||
self.dialogStyle(dlg)
|
||||
elif self.token=="EXSTYLE":
|
||||
self.dialogExStyle(dlg)
|
||||
elif self.token=="CAPTION":
|
||||
self.dialogCaption(dlg)
|
||||
elif self.token=="FONT":
|
||||
self.dialogFont(dlg)
|
||||
elif self.token=="BEGIN":
|
||||
self.controls(dlg)
|
||||
else:
|
||||
break
|
||||
self.dialogs[name] = dlg.createDialogTemplate()
|
||||
|
||||
def dialogStyle(self, dlg):
|
||||
dlg.style, dlg.styles = self.styles( [], win32con.DS_SETFONT)
|
||||
def dialogExStyle(self, dlg):
|
||||
self.getToken()
|
||||
dlg.styleEx, dlg.stylesEx = self.styles( [], 0)
|
||||
|
||||
def styles(self, defaults, defaultStyle):
|
||||
list = defaults
|
||||
style = defaultStyle
|
||||
|
||||
if "STYLE"==self.token:
|
||||
self.getToken()
|
||||
i = 0
|
||||
Not = False
|
||||
while ((i%2==1 and ("|"==self.token or "NOT"==self.token)) or (i%2==0)) and not self.token==None:
|
||||
Not = False;
|
||||
if "NOT"==self.token:
|
||||
Not = True
|
||||
self.getToken()
|
||||
i += 1
|
||||
if self.token!="|":
|
||||
if self.token in win32con.__dict__:
|
||||
value = getattr(win32con,self.token)
|
||||
else:
|
||||
if self.token in commctrl.__dict__:
|
||||
value = getattr(commctrl,self.token)
|
||||
else:
|
||||
value = 0
|
||||
if Not:
|
||||
list.append("NOT "+self.token)
|
||||
self.debug("styles add Not",self.token, value)
|
||||
style &= ~value
|
||||
else:
|
||||
list.append(self.token)
|
||||
self.debug("styles add", self.token, value)
|
||||
style |= value
|
||||
self.getToken()
|
||||
self.debug("style is ",style)
|
||||
|
||||
return style, list
|
||||
|
||||
def dialogCaption(self, dlg):
|
||||
if "CAPTION"==self.token:
|
||||
self.getToken()
|
||||
self.token = self.token[1:-1]
|
||||
self.debug("Caption is:",self.token)
|
||||
dlg.caption = self.token
|
||||
self.getToken()
|
||||
def dialogFont(self, dlg):
|
||||
if "FONT"==self.token:
|
||||
self.getToken()
|
||||
dlg.fontSize = int(self.token)
|
||||
self.getCommaToken()
|
||||
self.getToken() # Font name
|
||||
dlg.font = self.token[1:-1] # it's quoted
|
||||
self.getToken()
|
||||
while "BEGIN"!=self.token:
|
||||
self.getToken()
|
||||
def controls(self, dlg):
|
||||
if self.token=="BEGIN": self.getToken()
|
||||
# All controls look vaguely like:
|
||||
# TYPE [text, ] Control_id, l, t, r, b [, style]
|
||||
# .rc parser documents all control types as:
|
||||
# CHECKBOX, COMBOBOX, CONTROL, CTEXT, DEFPUSHBUTTON, EDITTEXT, GROUPBOX,
|
||||
# ICON, LISTBOX, LTEXT, PUSHBUTTON, RADIOBUTTON, RTEXT, SCROLLBAR
|
||||
without_text = ["EDITTEXT", "COMBOBOX", "LISTBOX", "SCROLLBAR"]
|
||||
while self.token!="END":
|
||||
control = ControlDef()
|
||||
control.controlType = self.token;
|
||||
self.getToken()
|
||||
if control.controlType not in without_text:
|
||||
if self.token[0:1]=='"':
|
||||
control.label = self.currentQuotedString()
|
||||
# Some funny controls, like icons and picture controls use
|
||||
# the "window text" as extra resource ID (ie, the ID of the
|
||||
# icon itself). This may be either a literal, or an ID string.
|
||||
elif self.token=="-" or self.token.isdigit():
|
||||
control.label = str(self.currentNumberToken())
|
||||
else:
|
||||
# An ID - use the numeric equiv.
|
||||
control.label = str(self.addId(self.token))
|
||||
self.getCommaToken()
|
||||
self.getToken()
|
||||
# Control IDs may be "names" or literal ints
|
||||
if self.token=="-" or self.token.isdigit():
|
||||
control.id = self.currentNumberToken()
|
||||
control.idNum = control.id
|
||||
else:
|
||||
# name of an ID
|
||||
control.id = self.token
|
||||
control.idNum = self.addId(control.id)
|
||||
self.getCommaToken()
|
||||
|
||||
if control.controlType == "CONTROL":
|
||||
self.getToken()
|
||||
control.subType = self.token[1:-1]
|
||||
thisDefaultStyle = defaultControlStyle | \
|
||||
_addDefaults.get(control.subType, 0)
|
||||
# Styles
|
||||
self.getCommaToken()
|
||||
self.getToken()
|
||||
control.style, control.styles = self.styles([], thisDefaultStyle)
|
||||
else:
|
||||
thisDefaultStyle = defaultControlStyle | \
|
||||
_addDefaults.get(control.controlType, 0)
|
||||
# incase no style is specified.
|
||||
control.style = thisDefaultStyle
|
||||
# Rect
|
||||
control.x = int(self.getToken())
|
||||
self.getCommaToken()
|
||||
control.y = int(self.getToken())
|
||||
self.getCommaToken()
|
||||
control.w = int(self.getToken())
|
||||
self.getCommaToken()
|
||||
self.getToken()
|
||||
control.h = int(self.token)
|
||||
self.getToken()
|
||||
if self.token==",":
|
||||
self.getToken()
|
||||
control.style, control.styles = self.styles([], thisDefaultStyle)
|
||||
if self.token==",":
|
||||
self.getToken()
|
||||
control.styleEx, control.stylesEx = self.styles([], defaultControlStyleEx)
|
||||
#print control.toString()
|
||||
dlg.controls.append(control)
|
||||
|
||||
def ParseStreams(rc_file, h_file):
|
||||
rcp = RCParser()
|
||||
if h_file:
|
||||
rcp.parseH(h_file)
|
||||
try:
|
||||
rcp.load(rc_file)
|
||||
except:
|
||||
lex = getattr(rcp, "lex", None)
|
||||
if lex:
|
||||
print("ERROR parsing dialogs at line", lex.lineno)
|
||||
print("Next 10 tokens are:")
|
||||
for i in range(10):
|
||||
print(lex.get_token(), end=' ')
|
||||
print()
|
||||
raise
|
||||
return rcp
|
||||
|
||||
def Parse(rc_name, h_name = None):
|
||||
if h_name:
|
||||
h_file = open(h_name, "rU")
|
||||
else:
|
||||
# See if same basename as the .rc
|
||||
h_name = rc_name[:-2]+"h"
|
||||
try:
|
||||
h_file = open(h_name, "rU")
|
||||
except IOError:
|
||||
# See if MSVC default of 'resource.h' in the same dir.
|
||||
h_name = os.path.join(os.path.dirname(rc_name), "resource.h")
|
||||
try:
|
||||
h_file = open(h_name, "rU")
|
||||
except IOError:
|
||||
# .h files are optional anyway
|
||||
h_file = None
|
||||
rc_file = open(rc_name, "rU")
|
||||
try:
|
||||
return ParseStreams(rc_file, h_file)
|
||||
finally:
|
||||
if h_file is not None:
|
||||
h_file.close()
|
||||
rc_file.close()
|
||||
return rcp
|
||||
|
||||
def GenerateFrozenResource(rc_name, output_name, h_name = None):
|
||||
"""Converts an .rc windows resource source file into a python source file
|
||||
with the same basic public interface as the rest of this module.
|
||||
Particularly useful for py2exe or other 'freeze' type solutions,
|
||||
where a frozen .py file can be used inplace of a real .rc file.
|
||||
"""
|
||||
rcp = Parse(rc_name, h_name)
|
||||
in_stat = os.stat(rc_name)
|
||||
|
||||
out = open(output_name, "wt")
|
||||
out.write("#%s\n" % output_name)
|
||||
out.write("#This is a generated file. Please edit %s instead.\n" % rc_name)
|
||||
out.write("__version__=%r\n" % __version__)
|
||||
out.write("_rc_size_=%d\n_rc_mtime_=%d\n" % (in_stat[stat.ST_SIZE], in_stat[stat.ST_MTIME]))
|
||||
|
||||
out.write("class StringDef:\n")
|
||||
out.write("\tdef __init__(self, id, idNum, value):\n")
|
||||
out.write("\t\tself.id = id\n")
|
||||
out.write("\t\tself.idNum = idNum\n")
|
||||
out.write("\t\tself.value = value\n")
|
||||
out.write("\tdef __repr__(self):\n")
|
||||
out.write("\t\treturn \"StringDef(%r, %r, %r)\" % (self.id, self.idNum, self.value)\n")
|
||||
|
||||
out.write("class FakeParser:\n")
|
||||
|
||||
for name in "dialogs", "ids", "names", "bitmaps", "icons", "stringTable":
|
||||
out.write("\t%s = \\\n" % (name,))
|
||||
pprint.pprint(getattr(rcp, name), out)
|
||||
out.write("\n")
|
||||
|
||||
out.write("def Parse(s):\n")
|
||||
out.write("\treturn FakeParser()\n")
|
||||
out.close()
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv) <= 1:
|
||||
print(__doc__)
|
||||
print()
|
||||
print("See test_win32rcparser.py, and the win32rcparser directory (both")
|
||||
print("in the test suite) for an example of this module's usage.")
|
||||
else:
|
||||
import pprint
|
||||
filename = sys.argv[1]
|
||||
if "-v" in sys.argv:
|
||||
RCParser.debugEnabled = 1
|
||||
print("Dumping all resources in '%s'" % filename)
|
||||
resources = Parse(filename)
|
||||
for id, ddef in resources.dialogs.items():
|
||||
print("Dialog %s (%d controls)" % (id, len(ddef)))
|
||||
pprint.pprint(ddef)
|
||||
print()
|
||||
for id, sdef in resources.stringTable.items():
|
||||
print("String %s=%r" % (id, sdef.value))
|
||||
print()
|
||||
for id, sdef in resources.bitmaps.items():
|
||||
print("Bitmap %s=%r" % (id, sdef))
|
||||
print()
|
||||
for id, sdef in resources.icons.items():
|
||||
print("Icon %s=%r" % (id, sdef))
|
||||
print()
|
||||
839
Pywin32/lib/x32/win32/lib/win32serviceutil.py
Normal file
@@ -0,0 +1,839 @@
|
||||
# General purpose service utilities, both for standard Python scripts,
|
||||
# and for for Python programs which run as services...
|
||||
#
|
||||
# Note that most utility functions here will raise win32api.error's
|
||||
# (which is == win32service.error, pywintypes.error, etc)
|
||||
# when things go wrong - eg, not enough permissions to hit the
|
||||
# registry etc.
|
||||
|
||||
import win32service, win32api, win32con, winerror
|
||||
import sys, pywintypes, os, warnings
|
||||
error = RuntimeError
|
||||
|
||||
def LocatePythonServiceExe(exeName = None):
|
||||
if not exeName and hasattr(sys, "frozen"):
|
||||
# If py2exe etc calls this with no exeName, default is current exe.
|
||||
return sys.executable
|
||||
|
||||
# Try and find the specified EXE somewhere. If specifically registered,
|
||||
# use it. Otherwise look down sys.path, and the global PATH environment.
|
||||
if exeName is None:
|
||||
if os.path.splitext(win32service.__file__)[0].endswith("_d"):
|
||||
exeName = "PythonService_d.exe"
|
||||
else:
|
||||
exeName = "PythonService.exe"
|
||||
# See if it exists as specified
|
||||
if os.path.isfile(exeName): return win32api.GetFullPathName(exeName)
|
||||
baseName = os.path.splitext(os.path.basename(exeName))[0]
|
||||
try:
|
||||
exeName = win32api.RegQueryValue(win32con.HKEY_LOCAL_MACHINE,
|
||||
"Software\\Python\\%s\\%s" % (baseName, sys.winver))
|
||||
if os.path.isfile(exeName):
|
||||
return exeName
|
||||
raise RuntimeError("The executable '%s' is registered as the Python " \
|
||||
"service exe, but it does not exist as specified" \
|
||||
% exeName)
|
||||
except win32api.error:
|
||||
# OK - not there - lets go a-searchin'
|
||||
for path in [sys.prefix] + sys.path:
|
||||
look = os.path.join(path, exeName)
|
||||
if os.path.isfile(look):
|
||||
return win32api.GetFullPathName(look)
|
||||
# Try the global Path.
|
||||
try:
|
||||
return win32api.SearchPath(None, exeName)[0]
|
||||
except win32api.error:
|
||||
msg = "%s is not correctly registered\nPlease locate and run %s, and it will self-register\nThen run this service registration process again." % (exeName, exeName)
|
||||
raise error(msg)
|
||||
|
||||
def _GetServiceShortName(longName):
|
||||
# looks up a services name
|
||||
# from the display name
|
||||
# Thanks to Andy McKay for this code.
|
||||
access = win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
|
||||
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access)
|
||||
num = win32api.RegQueryInfoKey(hkey)[0]
|
||||
longName = longName.lower()
|
||||
# loop through number of subkeys
|
||||
for x in range(0, num):
|
||||
# find service name, open subkey
|
||||
svc = win32api.RegEnumKey(hkey, x)
|
||||
skey = win32api.RegOpenKey(hkey, svc, 0, access)
|
||||
try:
|
||||
# find display name
|
||||
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
|
||||
if thisName.lower() == longName:
|
||||
return svc
|
||||
except win32api.error:
|
||||
# in case there is no key called DisplayName
|
||||
pass
|
||||
return None
|
||||
|
||||
# Open a service given either it's long or short name.
|
||||
def SmartOpenService(hscm, name, access):
|
||||
try:
|
||||
return win32service.OpenService(hscm, name, access)
|
||||
except win32api.error as details:
|
||||
if details.winerror not in [winerror.ERROR_SERVICE_DOES_NOT_EXIST,
|
||||
winerror.ERROR_INVALID_NAME]:
|
||||
raise
|
||||
name = win32service.GetServiceKeyName(hscm, name)
|
||||
return win32service.OpenService(hscm, name, access)
|
||||
|
||||
def LocateSpecificServiceExe(serviceName):
|
||||
# Given the name of a specific service, return the .EXE name _it_ uses
|
||||
# (which may or may not be the Python Service EXE
|
||||
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS)
|
||||
try:
|
||||
return win32api.RegQueryValueEx(hkey, "ImagePath")[0]
|
||||
finally:
|
||||
hkey.Close()
|
||||
|
||||
def InstallPerfmonForService(serviceName, iniName, dllName = None):
|
||||
# If no DLL name, look it up in the INI file name
|
||||
if not dllName: # May be empty string!
|
||||
dllName = win32api.GetProfileVal("Python", "dll", "", iniName)
|
||||
# Still not found - look for the standard one in the same dir as win32service.pyd
|
||||
if not dllName:
|
||||
try:
|
||||
tryName = os.path.join(os.path.split(win32service.__file__)[0], "perfmondata.dll")
|
||||
if os.path.isfile(tryName):
|
||||
dllName = tryName
|
||||
except AttributeError:
|
||||
# Frozen app? - anyway, can't find it!
|
||||
pass
|
||||
if not dllName:
|
||||
raise ValueError("The name of the performance DLL must be available")
|
||||
dllName = win32api.GetFullPathName(dllName)
|
||||
# Now setup all the required "Performance" entries.
|
||||
hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\%s" % (serviceName), 0, win32con.KEY_ALL_ACCESS)
|
||||
try:
|
||||
subKey = win32api.RegCreateKey(hkey, "Performance")
|
||||
try:
|
||||
win32api.RegSetValueEx(subKey, "Library", 0, win32con.REG_SZ, dllName)
|
||||
win32api.RegSetValueEx(subKey, "Open", 0, win32con.REG_SZ, "OpenPerformanceData")
|
||||
win32api.RegSetValueEx(subKey, "Close", 0, win32con.REG_SZ, "ClosePerformanceData")
|
||||
win32api.RegSetValueEx(subKey, "Collect", 0, win32con.REG_SZ, "CollectPerformanceData")
|
||||
finally:
|
||||
win32api.RegCloseKey(subKey)
|
||||
finally:
|
||||
win32api.RegCloseKey(hkey)
|
||||
# Now do the "Lodctr" thang...
|
||||
|
||||
try:
|
||||
import perfmon
|
||||
path, fname = os.path.split(iniName)
|
||||
oldPath = os.getcwd()
|
||||
if path:
|
||||
os.chdir(path)
|
||||
try:
|
||||
perfmon.LoadPerfCounterTextStrings("python.exe " + fname)
|
||||
finally:
|
||||
os.chdir(oldPath)
|
||||
except win32api.error as details:
|
||||
print("The service was installed OK, but the performance monitor")
|
||||
print("data could not be loaded.", details)
|
||||
|
||||
def _GetCommandLine(exeName, exeArgs):
|
||||
if exeArgs is not None:
|
||||
return exeName + " " + exeArgs
|
||||
else:
|
||||
return exeName
|
||||
|
||||
def InstallService(pythonClassString, serviceName, displayName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, perfMonIni = None, perfMonDll = None, exeArgs = None,
|
||||
description = None, delayedstart = None):
|
||||
# Handle the default arguments.
|
||||
if startType is None:
|
||||
startType = win32service.SERVICE_DEMAND_START
|
||||
serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
|
||||
if bRunInteractive:
|
||||
serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
|
||||
if errorControl is None:
|
||||
errorControl = win32service.SERVICE_ERROR_NORMAL
|
||||
|
||||
exeName = '"%s"' % LocatePythonServiceExe(exeName) # None here means use default PythonService.exe
|
||||
commandLine = _GetCommandLine(exeName, exeArgs)
|
||||
hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
hs = win32service.CreateService(hscm,
|
||||
serviceName,
|
||||
displayName,
|
||||
win32service.SERVICE_ALL_ACCESS, # desired access
|
||||
serviceType, # service type
|
||||
startType,
|
||||
errorControl, # error control type
|
||||
commandLine,
|
||||
None,
|
||||
0,
|
||||
serviceDeps,
|
||||
userName,
|
||||
password)
|
||||
if description is not None:
|
||||
try:
|
||||
win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
|
||||
except NotImplementedError:
|
||||
pass ## ChangeServiceConfig2 and description do not exist on NT
|
||||
if delayedstart is not None:
|
||||
try:
|
||||
win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart)
|
||||
except (win32service.error, NotImplementedError):
|
||||
## delayed start only exists on Vista and later - warn only when trying to set delayed to True
|
||||
if delayedstart:
|
||||
warnings.warn('Delayed Start not available on this system')
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
InstallPythonClassString(pythonClassString, serviceName)
|
||||
# If I have performance monitor info to install, do that.
|
||||
if perfMonIni is not None:
|
||||
InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
|
||||
|
||||
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0,
|
||||
serviceDeps = None, userName = None, password = None,
|
||||
exeName = None, displayName = None, perfMonIni = None, perfMonDll = None,
|
||||
exeArgs = None, description = None, delayedstart = None):
|
||||
# Before doing anything, remove any perfmon counters.
|
||||
try:
|
||||
import perfmon
|
||||
perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
|
||||
except (ImportError, win32api.error):
|
||||
pass
|
||||
|
||||
# The EXE location may have changed
|
||||
exeName = '"%s"' % LocatePythonServiceExe(exeName)
|
||||
|
||||
# Handle the default arguments.
|
||||
if startType is None: startType = win32service.SERVICE_NO_CHANGE
|
||||
if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE
|
||||
|
||||
hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
|
||||
if bRunInteractive:
|
||||
serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
|
||||
commandLine = _GetCommandLine(exeName, exeArgs)
|
||||
try:
|
||||
hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
|
||||
try:
|
||||
|
||||
win32service.ChangeServiceConfig(hs,
|
||||
serviceType, # service type
|
||||
startType,
|
||||
errorControl, # error control type
|
||||
commandLine,
|
||||
None,
|
||||
0,
|
||||
serviceDeps,
|
||||
userName,
|
||||
password,
|
||||
displayName)
|
||||
if description is not None:
|
||||
try:
|
||||
win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
|
||||
except NotImplementedError:
|
||||
pass ## ChangeServiceConfig2 and description do not exist on NT
|
||||
if delayedstart is not None:
|
||||
try:
|
||||
win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayedstart)
|
||||
except (win32service.error, NotImplementedError):
|
||||
## Delayed start only exists on Vista and later. On Nt, will raise NotImplementedError since ChangeServiceConfig2
|
||||
## doensn't exist. On Win2k and XP, will fail with ERROR_INVALID_LEVEL
|
||||
## Warn only if trying to set delayed to True
|
||||
if delayedstart:
|
||||
warnings.warn('Delayed Start not available on this system')
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
InstallPythonClassString(pythonClassString, serviceName)
|
||||
# If I have performance monitor info to install, do that.
|
||||
if perfMonIni is not None:
|
||||
InstallPerfmonForService(serviceName, perfMonIni, perfMonDll)
|
||||
|
||||
def InstallPythonClassString(pythonClassString, serviceName):
|
||||
# Now setup our Python specific entries.
|
||||
if pythonClassString:
|
||||
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\PythonClass" % serviceName)
|
||||
try:
|
||||
win32api.RegSetValue(key, None, win32con.REG_SZ, pythonClassString);
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
# Utility functions for Services, to allow persistant properties.
|
||||
def SetServiceCustomOption(serviceName, option, value):
|
||||
try:
|
||||
serviceName = serviceName._svc_name_
|
||||
except AttributeError:
|
||||
pass
|
||||
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
|
||||
try:
|
||||
if type(value)==type(0):
|
||||
win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value);
|
||||
else:
|
||||
win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value);
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
def GetServiceCustomOption(serviceName, option, defaultValue = None):
|
||||
# First param may also be a service class/instance.
|
||||
# This allows services to pass "self"
|
||||
try:
|
||||
serviceName = serviceName._svc_name_
|
||||
except AttributeError:
|
||||
pass
|
||||
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
|
||||
try:
|
||||
try:
|
||||
return win32api.RegQueryValueEx(key, option)[0]
|
||||
except win32api.error: # No value.
|
||||
return defaultValue
|
||||
finally:
|
||||
win32api.RegCloseKey(key)
|
||||
|
||||
|
||||
def RemoveService(serviceName):
|
||||
try:
|
||||
import perfmon
|
||||
perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
|
||||
except (ImportError, win32api.error):
|
||||
pass
|
||||
|
||||
hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
|
||||
win32service.DeleteService(hs)
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
|
||||
import win32evtlogutil
|
||||
try:
|
||||
win32evtlogutil.RemoveSourceFromRegistry(serviceName)
|
||||
except win32api.error:
|
||||
pass
|
||||
|
||||
def ControlService(serviceName, code, machine = None):
|
||||
hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
|
||||
hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
|
||||
try:
|
||||
status = win32service.ControlService(hs, code)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
return status
|
||||
|
||||
def __FindSvcDeps(findName):
|
||||
if type(findName) is pywintypes.UnicodeType: findName = str(findName)
|
||||
dict = {}
|
||||
k = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services")
|
||||
num = 0
|
||||
while 1:
|
||||
try:
|
||||
svc = win32api.RegEnumKey(k, num)
|
||||
except win32api.error:
|
||||
break
|
||||
num = num + 1
|
||||
sk = win32api.RegOpenKey(k, svc)
|
||||
try:
|
||||
deps, typ = win32api.RegQueryValueEx(sk, "DependOnService")
|
||||
except win32api.error:
|
||||
deps = ()
|
||||
for dep in deps:
|
||||
dep = dep.lower()
|
||||
dep_on = dict.get(dep, [])
|
||||
dep_on.append(svc)
|
||||
dict[dep]=dep_on
|
||||
|
||||
return __ResolveDeps(findName, dict)
|
||||
|
||||
|
||||
def __ResolveDeps(findName, dict):
|
||||
items = dict.get(findName.lower(), [])
|
||||
retList = []
|
||||
for svc in items:
|
||||
retList.insert(0, svc)
|
||||
retList = __ResolveDeps(svc, dict) + retList
|
||||
return retList
|
||||
|
||||
def WaitForServiceStatus(serviceName, status, waitSecs, machine=None):
|
||||
"""Waits for the service to return the specified status. You
|
||||
should have already requested the service to enter that state"""
|
||||
for i in range(waitSecs*4):
|
||||
now_status = QueryServiceStatus(serviceName, machine)[1]
|
||||
if now_status == status:
|
||||
break
|
||||
win32api.Sleep(250)
|
||||
else:
|
||||
raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "QueryServiceStatus", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
|
||||
|
||||
def __StopServiceWithTimeout(hs, waitSecs = 30):
|
||||
try:
|
||||
status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP)
|
||||
except pywintypes.error as exc:
|
||||
if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE:
|
||||
raise
|
||||
for i in range(waitSecs):
|
||||
status = win32service.QueryServiceStatus(hs)
|
||||
if status[1] == win32service.SERVICE_STOPPED:
|
||||
break
|
||||
win32api.Sleep(1000)
|
||||
else:
|
||||
raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
|
||||
|
||||
|
||||
def StopServiceWithDeps(serviceName, machine = None, waitSecs = 30):
|
||||
# Stop a service recursively looking for dependant services
|
||||
hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
deps = __FindSvcDeps(serviceName)
|
||||
for dep in deps:
|
||||
hs = win32service.OpenService(hscm, dep, win32service.SERVICE_ALL_ACCESS)
|
||||
try:
|
||||
__StopServiceWithTimeout(hs, waitSecs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
# Now my service!
|
||||
hs = win32service.OpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
|
||||
try:
|
||||
__StopServiceWithTimeout(hs, waitSecs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
|
||||
|
||||
def StopService(serviceName, machine = None):
|
||||
return ControlService(serviceName, win32service.SERVICE_CONTROL_STOP, machine)
|
||||
|
||||
def StartService(serviceName, args = None, machine = None):
|
||||
hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
|
||||
hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
|
||||
try:
|
||||
win32service.StartService(hs, args)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
|
||||
def RestartService(serviceName, args = None, waitSeconds = 30, machine = None):
|
||||
"Stop the service, and then start it again (with some tolerance for allowing it to stop.)"
|
||||
try:
|
||||
StopService(serviceName, machine)
|
||||
except pywintypes.error as exc:
|
||||
# Allow only "service not running" error
|
||||
if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE:
|
||||
raise
|
||||
# Give it a few goes, as the service may take time to stop
|
||||
for i in range(waitSeconds):
|
||||
try:
|
||||
StartService(serviceName, args, machine)
|
||||
break
|
||||
except pywintypes.error as exc:
|
||||
if exc.winerror!=winerror.ERROR_SERVICE_ALREADY_RUNNING:
|
||||
raise
|
||||
win32api.Sleep(1000)
|
||||
else:
|
||||
print("Gave up waiting for the old service to stop!")
|
||||
|
||||
def _DebugCtrlHandler(evt):
|
||||
if evt in (win32con.CTRL_C_EVENT, win32con.CTRL_BREAK_EVENT):
|
||||
assert g_debugService
|
||||
print("Stopping debug service.")
|
||||
g_debugService.SvcStop()
|
||||
return True
|
||||
return False
|
||||
|
||||
def DebugService(cls, argv = []):
|
||||
# Run a service in "debug" mode. Re-implements what pythonservice.exe
|
||||
# does when it sees a "-debug" param.
|
||||
# Currently only used by "frozen" (ie, py2exe) programs (but later may
|
||||
# end up being used for all services should we ever remove
|
||||
# pythonservice.exe)
|
||||
import servicemanager
|
||||
global g_debugService
|
||||
|
||||
print("Debugging service %s - press Ctrl+C to stop." % (cls._svc_name_,))
|
||||
servicemanager.Debugging(True)
|
||||
servicemanager.PrepareToHostSingle(cls)
|
||||
g_debugService = cls(argv)
|
||||
# Setup a ctrl+c handler to simulate a "stop"
|
||||
win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, True)
|
||||
try:
|
||||
g_debugService.SvcRun()
|
||||
finally:
|
||||
win32api.SetConsoleCtrlHandler(_DebugCtrlHandler, False)
|
||||
servicemanager.Debugging(False)
|
||||
g_debugService = None
|
||||
|
||||
def GetServiceClassString(cls, argv = None):
|
||||
if argv is None:
|
||||
argv = sys.argv
|
||||
import pickle
|
||||
modName = pickle.whichmodule(cls, cls.__name__)
|
||||
if modName == '__main__':
|
||||
try:
|
||||
fname = win32api.GetFullPathName(argv[0])
|
||||
path = os.path.split(fname)[0]
|
||||
# Eaaaahhhh - sometimes this will be a short filename, which causes
|
||||
# problems with 1.5.1 and the silly filename case rule.
|
||||
# Get the long name
|
||||
fname = os.path.join(path, win32api.FindFiles(fname)[0][8])
|
||||
except win32api.error:
|
||||
raise error("Could not resolve the path name '%s' to a full path" % (argv[0]))
|
||||
modName = os.path.splitext(fname)[0]
|
||||
return modName + "." + cls.__name__
|
||||
|
||||
def QueryServiceStatus(serviceName, machine=None):
|
||||
hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_CONNECT)
|
||||
try:
|
||||
|
||||
hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_QUERY_STATUS)
|
||||
try:
|
||||
status = win32service.QueryServiceStatus(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hs)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(hscm)
|
||||
return status
|
||||
|
||||
def usage():
|
||||
try:
|
||||
fname = os.path.split(sys.argv[0])[1]
|
||||
except:
|
||||
fname = sys.argv[0]
|
||||
print("Usage: '%s [options] install|update|remove|start [...]|stop|restart [...]|debug [...]'" % fname)
|
||||
print("Options for 'install' and 'update' commands only:")
|
||||
print(" --username domain\\username : The Username the service is to run under")
|
||||
print(" --password password : The password for the username")
|
||||
print(" --startup [manual|auto|disabled|delayed] : How the service starts, default = manual")
|
||||
print(" --interactive : Allow the service to interact with the desktop.")
|
||||
print(" --perfmonini file: .ini file to use for registering performance monitor data")
|
||||
print(" --perfmondll file: .dll file to use when querying the service for")
|
||||
print(" performance data, default = perfmondata.dll")
|
||||
print("Options for 'start' and 'stop' commands only:")
|
||||
print(" --wait seconds: Wait for the service to actually start or stop.")
|
||||
print(" If you specify --wait with the 'stop' option, the service")
|
||||
print(" and all dependent services will be stopped, each waiting")
|
||||
print(" the specified period.")
|
||||
sys.exit(1)
|
||||
|
||||
def HandleCommandLine(cls, serviceClassString = None, argv = None, customInstallOptions = "", customOptionHandler = None):
|
||||
"""Utility function allowing services to process the command line.
|
||||
|
||||
Allows standard commands such as 'start', 'stop', 'debug', 'install' etc.
|
||||
|
||||
Install supports 'standard' command line options prefixed with '--', such as
|
||||
--username, --password, etc. In addition,
|
||||
the function allows custom command line options to be handled by the calling function.
|
||||
"""
|
||||
err = 0
|
||||
|
||||
if argv is None: argv = sys.argv
|
||||
|
||||
if len(argv)<=1:
|
||||
usage()
|
||||
|
||||
serviceName = cls._svc_name_
|
||||
serviceDisplayName = cls._svc_display_name_
|
||||
if serviceClassString is None:
|
||||
serviceClassString = GetServiceClassString(cls)
|
||||
|
||||
# Pull apart the command line
|
||||
import getopt
|
||||
try:
|
||||
opts, args = getopt.getopt(argv[1:], customInstallOptions,["password=","username=","startup=","perfmonini=", "perfmondll=", "interactive", "wait="])
|
||||
except getopt.error as details:
|
||||
print(details)
|
||||
usage()
|
||||
userName = None
|
||||
password = None
|
||||
perfMonIni = perfMonDll = None
|
||||
startup = None
|
||||
delayedstart = None
|
||||
interactive = None
|
||||
waitSecs = 0
|
||||
for opt, val in opts:
|
||||
if opt=='--username':
|
||||
userName = val
|
||||
elif opt=='--password':
|
||||
password = val
|
||||
elif opt=='--perfmonini':
|
||||
perfMonIni = val
|
||||
elif opt=='--perfmondll':
|
||||
perfMonDll = val
|
||||
elif opt=='--interactive':
|
||||
interactive = 1
|
||||
elif opt=='--startup':
|
||||
map = {"manual": win32service.SERVICE_DEMAND_START,
|
||||
"auto" : win32service.SERVICE_AUTO_START,
|
||||
"delayed": win32service.SERVICE_AUTO_START, ## ChangeServiceConfig2 called later
|
||||
"disabled": win32service.SERVICE_DISABLED}
|
||||
try:
|
||||
startup = map[val.lower()]
|
||||
except KeyError:
|
||||
print("'%s' is not a valid startup option" % val)
|
||||
if val.lower() == "delayed":
|
||||
delayedstart = True
|
||||
elif val.lower() == "auto":
|
||||
delayedstart = False
|
||||
## else no change
|
||||
elif opt=='--wait':
|
||||
try:
|
||||
waitSecs = int(val)
|
||||
except ValueError:
|
||||
print("--wait must specify an integer number of seconds.")
|
||||
usage()
|
||||
|
||||
arg=args[0]
|
||||
knownArg = 0
|
||||
# First we process all arguments which pass additional args on
|
||||
if arg=="start":
|
||||
knownArg = 1
|
||||
print("Starting service %s" % (serviceName))
|
||||
try:
|
||||
StartService(serviceName, args[1:])
|
||||
if waitSecs:
|
||||
WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
|
||||
except win32service.error as exc:
|
||||
print("Error starting service: %s" % exc.strerror)
|
||||
err = exc.winerror
|
||||
|
||||
elif arg=="restart":
|
||||
knownArg = 1
|
||||
print("Restarting service %s" % (serviceName))
|
||||
RestartService(serviceName, args[1:])
|
||||
if waitSecs:
|
||||
WaitForServiceStatus(serviceName, win32service.SERVICE_RUNNING, waitSecs)
|
||||
|
||||
elif arg=="debug":
|
||||
knownArg = 1
|
||||
if not hasattr(sys, "frozen"):
|
||||
# non-frozen services use pythonservice.exe which handles a
|
||||
# -debug option
|
||||
svcArgs = " ".join(args[1:])
|
||||
try:
|
||||
exeName = LocateSpecificServiceExe(serviceName)
|
||||
except win32api.error as exc:
|
||||
if exc[0] == winerror.ERROR_FILE_NOT_FOUND:
|
||||
print("The service does not appear to be installed.")
|
||||
print("Please install the service before debugging it.")
|
||||
sys.exit(1)
|
||||
raise
|
||||
try:
|
||||
os.system("%s -debug %s %s" % (exeName, serviceName, svcArgs))
|
||||
# ^C is used to kill the debug service. Sometimes Python also gets
|
||||
# interrupted - ignore it...
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
else:
|
||||
# py2exe services don't use pythonservice - so we simulate
|
||||
# debugging here.
|
||||
DebugService(cls, args)
|
||||
|
||||
if not knownArg and len(args)!=1:
|
||||
usage() # the rest of the cmds don't take addn args
|
||||
|
||||
if arg=="install":
|
||||
knownArg = 1
|
||||
try:
|
||||
serviceDeps = cls._svc_deps_
|
||||
except AttributeError:
|
||||
serviceDeps = None
|
||||
try:
|
||||
exeName = cls._exe_name_
|
||||
except AttributeError:
|
||||
exeName = None # Default to PythonService.exe
|
||||
try:
|
||||
exeArgs = cls._exe_args_
|
||||
except AttributeError:
|
||||
exeArgs = None
|
||||
try:
|
||||
description = cls._svc_description_
|
||||
except AttributeError:
|
||||
description = None
|
||||
print("Installing service %s" % (serviceName,))
|
||||
# Note that we install the service before calling the custom option
|
||||
# handler, so if the custom handler fails, we have an installed service (from NT's POV)
|
||||
# but is unlikely to work, as the Python code controlling it failed. Therefore
|
||||
# we remove the service if the first bit works, but the second doesnt!
|
||||
try:
|
||||
InstallService(serviceClassString, serviceName, serviceDisplayName, serviceDeps = serviceDeps, startType=startup, bRunInteractive=interactive, userName=userName,password=password, exeName=exeName, perfMonIni=perfMonIni,perfMonDll=perfMonDll,exeArgs=exeArgs,
|
||||
description=description, delayedstart=delayedstart)
|
||||
if customOptionHandler:
|
||||
customOptionHandler(*(opts,))
|
||||
print("Service installed")
|
||||
except win32service.error as exc:
|
||||
if exc.winerror==winerror.ERROR_SERVICE_EXISTS:
|
||||
arg = "update" # Fall through to the "update" param!
|
||||
else:
|
||||
print("Error installing service: %s (%d)" % (exc.strerror, exc.winerror))
|
||||
err = exc.winerror
|
||||
except ValueError as msg: # Can be raised by custom option handler.
|
||||
print("Error installing service: %s" % str(msg))
|
||||
err = -1
|
||||
# xxx - maybe I should remove after _any_ failed install - however,
|
||||
# xxx - it may be useful to help debug to leave the service as it failed.
|
||||
# xxx - We really _must_ remove as per the comments above...
|
||||
# As we failed here, remove the service, so the next installation
|
||||
# attempt works.
|
||||
try:
|
||||
RemoveService(serviceName)
|
||||
except win32api.error:
|
||||
print("Warning - could not remove the partially installed service.")
|
||||
|
||||
if arg == "update":
|
||||
knownArg = 1
|
||||
try:
|
||||
serviceDeps = cls._svc_deps_
|
||||
except AttributeError:
|
||||
serviceDeps = None
|
||||
try:
|
||||
exeName = cls._exe_name_
|
||||
except AttributeError:
|
||||
exeName = None # Default to PythonService.exe
|
||||
try:
|
||||
exeArgs = cls._exe_args_
|
||||
except AttributeError:
|
||||
exeArgs = None
|
||||
try:
|
||||
description=cls._svc_description_
|
||||
except AttributeError:
|
||||
description=None
|
||||
print("Changing service configuration")
|
||||
try:
|
||||
ChangeServiceConfig(serviceClassString, serviceName, serviceDeps = serviceDeps, startType=startup, bRunInteractive=interactive, userName=userName,password=password, exeName=exeName, displayName = serviceDisplayName, perfMonIni=perfMonIni,perfMonDll=perfMonDll,exeArgs=exeArgs,
|
||||
description=description, delayedstart=delayedstart)
|
||||
if customOptionHandler:
|
||||
customOptionHandler(*(opts,))
|
||||
print("Service updated")
|
||||
except win32service.error as exc:
|
||||
print("Error changing service configuration: %s (%d)" % (exc.strerror,exc.winerror))
|
||||
err = exc.winerror
|
||||
|
||||
elif arg=="remove":
|
||||
knownArg = 1
|
||||
print("Removing service %s" % (serviceName))
|
||||
try:
|
||||
RemoveService(serviceName)
|
||||
print("Service removed")
|
||||
except win32service.error as exc:
|
||||
print("Error removing service: %s (%d)" % (exc.strerror,exc.winerror))
|
||||
err = exc.winerror
|
||||
elif arg=="stop":
|
||||
knownArg = 1
|
||||
print("Stopping service %s" % (serviceName))
|
||||
try:
|
||||
if waitSecs:
|
||||
StopServiceWithDeps(serviceName, waitSecs = waitSecs)
|
||||
else:
|
||||
StopService(serviceName)
|
||||
except win32service.error as exc:
|
||||
print("Error stopping service: %s (%d)" % (exc.strerror,exc.winerror))
|
||||
err = exc.winerror
|
||||
if not knownArg:
|
||||
err = -1
|
||||
print("Unknown command - '%s'" % arg)
|
||||
usage()
|
||||
return err
|
||||
|
||||
#
|
||||
# Useful base class to build services from.
|
||||
#
|
||||
class ServiceFramework:
|
||||
# Required Attributes:
|
||||
# _svc_name_ = The service name
|
||||
# _svc_display_name_ = The service display name
|
||||
|
||||
# Optional Attributes:
|
||||
_svc_deps_ = None # sequence of service names on which this depends
|
||||
_exe_name_ = None # Default to PythonService.exe
|
||||
_exe_args_ = None # Default to no arguments
|
||||
_svc_description_ = None # Only exists on Windows 2000 or later, ignored on windows NT
|
||||
|
||||
def __init__(self, args):
|
||||
import servicemanager
|
||||
self.ssh = servicemanager.RegisterServiceCtrlHandler(args[0], self.ServiceCtrlHandlerEx, True)
|
||||
servicemanager.SetEventSourceName(self._svc_name_)
|
||||
self.checkPoint = 0
|
||||
|
||||
def GetAcceptedControls(self):
|
||||
# Setup the service controls we accept based on our attributes. Note
|
||||
# that if you need to handle controls via SvcOther[Ex](), you must
|
||||
# override this.
|
||||
accepted = 0
|
||||
if hasattr(self, "SvcStop"): accepted = accepted | win32service.SERVICE_ACCEPT_STOP
|
||||
if hasattr(self, "SvcPause") and hasattr(self, "SvcContinue"):
|
||||
accepted = accepted | win32service.SERVICE_ACCEPT_PAUSE_CONTINUE
|
||||
if hasattr(self, "SvcShutdown"): accepted = accepted | win32service.SERVICE_ACCEPT_SHUTDOWN
|
||||
return accepted
|
||||
|
||||
def ReportServiceStatus(self, serviceStatus, waitHint = 5000, win32ExitCode = 0, svcExitCode = 0):
|
||||
if self.ssh is None: # Debugging!
|
||||
return
|
||||
if serviceStatus == win32service.SERVICE_START_PENDING:
|
||||
accepted = 0
|
||||
else:
|
||||
accepted = self.GetAcceptedControls()
|
||||
|
||||
if serviceStatus in [win32service.SERVICE_RUNNING, win32service.SERVICE_STOPPED]:
|
||||
checkPoint = 0
|
||||
else:
|
||||
self.checkPoint = self.checkPoint + 1
|
||||
checkPoint = self.checkPoint
|
||||
|
||||
# Now report the status to the control manager
|
||||
status = (win32service.SERVICE_WIN32_OWN_PROCESS,
|
||||
serviceStatus,
|
||||
accepted, # dwControlsAccepted,
|
||||
win32ExitCode, # dwWin32ExitCode;
|
||||
svcExitCode, # dwServiceSpecificExitCode;
|
||||
checkPoint, # dwCheckPoint;
|
||||
waitHint)
|
||||
win32service.SetServiceStatus( self.ssh, status)
|
||||
|
||||
def SvcInterrogate(self):
|
||||
# Assume we are running, and everyone is happy.
|
||||
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
|
||||
|
||||
def SvcOther(self, control):
|
||||
try:
|
||||
print("Unknown control status - %d" % control)
|
||||
except IOError:
|
||||
# services may not have a valid stdout!
|
||||
pass
|
||||
|
||||
def ServiceCtrlHandler(self, control):
|
||||
return self.ServiceCtrlHandlerEx(control, 0, None)
|
||||
|
||||
# The 'Ex' functions, which take additional params
|
||||
def SvcOtherEx(self, control, event_type, data):
|
||||
# The default here is to call self.SvcOther as that is the old behaviour.
|
||||
# If you want to take advantage of the extra data, override this method
|
||||
return self.SvcOther(control)
|
||||
|
||||
def ServiceCtrlHandlerEx(self, control, event_type, data):
|
||||
if control==win32service.SERVICE_CONTROL_STOP:
|
||||
return self.SvcStop()
|
||||
elif control==win32service.SERVICE_CONTROL_PAUSE:
|
||||
return self.SvcPause()
|
||||
elif control==win32service.SERVICE_CONTROL_CONTINUE:
|
||||
return self.SvcContinue()
|
||||
elif control==win32service.SERVICE_CONTROL_INTERROGATE:
|
||||
return self.SvcInterrogate()
|
||||
elif control==win32service.SERVICE_CONTROL_SHUTDOWN:
|
||||
return self.SvcShutdown()
|
||||
else:
|
||||
return self.SvcOtherEx(control, event_type, data)
|
||||
|
||||
def SvcRun(self):
|
||||
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
|
||||
self.SvcDoRun()
|
||||
# Once SvcDoRun terminates, the service has stopped.
|
||||
# We tell the SCM the service is still stopping - the C framework
|
||||
# will automatically tell the SCM it has stopped when this returns.
|
||||
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
|
||||
975
Pywin32/lib/x32/win32/lib/win32timezone.py
Normal file
@@ -0,0 +1,975 @@
|
||||
# -*- coding: UTF-8 -*-
|
||||
|
||||
"""
|
||||
win32timezone:
|
||||
Module for handling datetime.tzinfo time zones using the windows
|
||||
registry for time zone information. The time zone names are dependent
|
||||
on the registry entries defined by the operating system.
|
||||
|
||||
This module may be tested using the doctest module.
|
||||
|
||||
Written by Jason R. Coombs (jaraco@jaraco.com).
|
||||
Copyright © 2003-2012.
|
||||
All Rights Reserved.
|
||||
|
||||
This module is licenced for use in Mark Hammond's pywin32
|
||||
library under the same terms as the pywin32 library.
|
||||
|
||||
To use this time zone module with the datetime module, simply pass
|
||||
the TimeZoneInfo object to the datetime constructor. For example,
|
||||
|
||||
>>> import win32timezone, datetime
|
||||
>>> assert 'Mountain Standard Time' in win32timezone.TimeZoneInfo.get_sorted_time_zone_names()
|
||||
>>> MST = win32timezone.TimeZoneInfo('Mountain Standard Time')
|
||||
>>> now = datetime.datetime.now(MST)
|
||||
|
||||
The now object is now a time-zone aware object, and daylight savings-
|
||||
aware methods may be called on it.
|
||||
|
||||
>>> now.utcoffset() in (datetime.timedelta(-1, 61200), datetime.timedelta(-1, 64800))
|
||||
True
|
||||
|
||||
(note that the result of utcoffset call will be different based on when now was
|
||||
generated, unless standard time is always used)
|
||||
|
||||
>>> now = datetime.datetime.now(TimeZoneInfo('Mountain Standard Time', True))
|
||||
>>> now.utcoffset()
|
||||
datetime.timedelta(-1, 61200)
|
||||
|
||||
>>> aug2 = datetime.datetime(2003, 8, 2, tzinfo = MST)
|
||||
>>> tuple(aug2.utctimetuple())
|
||||
(2003, 8, 2, 6, 0, 0, 5, 214, 0)
|
||||
>>> nov2 = datetime.datetime(2003, 11, 25, tzinfo = MST)
|
||||
>>> tuple(nov2.utctimetuple())
|
||||
(2003, 11, 25, 7, 0, 0, 1, 329, 0)
|
||||
|
||||
To convert from one timezone to another, just use the astimezone method.
|
||||
|
||||
>>> aug2.isoformat()
|
||||
'2003-08-02T00:00:00-06:00'
|
||||
>>> aug2est = aug2.astimezone(win32timezone.TimeZoneInfo('Eastern Standard Time'))
|
||||
>>> aug2est.isoformat()
|
||||
'2003-08-02T02:00:00-04:00'
|
||||
|
||||
calling the displayName member will return the display name as set in the
|
||||
registry.
|
||||
|
||||
>>> est = win32timezone.TimeZoneInfo('Eastern Standard Time')
|
||||
>>> str(est.displayName)
|
||||
'(UTC-05:00) Eastern Time (US & Canada)'
|
||||
|
||||
>>> gmt = win32timezone.TimeZoneInfo('GMT Standard Time', True)
|
||||
>>> str(gmt.displayName)
|
||||
'(UTC) Dublin, Edinburgh, Lisbon, London'
|
||||
|
||||
To get the complete list of available time zone keys,
|
||||
>>> zones = win32timezone.TimeZoneInfo.get_all_time_zones()
|
||||
|
||||
If you want to get them in an order that's sorted longitudinally
|
||||
>>> zones = win32timezone.TimeZoneInfo.get_sorted_time_zones()
|
||||
|
||||
TimeZoneInfo now supports being pickled and comparison
|
||||
>>> import pickle
|
||||
>>> tz = win32timezone.TimeZoneInfo('China Standard Time')
|
||||
>>> tz == pickle.loads(pickle.dumps(tz))
|
||||
True
|
||||
|
||||
It's possible to construct a TimeZoneInfo from a TimeZoneDescription
|
||||
including the currently-defined zone.
|
||||
>>> tz = win32timezone.TimeZoneInfo(TimeZoneDefinition.current())
|
||||
>>> tz == pickle.loads(pickle.dumps(tz))
|
||||
True
|
||||
|
||||
>>> aest = win32timezone.TimeZoneInfo('AUS Eastern Standard Time')
|
||||
>>> est = win32timezone.TimeZoneInfo('E. Australia Standard Time')
|
||||
>>> dt = datetime.datetime(2006, 11, 11, 1, 0, 0, tzinfo = aest)
|
||||
>>> estdt = dt.astimezone(est)
|
||||
>>> estdt.strftime('%Y-%m-%d %H:%M:%S')
|
||||
'2006-11-11 00:00:00'
|
||||
|
||||
>>> dt = datetime.datetime(2007, 1, 12, 1, 0, 0, tzinfo = aest)
|
||||
>>> estdt = dt.astimezone(est)
|
||||
>>> estdt.strftime('%Y-%m-%d %H:%M:%S')
|
||||
'2007-01-12 00:00:00'
|
||||
|
||||
>>> dt = datetime.datetime(2007, 6, 13, 1, 0, 0, tzinfo = aest)
|
||||
>>> estdt = dt.astimezone(est)
|
||||
>>> estdt.strftime('%Y-%m-%d %H:%M:%S')
|
||||
'2007-06-13 01:00:00'
|
||||
|
||||
Microsoft now has a patch for handling time zones in 2007 (see
|
||||
http://support.microsoft.com/gp/cp_dst)
|
||||
|
||||
As a result, patched systems will give an incorrect result for
|
||||
dates prior to the designated year except for Vista and its
|
||||
successors, which have dynamic time zone support.
|
||||
>>> nov2_pre_change = datetime.datetime(2003, 11, 2, tzinfo = MST)
|
||||
>>> old_response = (2003, 11, 2, 7, 0, 0, 6, 306, 0)
|
||||
>>> incorrect_patch_response = (2003, 11, 2, 6, 0, 0, 6, 306, 0)
|
||||
>>> pre_response = nov2_pre_change.utctimetuple()
|
||||
>>> pre_response in (old_response, incorrect_patch_response)
|
||||
True
|
||||
|
||||
Furthermore, unpatched systems pre-Vista will give an incorrect
|
||||
result for dates after 2007.
|
||||
>>> nov2_post_change = datetime.datetime(2007, 11, 2, tzinfo = MST)
|
||||
>>> incorrect_unpatched_response = (2007, 11, 2, 7, 0, 0, 4, 306, 0)
|
||||
>>> new_response = (2007, 11, 2, 6, 0, 0, 4, 306, 0)
|
||||
>>> post_response = nov2_post_change.utctimetuple()
|
||||
>>> post_response in (new_response, incorrect_unpatched_response)
|
||||
True
|
||||
|
||||
|
||||
There is a function you can call to get some capabilities of the time
|
||||
zone data.
|
||||
>>> caps = GetTZCapabilities()
|
||||
>>> isinstance(caps, dict)
|
||||
True
|
||||
>>> 'MissingTZPatch' in caps
|
||||
True
|
||||
>>> 'DynamicTZSupport' in caps
|
||||
True
|
||||
|
||||
>>> both_dates_correct = (pre_response == old_response and post_response == new_response)
|
||||
>>> old_dates_wrong = (pre_response == incorrect_patch_response)
|
||||
>>> new_dates_wrong = (post_response == incorrect_unpatched_response)
|
||||
|
||||
>>> caps['DynamicTZSupport'] == both_dates_correct
|
||||
True
|
||||
|
||||
>>> (not caps['DynamicTZSupport'] and caps['MissingTZPatch']) == new_dates_wrong
|
||||
True
|
||||
|
||||
>>> (not caps['DynamicTZSupport'] and not caps['MissingTZPatch']) == old_dates_wrong
|
||||
True
|
||||
|
||||
This test helps ensure language support for unicode characters
|
||||
>>> x = TIME_ZONE_INFORMATION(0, u'français')
|
||||
|
||||
|
||||
Test conversion from one time zone to another at a DST boundary
|
||||
===============================================================
|
||||
|
||||
>>> tz_hi = TimeZoneInfo('Hawaiian Standard Time')
|
||||
>>> tz_pac = TimeZoneInfo('Pacific Standard Time')
|
||||
>>> time_before = datetime.datetime(2011, 11, 5, 15, 59, 59, tzinfo=tz_hi)
|
||||
>>> tz_hi.utcoffset(time_before)
|
||||
datetime.timedelta(-1, 50400)
|
||||
>>> tz_hi.dst(time_before)
|
||||
datetime.timedelta(0)
|
||||
|
||||
Hawaii doesn't need dynamic TZ info
|
||||
>>> getattr(tz_hi, 'dynamicInfo', None)
|
||||
|
||||
Here's a time that gave some trouble as reported in #3523104
|
||||
because one minute later, the equivalent UTC time changes from DST
|
||||
in the U.S.
|
||||
>>> dt_hi = datetime.datetime(2011, 11, 5, 15, 59, 59, 0, tzinfo=tz_hi)
|
||||
>>> dt_hi.timetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=15, tm_min=59, tm_sec=59, tm_wday=5, tm_yday=309, tm_isdst=0)
|
||||
>>> dt_hi.utctimetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=1, tm_min=59, tm_sec=59, tm_wday=6, tm_yday=310, tm_isdst=0)
|
||||
|
||||
Convert the time to pacific time.
|
||||
>>> dt_pac = dt_hi.astimezone(tz_pac)
|
||||
>>> dt_pac.timetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=18, tm_min=59, tm_sec=59, tm_wday=5, tm_yday=309, tm_isdst=1)
|
||||
|
||||
Notice that the UTC time is almost 2am.
|
||||
>>> dt_pac.utctimetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=1, tm_min=59, tm_sec=59, tm_wday=6, tm_yday=310, tm_isdst=0)
|
||||
|
||||
Now do the same tests one minute later in Hawaii.
|
||||
>>> time_after = datetime.datetime(2011, 11, 5, 16, 0, 0, 0, tzinfo=tz_hi)
|
||||
>>> tz_hi.utcoffset(time_after)
|
||||
datetime.timedelta(-1, 50400)
|
||||
>>> tz_hi.dst(time_before)
|
||||
datetime.timedelta(0)
|
||||
|
||||
>>> dt_hi = datetime.datetime(2011, 11, 5, 16, 0, 0, 0, tzinfo=tz_hi)
|
||||
>>> print dt_hi.timetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=16, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=309, tm_isdst=0)
|
||||
>>> print dt_hi.utctimetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
|
||||
|
||||
According to the docs, this is what astimezone does.
|
||||
>>> utc = (dt_hi - dt_hi.utcoffset()).replace(tzinfo=tz_pac)
|
||||
>>> utc
|
||||
datetime.datetime(2011, 11, 6, 2, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
|
||||
>>> tz_pac.fromutc(utc) == dt_hi.astimezone(tz_pac)
|
||||
True
|
||||
>>> tz_pac.fromutc(utc)
|
||||
datetime.datetime(2011, 11, 5, 19, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
|
||||
|
||||
Make sure the converted time is correct.
|
||||
>>> dt_pac = dt_hi.astimezone(tz_pac)
|
||||
>>> dt_pac.timetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=5, tm_hour=19, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=309, tm_isdst=1)
|
||||
>>> dt_pac.utctimetuple()
|
||||
time.struct_time(tm_year=2011, tm_mon=11, tm_mday=6, tm_hour=2, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=310, tm_isdst=0)
|
||||
|
||||
Check some internal methods
|
||||
>>> tz_pac._getStandardBias(datetime.datetime(2011, 1, 1))
|
||||
datetime.timedelta(0, 28800)
|
||||
>>> tz_pac._getDaylightBias(datetime.datetime(2011, 1, 1))
|
||||
datetime.timedelta(0, 25200)
|
||||
|
||||
Test the offsets
|
||||
>>> offset = tz_pac.utcoffset(datetime.datetime(2011, 11, 6, 2, 0))
|
||||
>>> offset == datetime.timedelta(hours=-8)
|
||||
True
|
||||
>>> dst_offset = tz_pac.dst(datetime.datetime(2011, 11, 6, 2, 0) + offset)
|
||||
>>> dst_offset == datetime.timedelta(hours=1)
|
||||
True
|
||||
>>> (offset + dst_offset) == datetime.timedelta(hours=-7)
|
||||
True
|
||||
|
||||
|
||||
Test offsets that occur right at the DST changeover
|
||||
>>> datetime.datetime.utcfromtimestamp(1320570000).replace(
|
||||
... tzinfo=TimeZoneInfo.utc()).astimezone(tz_pac)
|
||||
datetime.datetime(2011, 11, 6, 1, 0, tzinfo=TimeZoneInfo('Pacific Standard Time'))
|
||||
|
||||
"""
|
||||
from __future__ import generators
|
||||
|
||||
__author__ = 'Jason R. Coombs <jaraco@jaraco.com>'
|
||||
|
||||
import winreg
|
||||
import struct
|
||||
import datetime
|
||||
import win32api
|
||||
import re
|
||||
import operator
|
||||
import warnings
|
||||
from itertools import count
|
||||
|
||||
import logging
|
||||
log = logging.getLogger(__file__)
|
||||
|
||||
# A couple of objects for working with objects as if they were native C-type
|
||||
# structures.
|
||||
class _SimpleStruct(object):
|
||||
_fields_ = None # must be overridden by subclasses
|
||||
def __init__(self, *args, **kw):
|
||||
for i, (name, typ) in enumerate(self._fields_):
|
||||
def_arg = None
|
||||
if i < len(args):
|
||||
def_arg = args[i]
|
||||
if name in kw:
|
||||
def_arg = kw[name]
|
||||
if def_arg is not None:
|
||||
if not isinstance(def_arg, tuple):
|
||||
def_arg = (def_arg,)
|
||||
else:
|
||||
def_arg = ()
|
||||
if len(def_arg)==1 and isinstance(def_arg[0], typ):
|
||||
# already an object of this type.
|
||||
# XXX - should copy.copy???
|
||||
def_val = def_arg[0]
|
||||
else:
|
||||
def_val = typ(*def_arg)
|
||||
setattr(self, name, def_val)
|
||||
|
||||
def field_names(self):
|
||||
return [f[0] for f in self._fields_]
|
||||
|
||||
def __eq__(self, other):
|
||||
if not hasattr(other, "_fields_"):
|
||||
return False
|
||||
if self._fields_ != other._fields_:
|
||||
return False
|
||||
for name, _ in self._fields_:
|
||||
if getattr(self, name) != getattr(other, name):
|
||||
return False
|
||||
return True
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
|
||||
class SYSTEMTIME(_SimpleStruct):
|
||||
_fields_ = [
|
||||
('year', int),
|
||||
('month', int),
|
||||
('day_of_week', int),
|
||||
('day', int),
|
||||
('hour', int),
|
||||
('minute', int),
|
||||
('second', int),
|
||||
('millisecond', int),
|
||||
]
|
||||
|
||||
class TIME_ZONE_INFORMATION(_SimpleStruct):
|
||||
_fields_ = [
|
||||
('bias', int),
|
||||
('standard_name', str),
|
||||
('standard_start', SYSTEMTIME),
|
||||
('standard_bias', int),
|
||||
('daylight_name', str),
|
||||
('daylight_start', SYSTEMTIME),
|
||||
('daylight_bias', int),
|
||||
]
|
||||
|
||||
class DYNAMIC_TIME_ZONE_INFORMATION(_SimpleStruct):
|
||||
_fields_ = TIME_ZONE_INFORMATION._fields_ + [
|
||||
('key_name', str),
|
||||
('dynamic_daylight_time_disabled', bool),
|
||||
]
|
||||
|
||||
|
||||
class TimeZoneDefinition(DYNAMIC_TIME_ZONE_INFORMATION):
|
||||
"""
|
||||
A time zone definition class based on the win32
|
||||
DYNAMIC_TIME_ZONE_INFORMATION structure.
|
||||
|
||||
Describes a bias against UTC (bias), and two dates at which a separate
|
||||
additional bias applies (standard_bias and daylight_bias).
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""
|
||||
Try to construct a TimeZoneDefinition from
|
||||
a) [DYNAMIC_]TIME_ZONE_INFORMATION args
|
||||
b) another TimeZoneDefinition
|
||||
c) a byte structure (using _from_bytes)
|
||||
"""
|
||||
try:
|
||||
super(TimeZoneDefinition, self).__init__(*args, **kwargs)
|
||||
return
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
try:
|
||||
self.__init_from_other(*args, **kwargs)
|
||||
return
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
try:
|
||||
self.__init_from_bytes(*args, **kwargs)
|
||||
return
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
raise TypeError("Invalid arguments for %s" % self.__class__)
|
||||
|
||||
def __init_from_bytes(self, bytes, standard_name='', daylight_name='', key_name='', daylight_disabled=False):
|
||||
format = '3l8h8h'
|
||||
components = struct.unpack(format, bytes)
|
||||
bias, standard_bias, daylight_bias = components[:3]
|
||||
standard_start = SYSTEMTIME(*components[3:11])
|
||||
daylight_start = SYSTEMTIME(*components[11:19])
|
||||
super(TimeZoneDefinition, self).__init__(bias,
|
||||
standard_name, standard_start, standard_bias,
|
||||
daylight_name, daylight_start, daylight_bias,
|
||||
key_name, daylight_disabled,)
|
||||
|
||||
def __init_from_other(self, other):
|
||||
if not isinstance(other, TIME_ZONE_INFORMATION):
|
||||
raise TypeError("Not a TIME_ZONE_INFORMATION")
|
||||
for name in other.field_names():
|
||||
# explicitly get the value from the underlying structure
|
||||
value = super(TimeZoneDefinition, other).__getattribute__(other, name)
|
||||
setattr(self, name, value)
|
||||
# consider instead of the loop above just copying the memory directly
|
||||
#size = max(ctypes.sizeof(DYNAMIC_TIME_ZONE_INFO), ctypes.sizeof(other))
|
||||
#ctypes.memmove(ctypes.addressof(self), other, size)
|
||||
|
||||
def __getattribute__(self, attr):
|
||||
value = super(TimeZoneDefinition, self).__getattribute__(attr)
|
||||
if 'bias' in attr:
|
||||
make_minute_timedelta = lambda m: datetime.timedelta(minutes = m)
|
||||
value = make_minute_timedelta(value)
|
||||
return value
|
||||
|
||||
@classmethod
|
||||
def current(class_):
|
||||
"Windows Platform SDK GetTimeZoneInformation"
|
||||
code, tzi = win32api.GetTimeZoneInformation(True)
|
||||
return code, class_(*tzi)
|
||||
|
||||
def set(self):
|
||||
tzi = tuple(getattr(self, n) for n, t in self._fields_)
|
||||
win32api.SetTimeZoneInformation(tzi)
|
||||
|
||||
def copy(self):
|
||||
# XXX - this is no longer a copy!
|
||||
return self.__class__(self)
|
||||
|
||||
def locate_daylight_start(self, year):
|
||||
return self._locate_day(year, self.daylight_start)
|
||||
|
||||
def locate_standard_start(self, year):
|
||||
return self._locate_day(year, self.standard_start)
|
||||
|
||||
@staticmethod
|
||||
def _locate_day(year, cutoff):
|
||||
"""
|
||||
Takes a SYSTEMTIME object, such as retrieved from a TIME_ZONE_INFORMATION
|
||||
structure or call to GetTimeZoneInformation and interprets it based on the given
|
||||
year to identify the actual day.
|
||||
|
||||
This method is necessary because the SYSTEMTIME structure refers to a day by its
|
||||
day of the week and week of the month (e.g. 4th saturday in March).
|
||||
|
||||
>>> SATURDAY = 6
|
||||
>>> MARCH = 3
|
||||
>>> st = SYSTEMTIME(2000, MARCH, SATURDAY, 4, 0, 0, 0, 0)
|
||||
|
||||
# according to my calendar, the 4th Saturday in March in 2009 was the 28th
|
||||
>>> expected_date = datetime.datetime(2009, 3, 28)
|
||||
>>> TimeZoneDefinition._locate_day(2009, st) == expected_date
|
||||
True
|
||||
"""
|
||||
# MS stores Sunday as 0, Python datetime stores Monday as zero
|
||||
target_weekday = (cutoff.day_of_week + 6) % 7
|
||||
# For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day
|
||||
# is the week of the month
|
||||
week_of_month = cutoff.day
|
||||
# so the following is the first day of that week
|
||||
day = (week_of_month - 1) * 7 + 1
|
||||
result = datetime.datetime(year, cutoff.month, day,
|
||||
cutoff.hour, cutoff.minute, cutoff.second, cutoff.millisecond)
|
||||
# now the result is the correct week, but not necessarily the correct day of the week
|
||||
days_to_go = (target_weekday - result.weekday()) % 7
|
||||
result += datetime.timedelta(days_to_go)
|
||||
# if we selected a day in the month following the target month,
|
||||
# move back a week or two.
|
||||
# This is necessary because Microsoft defines the fifth week in a month
|
||||
# to be the last week in a month and adding the time delta might have
|
||||
# pushed the result into the next month.
|
||||
while result.month == cutoff.month + 1:
|
||||
result -= datetime.timedelta(weeks = 1)
|
||||
return result
|
||||
|
||||
class TimeZoneInfo(datetime.tzinfo):
|
||||
"""
|
||||
Main class for handling Windows time zones.
|
||||
Usage:
|
||||
TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>])
|
||||
|
||||
If <Fix Standard Time> evaluates to True, daylight savings time is
|
||||
calculated in the same way as standard time.
|
||||
|
||||
>>> tzi = TimeZoneInfo('Pacific Standard Time')
|
||||
>>> march31 = datetime.datetime(2000,3,31)
|
||||
|
||||
We know that time zone definitions haven't changed from 2007
|
||||
to 2012, so regardless of whether dynamic info is available,
|
||||
there should be consistent results for these years.
|
||||
>>> subsequent_years = [march31.replace(year=year)
|
||||
... for year in range(2007, 2013)]
|
||||
>>> offsets = set(tzi.utcoffset(year) for year in subsequent_years)
|
||||
>>> len(offsets)
|
||||
1
|
||||
"""
|
||||
|
||||
# this key works for WinNT+, but not for the Win95 line.
|
||||
tzRegKey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones'
|
||||
|
||||
def __init__(self, param=None, fix_standard_time=False):
|
||||
if isinstance(param, TimeZoneDefinition):
|
||||
self._LoadFromTZI(param)
|
||||
if isinstance(param, str):
|
||||
self.timeZoneName = param
|
||||
self._LoadInfoFromKey()
|
||||
self.fixedStandardTime = fix_standard_time
|
||||
|
||||
def _FindTimeZoneKey(self):
|
||||
"""Find the registry key for the time zone name (self.timeZoneName)."""
|
||||
# for multi-language compatability, match the time zone name in the
|
||||
# "Std" key of the time zone key.
|
||||
zoneNames = dict(self._get_indexed_time_zone_keys('Std'))
|
||||
# Also match the time zone key name itself, to be compatible with
|
||||
# English-based hard-coded time zones.
|
||||
timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName)
|
||||
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey)
|
||||
try:
|
||||
result = key.subkey(timeZoneName)
|
||||
except:
|
||||
raise ValueError('Timezone Name %s not found.' % timeZoneName)
|
||||
return result
|
||||
|
||||
def _LoadInfoFromKey(self):
|
||||
"""Loads the information from an opened time zone registry key
|
||||
into relevant fields of this TZI object"""
|
||||
key = self._FindTimeZoneKey()
|
||||
self.displayName = key['Display']
|
||||
self.standardName = key['Std']
|
||||
self.daylightName = key['Dlt']
|
||||
self.staticInfo = TimeZoneDefinition(key['TZI'])
|
||||
self._LoadDynamicInfoFromKey(key)
|
||||
|
||||
def _LoadFromTZI(self, tzi):
|
||||
self.timeZoneName = tzi.standard_name
|
||||
self.displayName = 'Unknown'
|
||||
self.standardName = tzi.standard_name
|
||||
self.daylightName = tzi.daylight_name
|
||||
self.staticInfo = tzi
|
||||
|
||||
def _LoadDynamicInfoFromKey(self, key):
|
||||
"""
|
||||
>>> tzi = TimeZoneInfo('Central Standard Time')
|
||||
|
||||
Here's how the RangeMap is supposed to work:
|
||||
>>> m = RangeMap(zip([2006,2007], 'BC'),
|
||||
... sort_params = dict(reverse=True),
|
||||
... key_match_comparator=operator.ge)
|
||||
>>> m.get(2000, 'A')
|
||||
'A'
|
||||
>>> m[2006]
|
||||
'B'
|
||||
>>> m[2007]
|
||||
'C'
|
||||
>>> m[2008]
|
||||
'C'
|
||||
|
||||
>>> m[RangeMap.last_item]
|
||||
'B'
|
||||
|
||||
>>> m.get(2008, m[RangeMap.last_item])
|
||||
'C'
|
||||
|
||||
|
||||
Now test the dynamic info (but fallback to our simple RangeMap
|
||||
on systems that don't have dynamicInfo).
|
||||
|
||||
>>> dinfo = getattr(tzi, 'dynamicInfo', m)
|
||||
>>> 2007 in dinfo
|
||||
True
|
||||
>>> 2008 in dinfo
|
||||
False
|
||||
>>> dinfo[2007] == dinfo[2008] == dinfo[2012]
|
||||
True
|
||||
"""
|
||||
try:
|
||||
info = key.subkey('Dynamic DST')
|
||||
except WindowsError:
|
||||
return
|
||||
del info['FirstEntry']
|
||||
del info['LastEntry']
|
||||
years = map(int, list(info.keys()))
|
||||
values = map(TimeZoneDefinition, list(info.values()))
|
||||
# create a range mapping that searches by descending year and matches
|
||||
# if the target year is greater or equal.
|
||||
self.dynamicInfo = RangeMap(zip(years, values),
|
||||
sort_params = dict(reverse=True),
|
||||
key_match_comparator = operator.ge)
|
||||
|
||||
def __repr__(self):
|
||||
result = '%s(%s' % (self.__class__.__name__, repr(self.timeZoneName))
|
||||
if self.fixedStandardTime:
|
||||
result += ', True'
|
||||
result += ')'
|
||||
return result
|
||||
|
||||
def __str__(self):
|
||||
return self.displayName
|
||||
|
||||
def tzname(self, dt):
|
||||
winInfo = self.getWinInfo(dt)
|
||||
if self.dst(dt) == winInfo.daylight_bias:
|
||||
result = self.daylightName
|
||||
elif self.dst(dt) == winInfo.standard_bias:
|
||||
result = self.standardName
|
||||
return result
|
||||
|
||||
def getWinInfo(self, targetYear):
|
||||
"""
|
||||
Return the most relevant "info" for this time zone
|
||||
in the target year.
|
||||
"""
|
||||
if not hasattr(self, 'dynamicInfo') or not self.dynamicInfo:
|
||||
return self.staticInfo
|
||||
# Find the greatest year entry in self.dynamicInfo which is for
|
||||
# a year greater than or equal to our targetYear. If not found,
|
||||
# default to the earliest year.
|
||||
return self.dynamicInfo.get(targetYear,
|
||||
self.dynamicInfo[RangeMap.last_item])
|
||||
|
||||
def _getStandardBias(self, dt):
|
||||
winInfo = self.getWinInfo(dt.year)
|
||||
return winInfo.bias + winInfo.standard_bias
|
||||
|
||||
def _getDaylightBias(self, dt):
|
||||
winInfo = self.getWinInfo(dt.year)
|
||||
return winInfo.bias + winInfo.daylight_bias
|
||||
|
||||
def utcoffset(self, dt):
|
||||
"Calculates the utcoffset according to the datetime.tzinfo spec"
|
||||
if dt is None: return
|
||||
winInfo = self.getWinInfo(dt.year)
|
||||
return -winInfo.bias + self.dst(dt)
|
||||
|
||||
def dst(self, dt):
|
||||
"Calculates the daylight savings offset according to the datetime.tzinfo spec"
|
||||
if dt is None: return
|
||||
winInfo = self.getWinInfo(dt.year)
|
||||
if not self.fixedStandardTime and self._inDaylightSavings(dt):
|
||||
result = winInfo.daylight_bias
|
||||
else:
|
||||
result = winInfo.standard_bias
|
||||
return -result
|
||||
|
||||
def _inDaylightSavings(self, dt):
|
||||
dt = dt.replace(tzinfo=None)
|
||||
winInfo = self.getWinInfo(dt.year)
|
||||
try:
|
||||
dstStart = self.GetDSTStartTime(dt.year)
|
||||
dstEnd = self.GetDSTEndTime(dt.year)
|
||||
|
||||
# at the end of DST, when clocks are moved back, there's a period
|
||||
# of daylight_bias where it's ambiguous whether we're in DST or
|
||||
# not.
|
||||
dstEndAdj = dstEnd + winInfo.daylight_bias
|
||||
|
||||
# the same thing could theoretically happen at the start of DST
|
||||
# if there's a standard_bias (which I suspect is always 0).
|
||||
dstStartAdj = dstStart + winInfo.standard_bias
|
||||
|
||||
if dstStart < dstEnd:
|
||||
in_dst = dstStartAdj <= dt < dstEndAdj
|
||||
else:
|
||||
# in the southern hemisphere, daylight savings time
|
||||
# typically ends before it begins in a given year.
|
||||
in_dst = not (dstEndAdj < dt <= dstStartAdj)
|
||||
except ValueError:
|
||||
# there was an error parsing the time zone, which is normal when a
|
||||
# start and end time are not specified.
|
||||
in_dst = False
|
||||
|
||||
return in_dst
|
||||
|
||||
def GetDSTStartTime(self, year):
|
||||
"Given a year, determines the time when daylight savings time starts"
|
||||
return self.getWinInfo(year).locate_daylight_start(year)
|
||||
|
||||
def GetDSTEndTime(self, year):
|
||||
"Given a year, determines the time when daylight savings ends."
|
||||
return self.getWinInfo(year).locate_standard_start(year)
|
||||
|
||||
def __cmp__(self, other):
|
||||
return cmp(self.__dict__, other.__dict__)
|
||||
|
||||
def __eq__(self, other):
|
||||
return self.__dict__==other.__dict__
|
||||
|
||||
def __ne__(self, other):
|
||||
return self.__dict__!=other.__dict__
|
||||
|
||||
@classmethod
|
||||
def local(class_):
|
||||
"""Returns the local time zone as defined by the operating system in the
|
||||
registry.
|
||||
>>> localTZ = TimeZoneInfo.local()
|
||||
>>> now_local = datetime.datetime.now(localTZ)
|
||||
>>> now_UTC = datetime.datetime.utcnow()
|
||||
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't subtract offset-naive and offset-aware datetimes
|
||||
|
||||
>>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True))
|
||||
|
||||
Now one can compare the results of the two offset aware values
|
||||
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
|
||||
True
|
||||
"""
|
||||
code, info = TimeZoneDefinition.current()
|
||||
# code is 0 if daylight savings is disabled or not defined
|
||||
# code is 1 or 2 if daylight savings is enabled, 2 if currently active
|
||||
fix_standard_time = not code
|
||||
# note that although the given information is sufficient to construct a WinTZI object, it's
|
||||
# not sufficient to represent the time zone in which the current user is operating due
|
||||
# to dynamic time zones.
|
||||
return class_(info, fix_standard_time)
|
||||
|
||||
@classmethod
|
||||
def utc(class_):
|
||||
"""Returns a time-zone representing UTC.
|
||||
|
||||
Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
|
||||
for performance.
|
||||
|
||||
>>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
|
||||
True
|
||||
"""
|
||||
if not '_tzutc' in class_.__dict__:
|
||||
setattr(class_, '_tzutc', class_('GMT Standard Time', True))
|
||||
return class_._tzutc
|
||||
|
||||
# helper methods for accessing the timezone info from the registry
|
||||
@staticmethod
|
||||
def _get_time_zone_key(subkey=None):
|
||||
"Return the registry key that stores time zone details"
|
||||
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey)
|
||||
if subkey:
|
||||
key = key.subkey(subkey)
|
||||
return key
|
||||
|
||||
@staticmethod
|
||||
def _get_time_zone_key_names():
|
||||
"Returns the names of the (registry keys of the) time zones"
|
||||
return TimeZoneInfo._get_time_zone_key().subkeys()
|
||||
|
||||
@staticmethod
|
||||
def _get_indexed_time_zone_keys(index_key='Index'):
|
||||
"""
|
||||
Get the names of the registry keys indexed by a value in that key.
|
||||
"""
|
||||
key_names = list(TimeZoneInfo._get_time_zone_key_names())
|
||||
def get_index_value(key_name):
|
||||
key = TimeZoneInfo._get_time_zone_key(key_name)
|
||||
return key[index_key]
|
||||
values = map(get_index_value, key_names)
|
||||
return zip(values, key_names)
|
||||
|
||||
@staticmethod
|
||||
def get_sorted_time_zone_names():
|
||||
"Return a list of time zone names that can be used to initialize TimeZoneInfo instances"
|
||||
tzs = TimeZoneInfo.get_sorted_time_zones()
|
||||
get_standard_name = lambda tzi: tzi.standardName
|
||||
return [get_standard_name(tz) for tz in tzs]
|
||||
|
||||
@staticmethod
|
||||
def get_all_time_zones():
|
||||
return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()]
|
||||
|
||||
@staticmethod
|
||||
def get_sorted_time_zones(key=None):
|
||||
"""
|
||||
Return the time zones sorted by some key.
|
||||
key must be a function that takes a TimeZoneInfo object and returns
|
||||
a value suitable for sorting on.
|
||||
The key defaults to the bias (descending), as is done in Windows
|
||||
(see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)
|
||||
"""
|
||||
key = key or (lambda tzi: -tzi.staticInfo.bias)
|
||||
zones = TimeZoneInfo.get_all_time_zones()
|
||||
zones.sort(key=key)
|
||||
return zones
|
||||
|
||||
class _RegKeyDict(dict):
|
||||
def __init__(self, key):
|
||||
dict.__init__(self)
|
||||
self.key = key
|
||||
self.__load_values()
|
||||
|
||||
@classmethod
|
||||
def open(cls, *args, **kargs):
|
||||
return _RegKeyDict(winreg.OpenKeyEx(*args, **kargs))
|
||||
|
||||
def subkey(self, name):
|
||||
return _RegKeyDict(winreg.OpenKeyEx(self.key, name))
|
||||
|
||||
def __load_values(self):
|
||||
pairs = [(n, v) for (n, v, t) in self._enumerate_reg_values(self.key)]
|
||||
self.update(pairs)
|
||||
|
||||
def subkeys(self):
|
||||
return self._enumerate_reg_keys(self.key)
|
||||
|
||||
@staticmethod
|
||||
def _enumerate_reg_values(key):
|
||||
return _RegKeyDict._enumerate_reg(key, winreg.EnumValue)
|
||||
|
||||
@staticmethod
|
||||
def _enumerate_reg_keys(key):
|
||||
return _RegKeyDict._enumerate_reg(key, winreg.EnumKey)
|
||||
|
||||
@staticmethod
|
||||
def _enumerate_reg(key, func):
|
||||
"Enumerates an open registry key as an iterable generator"
|
||||
try:
|
||||
for index in count():
|
||||
yield func(key, index)
|
||||
except WindowsError: pass
|
||||
|
||||
|
||||
# for backward compatibility
|
||||
def deprecated(func, name='Unknown'):
|
||||
"""This is a decorator which can be used to mark functions
|
||||
as deprecated. It will result in a warning being emmitted
|
||||
when the function is used."""
|
||||
def newFunc(*args, **kwargs):
|
||||
warnings.warn("Call to deprecated function %s." % name,
|
||||
category=DeprecationWarning)
|
||||
return func(*args, **kwargs)
|
||||
newFunc.__name__ = func.__name__
|
||||
newFunc.__doc__ = func.__doc__
|
||||
newFunc.__dict__.update(func.__dict__)
|
||||
return newFunc
|
||||
|
||||
GetTimeZoneNames = deprecated(TimeZoneInfo._get_time_zone_key_names, 'GetTimeZoneNames')
|
||||
GetIndexedTimeZoneNames = deprecated(TimeZoneInfo._get_indexed_time_zone_keys, 'GetIndexedTimeZoneNames')
|
||||
GetSortedTimeZoneNames = deprecated(TimeZoneInfo.get_sorted_time_zone_names, 'GetSortedTimeZoneNames')
|
||||
# end backward compatibility
|
||||
|
||||
def utcnow():
|
||||
"""
|
||||
Return the UTC time now with timezone awareness as enabled
|
||||
by this module
|
||||
>>> now = utcnow()
|
||||
"""
|
||||
now = datetime.datetime.utcnow()
|
||||
now = now.replace(tzinfo=TimeZoneInfo.utc())
|
||||
return now
|
||||
|
||||
def now():
|
||||
"""
|
||||
Return the local time now with timezone awareness as enabled
|
||||
by this module
|
||||
>>> now_local = now()
|
||||
"""
|
||||
return datetime.datetime.now(TimeZoneInfo.local())
|
||||
|
||||
def GetTZCapabilities():
|
||||
"""Run a few known tests to determine the capabilities of the time zone database
|
||||
on this machine.
|
||||
Note Dynamic Time Zone support is not available on any platform at this time; this
|
||||
is a limitation of this library, not the platform."""
|
||||
tzi = TimeZoneInfo('Mountain Standard Time')
|
||||
MissingTZPatch = datetime.datetime(2007,11,2,tzinfo=tzi).utctimetuple() != (2007,11,2,6,0,0,4,306,0)
|
||||
DynamicTZSupport = not MissingTZPatch and datetime.datetime(2003,11,2,tzinfo=tzi).utctimetuple() == (2003,11,2,7,0,0,6,306,0)
|
||||
del tzi
|
||||
return vars()
|
||||
|
||||
|
||||
class DLLHandleCache(object):
|
||||
def __init__(self):
|
||||
self.__cache = {}
|
||||
|
||||
def __getitem__(self, filename):
|
||||
key = filename.lower()
|
||||
return self.__cache.setdefault(key, win32api.LoadLibrary(key))
|
||||
|
||||
DLLCache = DLLHandleCache()
|
||||
|
||||
def resolveMUITimeZone(spec):
|
||||
"""Resolve a multilingual user interface resource for the time zone name
|
||||
>>> #some pre-amble for the doc-tests to be py2k and py3k aware)
|
||||
>>> try: unicode and None
|
||||
... except NameError: unicode=str
|
||||
...
|
||||
>>> import sys
|
||||
>>> result = resolveMUITimeZone('@tzres.dll,-110')
|
||||
>>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)]
|
||||
>>> type(result) is expectedResultType
|
||||
True
|
||||
|
||||
spec should be of the format @path,-stringID[;comment]
|
||||
see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
|
||||
"""
|
||||
pattern = re.compile('@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?')
|
||||
matcher = pattern.match(spec)
|
||||
assert matcher, 'Could not parse MUI spec'
|
||||
|
||||
try:
|
||||
handle = DLLCache[matcher.groupdict()['dllname']]
|
||||
result = win32api.LoadString(handle, int(matcher.groupdict()['index']))
|
||||
except win32api.error:
|
||||
result = None
|
||||
return result
|
||||
|
||||
# from jaraco.util.dictlib 5.3.1
|
||||
class RangeMap(dict):
|
||||
"""
|
||||
A dictionary-like object that uses the keys as bounds for a range.
|
||||
Inclusion of the value for that range is determined by the
|
||||
key_match_comparator, which defaults to less-than-or-equal.
|
||||
A value is returned for a key if it is the first key that matches in
|
||||
the sorted list of keys.
|
||||
|
||||
One may supply keyword parameters to be passed to the sort function used
|
||||
to sort keys (i.e. cmp [python 2 only], keys, reverse) as sort_params.
|
||||
|
||||
Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
|
||||
>>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
|
||||
>>> r[1], r[2], r[3], r[4], r[5], r[6]
|
||||
('a', 'a', 'a', 'b', 'b', 'b')
|
||||
|
||||
Even float values should work so long as the comparison operator
|
||||
supports it.
|
||||
>>> r[4.5]
|
||||
'b'
|
||||
|
||||
But you'll notice that the way rangemap is defined, it must be open-ended on one side.
|
||||
>>> r[0]
|
||||
'a'
|
||||
>>> r[-1]
|
||||
'a'
|
||||
|
||||
One can close the open-end of the RangeMap by using undefined_value
|
||||
>>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
|
||||
>>> r[0]
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
KeyError: 0
|
||||
|
||||
One can get the first or last elements in the range by using RangeMap.Item
|
||||
>>> last_item = RangeMap.Item(-1)
|
||||
>>> r[last_item]
|
||||
'b'
|
||||
|
||||
.last_item is a shortcut for Item(-1)
|
||||
>>> r[RangeMap.last_item]
|
||||
'b'
|
||||
|
||||
Sometimes it's useful to find the bounds for a RangeMap
|
||||
>>> r.bounds()
|
||||
(0, 6)
|
||||
|
||||
RangeMap supports .get(key, default)
|
||||
>>> r.get(0, 'not found')
|
||||
'not found'
|
||||
|
||||
>>> r.get(7, 'not found')
|
||||
'not found'
|
||||
|
||||
"""
|
||||
def __init__(self, source, sort_params = {}, key_match_comparator = operator.le):
|
||||
dict.__init__(self, source)
|
||||
self.sort_params = sort_params
|
||||
self.match = key_match_comparator
|
||||
|
||||
def __getitem__(self, item):
|
||||
sorted_keys = sorted(list(self.keys()), **self.sort_params)
|
||||
if isinstance(item, RangeMap.Item):
|
||||
result = self.__getitem__(sorted_keys[item])
|
||||
else:
|
||||
key = self._find_first_match_(sorted_keys, item)
|
||||
result = dict.__getitem__(self, key)
|
||||
if result is RangeMap.undefined_value:
|
||||
raise KeyError(key)
|
||||
return result
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""
|
||||
Return the value for key if key is in the dictionary, else default.
|
||||
If default is not given, it defaults to None, so that this method
|
||||
never raises a KeyError.
|
||||
"""
|
||||
try:
|
||||
return self[key]
|
||||
except KeyError:
|
||||
return default
|
||||
|
||||
def _find_first_match_(self, keys, item):
|
||||
is_match = lambda k: self.match(item, k)
|
||||
matches = list(filter(is_match, keys))
|
||||
if matches:
|
||||
return matches[0]
|
||||
raise KeyError(item)
|
||||
|
||||
def bounds(self):
|
||||
sorted_keys = sorted(list(self.keys()), **self.sort_params)
|
||||
return (
|
||||
sorted_keys[RangeMap.first_item],
|
||||
sorted_keys[RangeMap.last_item],
|
||||
)
|
||||
|
||||
# some special values for the RangeMap
|
||||
undefined_value = type(str('RangeValueUndefined'), (object,), {})()
|
||||
class Item(int): pass
|
||||
first_item = Item(0)
|
||||
last_item = Item(-1)
|
||||
55
Pywin32/lib/x32/win32/lib/win32traceutil.py
Normal file
@@ -0,0 +1,55 @@
|
||||
# This is a helper for the win32trace module
|
||||
|
||||
# If imported from a normal Python program, it sets up sys.stdout and sys.stderr
|
||||
# so output goes to the collector.
|
||||
|
||||
# If run from the command line, it creates a collector loop.
|
||||
|
||||
# Eg:
|
||||
# C:>start win32traceutil.py (or python.exe win32traceutil.py)
|
||||
# will start a process with a (pretty much) blank screen.
|
||||
#
|
||||
# then, switch to a DOS prompt, and type:
|
||||
# C:>python.exe
|
||||
# Python 1.4 etc...
|
||||
# >>> import win32traceutil
|
||||
# Redirecting output to win32trace remote collector
|
||||
# >>> print "Hello"
|
||||
# >>>
|
||||
# And the output will appear in the first collector process.
|
||||
|
||||
# Note - the client or the collector can be started first.
|
||||
# There is a 0x20000 byte buffer. If this gets full, it is reset, and new
|
||||
# output appended from the start.
|
||||
|
||||
import win32trace
|
||||
|
||||
def RunAsCollector():
|
||||
import sys
|
||||
try:
|
||||
import win32api
|
||||
win32api.SetConsoleTitle("Python Trace Collector")
|
||||
except:
|
||||
pass # Oh well!
|
||||
win32trace.InitRead()
|
||||
print("Collecting Python Trace Output...")
|
||||
try:
|
||||
while 1:
|
||||
# a short timeout means ctrl+c works next time we wake...
|
||||
sys.stdout.write(win32trace.blockingread(500))
|
||||
except KeyboardInterrupt:
|
||||
print("Ctrl+C")
|
||||
|
||||
|
||||
def SetupForPrint():
|
||||
win32trace.InitWrite()
|
||||
try: # Under certain servers, sys.stdout may be invalid.
|
||||
print("Redirecting output to win32trace remote collector")
|
||||
except:
|
||||
pass
|
||||
win32trace.setprint() # this works in an rexec environment.
|
||||
|
||||
if __name__=='__main__':
|
||||
RunAsCollector()
|
||||
else:
|
||||
SetupForPrint()
|
||||
200
Pywin32/lib/x32/win32/lib/win32verstamp.py
Normal file
@@ -0,0 +1,200 @@
|
||||
""" Stamp a Win32 binary with version information.
|
||||
"""
|
||||
|
||||
from win32api import BeginUpdateResource, UpdateResource, EndUpdateResource
|
||||
|
||||
import os
|
||||
import struct
|
||||
import glob
|
||||
|
||||
import optparse
|
||||
|
||||
VS_FFI_SIGNATURE = -17890115 # 0xFEEF04BD
|
||||
VS_FFI_STRUCVERSION = 0x00010000
|
||||
VS_FFI_FILEFLAGSMASK = 0x0000003f
|
||||
VOS_NT_WINDOWS32 = 0x00040004
|
||||
|
||||
null_byte = "\0".encode("ascii") # str in py2k, bytes in py3k
|
||||
#
|
||||
# Set VS_FF_PRERELEASE and DEBUG if Debug
|
||||
#
|
||||
def file_flags(debug):
|
||||
if debug:
|
||||
return 3 # VS_FF_DEBUG | VS_FF_PRERELEASE
|
||||
return 0
|
||||
|
||||
def file_type(is_dll):
|
||||
if is_dll:
|
||||
return 2 # VFT_DLL
|
||||
return 1 # VFT_APP
|
||||
|
||||
def VS_FIXEDFILEINFO(maj, min, sub, build, debug=0, is_dll=1):
|
||||
return struct.pack('lllllllllllll',
|
||||
VS_FFI_SIGNATURE, # dwSignature
|
||||
VS_FFI_STRUCVERSION, # dwStrucVersion
|
||||
(maj << 16) | min, # dwFileVersionMS
|
||||
(sub << 16) | build,# dwFileVersionLS
|
||||
(maj << 16) | min, # dwProductVersionMS
|
||||
(sub << 16) | build, # dwProductVersionLS
|
||||
VS_FFI_FILEFLAGSMASK, # dwFileFlagsMask
|
||||
file_flags(debug), # dwFileFlags
|
||||
VOS_NT_WINDOWS32, # dwFileOS
|
||||
file_type(is_dll), # dwFileType
|
||||
0x00000000, # dwFileSubtype
|
||||
0x00000000, # dwFileDateMS
|
||||
0x00000000, # dwFileDateLS
|
||||
)
|
||||
|
||||
def nullterm(s):
|
||||
# get raw bytes for a NULL terminated unicode string.
|
||||
return (str(s) + '\0').encode('unicode-internal')
|
||||
|
||||
def pad32(s, extra=2):
|
||||
# extra is normally 2 to deal with wLength
|
||||
l = 4 - ((len(s) + extra) & 3)
|
||||
if l < 4:
|
||||
return s + (null_byte * l)
|
||||
return s
|
||||
|
||||
def addlen(s):
|
||||
return struct.pack('h', len(s) + 2) + s
|
||||
|
||||
def String(key, value):
|
||||
key = nullterm(key)
|
||||
value = nullterm(value)
|
||||
result = struct.pack('hh', len(value)//2, 1) # wValueLength, wType
|
||||
result = result + key
|
||||
result = pad32(result) + value
|
||||
return addlen(result)
|
||||
|
||||
def StringTable(key, data):
|
||||
key = nullterm(key)
|
||||
result = struct.pack('hh', 0, 1) # wValueLength, wType
|
||||
result = result + key
|
||||
for k, v in data.items():
|
||||
result = result + String(k, v)
|
||||
result = pad32(result)
|
||||
return addlen(result)
|
||||
|
||||
def StringFileInfo(data):
|
||||
result = struct.pack('hh', 0, 1) # wValueLength, wType
|
||||
result = result + nullterm('StringFileInfo')
|
||||
# result = pad32(result) + StringTable('040904b0', data)
|
||||
result = pad32(result) + StringTable('040904E4', data)
|
||||
return addlen(result)
|
||||
|
||||
def Var(key, value):
|
||||
result = struct.pack('hh', len(value), 0) # wValueLength, wType
|
||||
result = result + nullterm(key)
|
||||
result = pad32(result) + value
|
||||
return addlen(result)
|
||||
|
||||
def VarFileInfo(data):
|
||||
result = struct.pack('hh', 0, 1) # wValueLength, wType
|
||||
result = result + nullterm('VarFileInfo')
|
||||
result = pad32(result)
|
||||
for k, v in data.items():
|
||||
result = result + Var(k, v)
|
||||
return addlen(result)
|
||||
|
||||
def VS_VERSION_INFO(maj, min, sub, build, sdata, vdata, debug=0, is_dll=1):
|
||||
ffi = VS_FIXEDFILEINFO(maj, min, sub, build, debug, is_dll)
|
||||
result = struct.pack('hh', len(ffi), 0) # wValueLength, wType
|
||||
result = result + nullterm('VS_VERSION_INFO')
|
||||
result = pad32(result) + ffi
|
||||
result = pad32(result) + StringFileInfo(sdata) + VarFileInfo(vdata)
|
||||
return addlen(result)
|
||||
|
||||
def stamp(pathname, options):
|
||||
# For some reason, the API functions report success if the file is open
|
||||
# but doesnt work! Try and open the file for writing, just to see if it is
|
||||
# likely the stamp will work!
|
||||
try:
|
||||
f = open(pathname, "a+b")
|
||||
f.close()
|
||||
except IOError as why:
|
||||
print("WARNING: File %s could not be opened - %s" % (pathname, why))
|
||||
|
||||
ver = options.version
|
||||
try:
|
||||
bits = [int(i) for i in ver.split(".")]
|
||||
vmaj, vmin, vsub, vbuild = bits
|
||||
except (IndexError, TypeError, ValueError):
|
||||
raise ValueError("--version must be a.b.c.d (all integers) - got %r" % ver)
|
||||
|
||||
ifn = options.internal_name
|
||||
if not ifn:
|
||||
ifn = os.path.basename(pathname)
|
||||
ofn = options.original_filename
|
||||
if not ofn:
|
||||
ofn = os.path.basename(pathname)
|
||||
|
||||
sdata = {
|
||||
'Comments' : options.comments,
|
||||
'CompanyName' : options.company,
|
||||
'FileDescription' : options.description,
|
||||
'FileVersion' : ver,
|
||||
'InternalName' : ifn,
|
||||
'LegalCopyright' : options.copyright,
|
||||
'LegalTrademarks' : options.trademarks,
|
||||
'OriginalFilename' : ofn,
|
||||
'ProductName' : options.product,
|
||||
'ProductVersion' : ver,
|
||||
}
|
||||
vdata = {
|
||||
'Translation' : struct.pack('hh', 0x409,1252),
|
||||
}
|
||||
is_dll = options.dll
|
||||
if is_dll is None:
|
||||
is_dll = os.path.splitext(pathname)[1].lower() in '.dll .pyd'.split()
|
||||
is_debug = options.debug
|
||||
if is_debug is None:
|
||||
is_debug = os.path.splitext(pathname)[0].lower().endswith("_d")
|
||||
# convert None to blank strings
|
||||
for k, v in list(sdata.items()):
|
||||
if v is None:
|
||||
sdata[k] = ""
|
||||
vs = VS_VERSION_INFO(vmaj, vmin, vsub, vbuild, sdata, vdata, is_debug, is_dll)
|
||||
|
||||
h = BeginUpdateResource(pathname, 0)
|
||||
UpdateResource(h, 16, 1, vs)
|
||||
EndUpdateResource(h, 0)
|
||||
|
||||
if options.verbose:
|
||||
print("Stamped:", pathname)
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = optparse.OptionParser("%prog [options] filespec ...",
|
||||
description=__doc__)
|
||||
|
||||
parser.add_option("-q", "--quiet",
|
||||
action="store_false", dest="verbose", default=True,
|
||||
help="don't print status messages to stdout")
|
||||
parser.add_option("", "--version", default="0.0.0.0",
|
||||
help="The version number as m.n.s.b")
|
||||
parser.add_option("", "--dll",
|
||||
help="""Stamp the file as a DLL. Default is to look at the
|
||||
file extension for .dll or .pyd.""")
|
||||
parser.add_option("", "--debug", help="""Stamp the file as a debug binary.""")
|
||||
parser.add_option("", "--product", help="""The product name to embed.""")
|
||||
parser.add_option("", "--company", help="""The company name to embed.""")
|
||||
parser.add_option("", "--trademarks", help="The trademark string to embed.")
|
||||
parser.add_option("", "--comments", help="The comments string to embed.")
|
||||
parser.add_option("", "--copyright",
|
||||
help="""The copyright message string to embed.""")
|
||||
parser.add_option("", "--description", metavar="DESC",
|
||||
help="The description to embed.")
|
||||
parser.add_option("", "--internal-name", metavar="NAME",
|
||||
help="""The internal filename to embed. If not specified
|
||||
the base filename is used.""")
|
||||
parser.add_option("", "--original-filename",
|
||||
help="""The original filename to embed. If not specified
|
||||
the base filename is used.""")
|
||||
|
||||
options, args = parser.parse_args()
|
||||
if not args:
|
||||
parser.error("You must supply a file to stamp. Use --help for details.")
|
||||
|
||||
for g in args:
|
||||
for f in glob.glob(g):
|
||||
stamp(f, options)
|
||||
3012
Pywin32/lib/x32/win32/lib/winerror.py
Normal file
708
Pywin32/lib/x32/win32/lib/winioctlcon.py
Normal file
@@ -0,0 +1,708 @@
|
||||
## flags, enums, guids used with DeviceIoControl from WinIoCtl.h
|
||||
|
||||
import pywintypes
|
||||
from ntsecuritycon import FILE_READ_DATA,FILE_WRITE_DATA
|
||||
def CTL_CODE(DeviceType, Function, Method, Access):
|
||||
return (DeviceType << 16) | (Access << 14) | (Function << 2) | Method
|
||||
|
||||
def DEVICE_TYPE_FROM_CTL_CODE(ctrlCode):
|
||||
return (ctrlCode & 0xffff0000) >> 16
|
||||
|
||||
FILE_DEVICE_BEEP = 0x00000001
|
||||
FILE_DEVICE_CD_ROM = 0x00000002
|
||||
FILE_DEVICE_CD_ROM_FILE_SYSTEM = 0x00000003
|
||||
FILE_DEVICE_CONTROLLER = 0x00000004
|
||||
FILE_DEVICE_DATALINK = 0x00000005
|
||||
FILE_DEVICE_DFS = 0x00000006
|
||||
FILE_DEVICE_DISK = 0x00000007
|
||||
FILE_DEVICE_DISK_FILE_SYSTEM = 0x00000008
|
||||
FILE_DEVICE_FILE_SYSTEM = 0x00000009
|
||||
FILE_DEVICE_INPORT_PORT = 0x0000000a
|
||||
FILE_DEVICE_KEYBOARD = 0x0000000b
|
||||
FILE_DEVICE_MAILSLOT = 0x0000000c
|
||||
FILE_DEVICE_MIDI_IN = 0x0000000d
|
||||
FILE_DEVICE_MIDI_OUT = 0x0000000e
|
||||
FILE_DEVICE_MOUSE = 0x0000000f
|
||||
FILE_DEVICE_MULTI_UNC_PROVIDER = 0x00000010
|
||||
FILE_DEVICE_NAMED_PIPE = 0x00000011
|
||||
FILE_DEVICE_NETWORK = 0x00000012
|
||||
FILE_DEVICE_NETWORK_BROWSER = 0x00000013
|
||||
FILE_DEVICE_NETWORK_FILE_SYSTEM = 0x00000014
|
||||
FILE_DEVICE_NULL = 0x00000015
|
||||
FILE_DEVICE_PARALLEL_PORT = 0x00000016
|
||||
FILE_DEVICE_PHYSICAL_NETCARD = 0x00000017
|
||||
FILE_DEVICE_PRINTER = 0x00000018
|
||||
FILE_DEVICE_SCANNER = 0x00000019
|
||||
FILE_DEVICE_SERIAL_MOUSE_PORT = 0x0000001a
|
||||
FILE_DEVICE_SERIAL_PORT = 0x0000001b
|
||||
FILE_DEVICE_SCREEN = 0x0000001c
|
||||
FILE_DEVICE_SOUND = 0x0000001d
|
||||
FILE_DEVICE_STREAMS = 0x0000001e
|
||||
FILE_DEVICE_TAPE = 0x0000001f
|
||||
FILE_DEVICE_TAPE_FILE_SYSTEM = 0x00000020
|
||||
FILE_DEVICE_TRANSPORT = 0x00000021
|
||||
FILE_DEVICE_UNKNOWN = 0x00000022
|
||||
FILE_DEVICE_VIDEO = 0x00000023
|
||||
FILE_DEVICE_VIRTUAL_DISK = 0x00000024
|
||||
FILE_DEVICE_WAVE_IN = 0x00000025
|
||||
FILE_DEVICE_WAVE_OUT = 0x00000026
|
||||
FILE_DEVICE_8042_PORT = 0x00000027
|
||||
FILE_DEVICE_NETWORK_REDIRECTOR = 0x00000028
|
||||
FILE_DEVICE_BATTERY = 0x00000029
|
||||
FILE_DEVICE_BUS_EXTENDER = 0x0000002a
|
||||
FILE_DEVICE_MODEM = 0x0000002b
|
||||
FILE_DEVICE_VDM = 0x0000002c
|
||||
FILE_DEVICE_MASS_STORAGE = 0x0000002d
|
||||
FILE_DEVICE_SMB = 0x0000002e
|
||||
FILE_DEVICE_KS = 0x0000002f
|
||||
FILE_DEVICE_CHANGER = 0x00000030
|
||||
FILE_DEVICE_SMARTCARD = 0x00000031
|
||||
FILE_DEVICE_ACPI = 0x00000032
|
||||
FILE_DEVICE_DVD = 0x00000033
|
||||
FILE_DEVICE_FULLSCREEN_VIDEO = 0x00000034
|
||||
FILE_DEVICE_DFS_FILE_SYSTEM = 0x00000035
|
||||
FILE_DEVICE_DFS_VOLUME = 0x00000036
|
||||
FILE_DEVICE_SERENUM = 0x00000037
|
||||
FILE_DEVICE_TERMSRV = 0x00000038
|
||||
FILE_DEVICE_KSEC = 0x00000039
|
||||
FILE_DEVICE_FIPS = 0x0000003A
|
||||
FILE_DEVICE_INFINIBAND = 0x0000003B
|
||||
|
||||
METHOD_BUFFERED = 0
|
||||
METHOD_IN_DIRECT = 1
|
||||
METHOD_OUT_DIRECT = 2
|
||||
METHOD_NEITHER = 3
|
||||
METHOD_DIRECT_TO_HARDWARE = METHOD_IN_DIRECT
|
||||
METHOD_DIRECT_FROM_HARDWARE = METHOD_OUT_DIRECT
|
||||
FILE_ANY_ACCESS = 0
|
||||
FILE_SPECIAL_ACCESS = FILE_ANY_ACCESS
|
||||
FILE_READ_ACCESS = 0x0001
|
||||
FILE_WRITE_ACCESS = 0x0002
|
||||
IOCTL_STORAGE_BASE = FILE_DEVICE_MASS_STORAGE
|
||||
RECOVERED_WRITES_VALID = 0x00000001
|
||||
UNRECOVERED_WRITES_VALID = 0x00000002
|
||||
RECOVERED_READS_VALID = 0x00000004
|
||||
UNRECOVERED_READS_VALID = 0x00000008
|
||||
WRITE_COMPRESSION_INFO_VALID = 0x00000010
|
||||
READ_COMPRESSION_INFO_VALID = 0x00000020
|
||||
TAPE_RETURN_STATISTICS = 0
|
||||
TAPE_RETURN_ENV_INFO = 1
|
||||
TAPE_RESET_STATISTICS = 2
|
||||
MEDIA_ERASEABLE = 0x00000001
|
||||
MEDIA_WRITE_ONCE = 0x00000002
|
||||
MEDIA_READ_ONLY = 0x00000004
|
||||
MEDIA_READ_WRITE = 0x00000008
|
||||
MEDIA_WRITE_PROTECTED = 0x00000100
|
||||
MEDIA_CURRENTLY_MOUNTED = 0x80000000
|
||||
IOCTL_DISK_BASE = FILE_DEVICE_DISK
|
||||
PARTITION_ENTRY_UNUSED = 0x00
|
||||
PARTITION_FAT_12 = 0x01
|
||||
PARTITION_XENIX_1 = 0x02
|
||||
PARTITION_XENIX_2 = 0x03
|
||||
PARTITION_FAT_16 = 0x04
|
||||
PARTITION_EXTENDED = 0x05
|
||||
PARTITION_HUGE = 0x06
|
||||
PARTITION_IFS = 0x07
|
||||
PARTITION_OS2BOOTMGR = 0x0A
|
||||
PARTITION_FAT32 = 0x0B
|
||||
PARTITION_FAT32_XINT13 = 0x0C
|
||||
PARTITION_XINT13 = 0x0E
|
||||
PARTITION_XINT13_EXTENDED = 0x0F
|
||||
PARTITION_PREP = 0x41
|
||||
PARTITION_LDM = 0x42
|
||||
PARTITION_UNIX = 0x63
|
||||
VALID_NTFT = 0xC0
|
||||
PARTITION_NTFT = 0x80
|
||||
|
||||
GPT_ATTRIBUTE_PLATFORM_REQUIRED = 0x0000000000000001
|
||||
GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 0x8000000000000000
|
||||
GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = 0x4000000000000000
|
||||
GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 0x2000000000000000
|
||||
GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = 0x1000000000000000
|
||||
|
||||
HIST_NO_OF_BUCKETS = 24
|
||||
DISK_LOGGING_START = 0
|
||||
DISK_LOGGING_STOP = 1
|
||||
DISK_LOGGING_DUMP = 2
|
||||
DISK_BINNING = 3
|
||||
CAP_ATA_ID_CMD = 1
|
||||
CAP_ATAPI_ID_CMD = 2
|
||||
CAP_SMART_CMD = 4
|
||||
ATAPI_ID_CMD = 0xA1
|
||||
ID_CMD = 0xEC
|
||||
SMART_CMD = 0xB0
|
||||
SMART_CYL_LOW = 0x4F
|
||||
SMART_CYL_HI = 0xC2
|
||||
SMART_NO_ERROR = 0
|
||||
SMART_IDE_ERROR = 1
|
||||
SMART_INVALID_FLAG = 2
|
||||
SMART_INVALID_COMMAND = 3
|
||||
SMART_INVALID_BUFFER = 4
|
||||
SMART_INVALID_DRIVE = 5
|
||||
SMART_INVALID_IOCTL = 6
|
||||
SMART_ERROR_NO_MEM = 7
|
||||
SMART_INVALID_REGISTER = 8
|
||||
SMART_NOT_SUPPORTED = 9
|
||||
SMART_NO_IDE_DEVICE = 10
|
||||
SMART_OFFLINE_ROUTINE_OFFLINE = 0
|
||||
SMART_SHORT_SELFTEST_OFFLINE = 1
|
||||
SMART_EXTENDED_SELFTEST_OFFLINE = 2
|
||||
SMART_ABORT_OFFLINE_SELFTEST = 127
|
||||
SMART_SHORT_SELFTEST_CAPTIVE = 129
|
||||
SMART_EXTENDED_SELFTEST_CAPTIVE = 130
|
||||
READ_ATTRIBUTE_BUFFER_SIZE = 512
|
||||
IDENTIFY_BUFFER_SIZE = 512
|
||||
READ_THRESHOLD_BUFFER_SIZE = 512
|
||||
SMART_LOG_SECTOR_SIZE = 512
|
||||
READ_ATTRIBUTES = 0xD0
|
||||
READ_THRESHOLDS = 0xD1
|
||||
ENABLE_DISABLE_AUTOSAVE = 0xD2
|
||||
SAVE_ATTRIBUTE_VALUES = 0xD3
|
||||
EXECUTE_OFFLINE_DIAGS = 0xD4
|
||||
SMART_READ_LOG = 0xD5
|
||||
SMART_WRITE_LOG = 0xd6
|
||||
ENABLE_SMART = 0xD8
|
||||
DISABLE_SMART = 0xD9
|
||||
RETURN_SMART_STATUS = 0xDA
|
||||
ENABLE_DISABLE_AUTO_OFFLINE = 0xDB
|
||||
IOCTL_CHANGER_BASE = FILE_DEVICE_CHANGER
|
||||
MAX_VOLUME_ID_SIZE = 36
|
||||
MAX_VOLUME_TEMPLATE_SIZE = 40
|
||||
VENDOR_ID_LENGTH = 8
|
||||
PRODUCT_ID_LENGTH = 16
|
||||
REVISION_LENGTH = 4
|
||||
SERIAL_NUMBER_LENGTH = 32
|
||||
CHANGER_BAR_CODE_SCANNER_INSTALLED = 0x00000001
|
||||
CHANGER_INIT_ELEM_STAT_WITH_RANGE = 0x00000002
|
||||
CHANGER_CLOSE_IEPORT = 0x00000004
|
||||
CHANGER_OPEN_IEPORT = 0x00000008
|
||||
CHANGER_STATUS_NON_VOLATILE = 0x00000010
|
||||
CHANGER_EXCHANGE_MEDIA = 0x00000020
|
||||
CHANGER_CLEANER_SLOT = 0x00000040
|
||||
CHANGER_LOCK_UNLOCK = 0x00000080
|
||||
CHANGER_CARTRIDGE_MAGAZINE = 0x00000100
|
||||
CHANGER_MEDIUM_FLIP = 0x00000200
|
||||
CHANGER_POSITION_TO_ELEMENT = 0x00000400
|
||||
CHANGER_REPORT_IEPORT_STATE = 0x00000800
|
||||
CHANGER_STORAGE_DRIVE = 0x00001000
|
||||
CHANGER_STORAGE_IEPORT = 0x00002000
|
||||
CHANGER_STORAGE_SLOT = 0x00004000
|
||||
CHANGER_STORAGE_TRANSPORT = 0x00008000
|
||||
CHANGER_DRIVE_CLEANING_REQUIRED = 0x00010000
|
||||
CHANGER_PREDISMOUNT_EJECT_REQUIRED = 0x00020000
|
||||
CHANGER_CLEANER_ACCESS_NOT_VALID = 0x00040000
|
||||
CHANGER_PREMOUNT_EJECT_REQUIRED = 0x00080000
|
||||
CHANGER_VOLUME_IDENTIFICATION = 0x00100000
|
||||
CHANGER_VOLUME_SEARCH = 0x00200000
|
||||
CHANGER_VOLUME_ASSERT = 0x00400000
|
||||
CHANGER_VOLUME_REPLACE = 0x00800000
|
||||
CHANGER_VOLUME_UNDEFINE = 0x01000000
|
||||
CHANGER_SERIAL_NUMBER_VALID = 0x04000000
|
||||
CHANGER_DEVICE_REINITIALIZE_CAPABLE = 0x08000000
|
||||
CHANGER_KEYPAD_ENABLE_DISABLE = 0x10000000
|
||||
CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS = 0x20000000
|
||||
|
||||
CHANGER_RESERVED_BIT = 0x80000000
|
||||
CHANGER_PREDISMOUNT_ALIGN_TO_SLOT = 0x80000001
|
||||
CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE = 0x80000002
|
||||
CHANGER_CLEANER_AUTODISMOUNT = 0x80000004
|
||||
CHANGER_TRUE_EXCHANGE_CAPABLE = 0x80000008
|
||||
CHANGER_SLOTS_USE_TRAYS = 0x80000010
|
||||
CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR = 0x80000020
|
||||
CHANGER_CLEANER_OPS_NOT_SUPPORTED = 0x80000040
|
||||
CHANGER_IEPORT_USER_CONTROL_OPEN = 0x80000080
|
||||
CHANGER_IEPORT_USER_CONTROL_CLOSE = 0x80000100
|
||||
CHANGER_MOVE_EXTENDS_IEPORT = 0x80000200
|
||||
CHANGER_MOVE_RETRACTS_IEPORT = 0x80000400
|
||||
|
||||
|
||||
CHANGER_TO_TRANSPORT = 0x01
|
||||
CHANGER_TO_SLOT = 0x02
|
||||
CHANGER_TO_IEPORT = 0x04
|
||||
CHANGER_TO_DRIVE = 0x08
|
||||
LOCK_UNLOCK_IEPORT = 0x01
|
||||
LOCK_UNLOCK_DOOR = 0x02
|
||||
LOCK_UNLOCK_KEYPAD = 0x04
|
||||
LOCK_ELEMENT = 0
|
||||
UNLOCK_ELEMENT = 1
|
||||
EXTEND_IEPORT = 2
|
||||
RETRACT_IEPORT = 3
|
||||
ELEMENT_STATUS_FULL = 0x00000001
|
||||
ELEMENT_STATUS_IMPEXP = 0x00000002
|
||||
ELEMENT_STATUS_EXCEPT = 0x00000004
|
||||
ELEMENT_STATUS_ACCESS = 0x00000008
|
||||
ELEMENT_STATUS_EXENAB = 0x00000010
|
||||
ELEMENT_STATUS_INENAB = 0x00000020
|
||||
ELEMENT_STATUS_PRODUCT_DATA = 0x00000040
|
||||
ELEMENT_STATUS_LUN_VALID = 0x00001000
|
||||
ELEMENT_STATUS_ID_VALID = 0x00002000
|
||||
ELEMENT_STATUS_NOT_BUS = 0x00008000
|
||||
ELEMENT_STATUS_INVERT = 0x00400000
|
||||
ELEMENT_STATUS_SVALID = 0x00800000
|
||||
ELEMENT_STATUS_PVOLTAG = 0x10000000
|
||||
ELEMENT_STATUS_AVOLTAG = 0x20000000
|
||||
ERROR_LABEL_UNREADABLE = 0x00000001
|
||||
ERROR_LABEL_QUESTIONABLE = 0x00000002
|
||||
ERROR_SLOT_NOT_PRESENT = 0x00000004
|
||||
ERROR_DRIVE_NOT_INSTALLED = 0x00000008
|
||||
ERROR_TRAY_MALFUNCTION = 0x00000010
|
||||
ERROR_INIT_STATUS_NEEDED = 0x00000011
|
||||
ERROR_UNHANDLED_ERROR = 0xFFFFFFFF
|
||||
SEARCH_ALL = 0x0
|
||||
SEARCH_PRIMARY = 0x1
|
||||
SEARCH_ALTERNATE = 0x2
|
||||
SEARCH_ALL_NO_SEQ = 0x4
|
||||
SEARCH_PRI_NO_SEQ = 0x5
|
||||
SEARCH_ALT_NO_SEQ = 0x6
|
||||
ASSERT_PRIMARY = 0x8
|
||||
ASSERT_ALTERNATE = 0x9
|
||||
REPLACE_PRIMARY = 0xA
|
||||
REPLACE_ALTERNATE = 0xB
|
||||
UNDEFINE_PRIMARY = 0xC
|
||||
UNDEFINE_ALTERNATE = 0xD
|
||||
USN_PAGE_SIZE = 0x1000
|
||||
USN_REASON_DATA_OVERWRITE = 0x00000001
|
||||
USN_REASON_DATA_EXTEND = 0x00000002
|
||||
USN_REASON_DATA_TRUNCATION = 0x00000004
|
||||
USN_REASON_NAMED_DATA_OVERWRITE = 0x00000010
|
||||
USN_REASON_NAMED_DATA_EXTEND = 0x00000020
|
||||
USN_REASON_NAMED_DATA_TRUNCATION = 0x00000040
|
||||
USN_REASON_FILE_CREATE = 0x00000100
|
||||
USN_REASON_FILE_DELETE = 0x00000200
|
||||
USN_REASON_EA_CHANGE = 0x00000400
|
||||
USN_REASON_SECURITY_CHANGE = 0x00000800
|
||||
USN_REASON_RENAME_OLD_NAME = 0x00001000
|
||||
USN_REASON_RENAME_NEW_NAME = 0x00002000
|
||||
USN_REASON_INDEXABLE_CHANGE = 0x00004000
|
||||
USN_REASON_BASIC_INFO_CHANGE = 0x00008000
|
||||
USN_REASON_HARD_LINK_CHANGE = 0x00010000
|
||||
USN_REASON_COMPRESSION_CHANGE = 0x00020000
|
||||
USN_REASON_ENCRYPTION_CHANGE = 0x00040000
|
||||
USN_REASON_OBJECT_ID_CHANGE = 0x00080000
|
||||
USN_REASON_REPARSE_POINT_CHANGE = 0x00100000
|
||||
USN_REASON_STREAM_CHANGE = 0x00200000
|
||||
USN_REASON_TRANSACTED_CHANGE = 0x00400000
|
||||
USN_REASON_CLOSE = 0x80000000
|
||||
USN_DELETE_FLAG_DELETE = 0x00000001
|
||||
USN_DELETE_FLAG_NOTIFY = 0x00000002
|
||||
USN_DELETE_VALID_FLAGS = 0x00000003
|
||||
USN_SOURCE_DATA_MANAGEMENT = 0x00000001
|
||||
USN_SOURCE_AUXILIARY_DATA = 0x00000002
|
||||
USN_SOURCE_REPLICATION_MANAGEMENT = 0x00000004
|
||||
|
||||
MARK_HANDLE_PROTECT_CLUSTERS = 1
|
||||
MARK_HANDLE_TXF_SYSTEM_LOG = 4
|
||||
MARK_HANDLE_NOT_TXF_SYSTEM_LOG = 8
|
||||
|
||||
VOLUME_IS_DIRTY = 0x00000001
|
||||
VOLUME_UPGRADE_SCHEDULED = 0x00000002
|
||||
VOLUME_SESSION_OPEN = 4
|
||||
|
||||
FILE_PREFETCH_TYPE_FOR_CREATE = 1
|
||||
FILE_PREFETCH_TYPE_FOR_DIRENUM = 2
|
||||
FILE_PREFETCH_TYPE_FOR_CREATE_EX = 3
|
||||
FILE_PREFETCH_TYPE_FOR_DIRENUM_EX = 4
|
||||
FILE_PREFETCH_TYPE_MAX = 4
|
||||
|
||||
FILESYSTEM_STATISTICS_TYPE_NTFS = 1
|
||||
FILESYSTEM_STATISTICS_TYPE_FAT = 2
|
||||
FILE_SET_ENCRYPTION = 0x00000001
|
||||
FILE_CLEAR_ENCRYPTION = 0x00000002
|
||||
STREAM_SET_ENCRYPTION = 0x00000003
|
||||
STREAM_CLEAR_ENCRYPTION = 0x00000004
|
||||
MAXIMUM_ENCRYPTION_VALUE = 0x00000004
|
||||
ENCRYPTION_FORMAT_DEFAULT = 0x01
|
||||
COMPRESSION_FORMAT_SPARSE = 0x4000
|
||||
COPYFILE_SIS_LINK = 0x0001
|
||||
COPYFILE_SIS_REPLACE = 0x0002
|
||||
COPYFILE_SIS_FLAGS = 0x0003
|
||||
|
||||
WMI_DISK_GEOMETRY_GUID = pywintypes.IID("{25007F51-57C2-11D1-A528-00A0C9062910}")
|
||||
GUID_DEVINTERFACE_CDROM = pywintypes.IID("{53F56308-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_FLOPPY = pywintypes.IID("{53F56311-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR = pywintypes.IID("{4D36E978-E325-11CE-BFC1-08002BE10318}")
|
||||
GUID_DEVINTERFACE_COMPORT = pywintypes.IID("{86E0D1E0-8089-11D0-9CE4-08003E301F73}")
|
||||
GUID_DEVINTERFACE_DISK = pywintypes.IID("{53F56307-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_STORAGEPORT = pywintypes.IID("{2ACCFE60-C130-11D2-B082-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_CDCHANGER = pywintypes.IID("{53F56312-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_PARTITION = pywintypes.IID("{53F5630A-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_VOLUME = pywintypes.IID("{53F5630D-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_WRITEONCEDISK = pywintypes.IID("{53F5630C-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_TAPE = pywintypes.IID("{53F5630B-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_DEVINTERFACE_MEDIUMCHANGER = pywintypes.IID("{53F56310-B6BF-11D0-94F2-00A0C91EFB8B}")
|
||||
GUID_SERENUM_BUS_ENUMERATOR = GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR
|
||||
GUID_CLASS_COMPORT = GUID_DEVINTERFACE_COMPORT
|
||||
|
||||
DiskClassGuid = GUID_DEVINTERFACE_DISK
|
||||
CdRomClassGuid = GUID_DEVINTERFACE_CDROM
|
||||
PartitionClassGuid = GUID_DEVINTERFACE_PARTITION
|
||||
TapeClassGuid = GUID_DEVINTERFACE_TAPE
|
||||
WriteOnceDiskClassGuid = GUID_DEVINTERFACE_WRITEONCEDISK
|
||||
VolumeClassGuid = GUID_DEVINTERFACE_VOLUME
|
||||
MediumChangerClassGuid = GUID_DEVINTERFACE_MEDIUMCHANGER
|
||||
FloppyClassGuid = GUID_DEVINTERFACE_FLOPPY
|
||||
CdChangerClassGuid = GUID_DEVINTERFACE_CDCHANGER
|
||||
StoragePortClassGuid = GUID_DEVINTERFACE_STORAGEPORT
|
||||
|
||||
|
||||
IOCTL_STORAGE_CHECK_VERIFY = CTL_CODE(IOCTL_STORAGE_BASE, 0x0200, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_CHECK_VERIFY2 = CTL_CODE(IOCTL_STORAGE_BASE, 0x0200, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_MEDIA_REMOVAL = CTL_CODE(IOCTL_STORAGE_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_EJECT_MEDIA = CTL_CODE(IOCTL_STORAGE_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_LOAD_MEDIA = CTL_CODE(IOCTL_STORAGE_BASE, 0x0203, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_LOAD_MEDIA2 = CTL_CODE(IOCTL_STORAGE_BASE, 0x0203, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_RESERVE = CTL_CODE(IOCTL_STORAGE_BASE, 0x0204, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_RELEASE = CTL_CODE(IOCTL_STORAGE_BASE, 0x0205, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_FIND_NEW_DEVICES = CTL_CODE(IOCTL_STORAGE_BASE, 0x0206, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_EJECTION_CONTROL = CTL_CODE(IOCTL_STORAGE_BASE, 0x0250, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_MCN_CONTROL = CTL_CODE(IOCTL_STORAGE_BASE, 0x0251, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_GET_MEDIA_TYPES = CTL_CODE(IOCTL_STORAGE_BASE, 0x0300, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_GET_MEDIA_TYPES_EX = CTL_CODE(IOCTL_STORAGE_BASE, 0x0301, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER = CTL_CODE(IOCTL_STORAGE_BASE, 0x0304, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_GET_HOTPLUG_INFO = CTL_CODE(IOCTL_STORAGE_BASE, 0x0305, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_SET_HOTPLUG_INFO = CTL_CODE(IOCTL_STORAGE_BASE, 0x0306, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_STORAGE_RESET_BUS = CTL_CODE(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_RESET_DEVICE = CTL_CODE(IOCTL_STORAGE_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_BREAK_RESERVATION = CTL_CODE(IOCTL_STORAGE_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_STORAGE_GET_DEVICE_NUMBER = CTL_CODE(IOCTL_STORAGE_BASE, 0x0420, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_STORAGE_PREDICT_FAILURE = CTL_CODE(IOCTL_STORAGE_BASE, 0x0440, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_GET_DRIVE_GEOMETRY = CTL_CODE(IOCTL_DISK_BASE, 0x0000, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_GET_PARTITION_INFO = CTL_CODE(IOCTL_DISK_BASE, 0x0001, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_SET_PARTITION_INFO = CTL_CODE(IOCTL_DISK_BASE, 0x0002, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GET_DRIVE_LAYOUT = CTL_CODE(IOCTL_DISK_BASE, 0x0003, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_SET_DRIVE_LAYOUT = CTL_CODE(IOCTL_DISK_BASE, 0x0004, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_VERIFY = CTL_CODE(IOCTL_DISK_BASE, 0x0005, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_FORMAT_TRACKS = CTL_CODE(IOCTL_DISK_BASE, 0x0006, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_REASSIGN_BLOCKS = CTL_CODE(IOCTL_DISK_BASE, 0x0007, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_PERFORMANCE = CTL_CODE(IOCTL_DISK_BASE, 0x0008, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_IS_WRITABLE = CTL_CODE(IOCTL_DISK_BASE, 0x0009, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_LOGGING = CTL_CODE(IOCTL_DISK_BASE, 0x000a, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_FORMAT_TRACKS_EX = CTL_CODE(IOCTL_DISK_BASE, 0x000b, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_HISTOGRAM_STRUCTURE = CTL_CODE(IOCTL_DISK_BASE, 0x000c, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_HISTOGRAM_DATA = CTL_CODE(IOCTL_DISK_BASE, 0x000d, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_HISTOGRAM_RESET = CTL_CODE(IOCTL_DISK_BASE, 0x000e, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_REQUEST_STRUCTURE = CTL_CODE(IOCTL_DISK_BASE, 0x000f, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_REQUEST_DATA = CTL_CODE(IOCTL_DISK_BASE, 0x0010, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_PERFORMANCE_OFF = CTL_CODE(IOCTL_DISK_BASE, 0x0018, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_CONTROLLER_NUMBER = CTL_CODE(IOCTL_DISK_BASE, 0x0011, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
SMART_GET_VERSION = CTL_CODE(IOCTL_DISK_BASE, 0x0020, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
SMART_SEND_DRIVE_COMMAND = CTL_CODE(IOCTL_DISK_BASE, 0x0021, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
SMART_RCV_DRIVE_DATA = CTL_CODE(IOCTL_DISK_BASE, 0x0022, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GET_PARTITION_INFO_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0012, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_SET_PARTITION_INFO_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0013, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GET_DRIVE_LAYOUT_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0014, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_SET_DRIVE_LAYOUT_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0015, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_CREATE_DISK = CTL_CODE(IOCTL_DISK_BASE, 0x0016, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GET_LENGTH_INFO = CTL_CODE(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0028, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_REASSIGN_BLOCKS_EX = CTL_CODE(IOCTL_DISK_BASE, 0x0029, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
|
||||
IOCTL_DISK_UPDATE_DRIVE_SIZE = CTL_CODE(IOCTL_DISK_BASE, 0x0032, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GROW_PARTITION = CTL_CODE(IOCTL_DISK_BASE, 0x0034, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_GET_CACHE_INFORMATION = CTL_CODE(IOCTL_DISK_BASE, 0x0035, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_SET_CACHE_INFORMATION = CTL_CODE(IOCTL_DISK_BASE, 0x0036, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
|
||||
OBSOLETE_IOCTL_STORAGE_RESET_BUS = CTL_CODE(IOCTL_STORAGE_BASE, 0x0400, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
OBSOLETE_IOCTL_STORAGE_RESET_DEVICE = CTL_CODE(IOCTL_STORAGE_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
## the original define no longer exists in winioctl.h
|
||||
OBSOLETE_DISK_GET_WRITE_CACHE_STATE = CTL_CODE(IOCTL_DISK_BASE, 0x0037, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_GET_WRITE_CACHE_STATE=OBSOLETE_DISK_GET_WRITE_CACHE_STATE
|
||||
|
||||
|
||||
IOCTL_DISK_DELETE_DRIVE_LAYOUT = CTL_CODE(IOCTL_DISK_BASE, 0x0040, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_UPDATE_PROPERTIES = CTL_CODE(IOCTL_DISK_BASE, 0x0050, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_FORMAT_DRIVE = CTL_CODE(IOCTL_DISK_BASE, 0x00f3, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_DISK_SENSE_DEVICE = CTL_CODE(IOCTL_DISK_BASE, 0x00f8, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_DISK_CHECK_VERIFY = CTL_CODE(IOCTL_DISK_BASE, 0x0200, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_MEDIA_REMOVAL = CTL_CODE(IOCTL_DISK_BASE, 0x0201, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_EJECT_MEDIA = CTL_CODE(IOCTL_DISK_BASE, 0x0202, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_LOAD_MEDIA = CTL_CODE(IOCTL_DISK_BASE, 0x0203, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_RESERVE = CTL_CODE(IOCTL_DISK_BASE, 0x0204, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_RELEASE = CTL_CODE(IOCTL_DISK_BASE, 0x0205, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_FIND_NEW_DEVICES = CTL_CODE(IOCTL_DISK_BASE, 0x0206, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_DISK_GET_MEDIA_TYPES = CTL_CODE(IOCTL_DISK_BASE, 0x0300, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
|
||||
DISK_HISTOGRAM_SIZE = 72
|
||||
HISTOGRAM_BUCKET_SIZE = 8
|
||||
|
||||
IOCTL_CHANGER_GET_PARAMETERS = CTL_CODE(IOCTL_CHANGER_BASE, 0x0000, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_GET_STATUS = CTL_CODE(IOCTL_CHANGER_BASE, 0x0001, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_GET_PRODUCT_DATA = CTL_CODE(IOCTL_CHANGER_BASE, 0x0002, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_SET_ACCESS = CTL_CODE(IOCTL_CHANGER_BASE, 0x0004, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_CHANGER_GET_ELEMENT_STATUS = CTL_CODE(IOCTL_CHANGER_BASE, 0x0005, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = CTL_CODE(IOCTL_CHANGER_BASE, 0x0006, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_SET_POSITION = CTL_CODE(IOCTL_CHANGER_BASE, 0x0007, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_EXCHANGE_MEDIUM = CTL_CODE(IOCTL_CHANGER_BASE, 0x0008, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_MOVE_MEDIUM = CTL_CODE(IOCTL_CHANGER_BASE, 0x0009, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_REINITIALIZE_TRANSPORT = CTL_CODE(IOCTL_CHANGER_BASE, 0x000A, METHOD_BUFFERED, FILE_READ_ACCESS)
|
||||
IOCTL_CHANGER_QUERY_VOLUME_TAGS = CTL_CODE(IOCTL_CHANGER_BASE, 0x000B, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
|
||||
IOCTL_SERIAL_LSRMST_INSERT = CTL_CODE(FILE_DEVICE_SERIAL_PORT,31,METHOD_BUFFERED,FILE_ANY_ACCESS)
|
||||
IOCTL_SERENUM_EXPOSE_HARDWARE = CTL_CODE(FILE_DEVICE_SERENUM,128,METHOD_BUFFERED,FILE_ANY_ACCESS)
|
||||
IOCTL_SERENUM_REMOVE_HARDWARE = CTL_CODE(FILE_DEVICE_SERENUM,129,METHOD_BUFFERED,FILE_ANY_ACCESS)
|
||||
IOCTL_SERENUM_PORT_DESC = CTL_CODE(FILE_DEVICE_SERENUM,130,METHOD_BUFFERED,FILE_ANY_ACCESS)
|
||||
IOCTL_SERENUM_GET_PORT_NAME = CTL_CODE(FILE_DEVICE_SERENUM,131,METHOD_BUFFERED,FILE_ANY_ACCESS)
|
||||
|
||||
## ??? can't find where FILE_DEVICE_AVIO is defined ???
|
||||
## IOCTL_AVIO_ALLOCATE_STREAM = CTL_CODE(FILE_DEVICE_AVIO, 1, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
## IOCTL_AVIO_FREE_STREAM = CTL_CODE(FILE_DEVICE_AVIO, 2, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
## IOCTL_AVIO_MODIFY_STREAM = CTL_CODE(FILE_DEVICE_AVIO, 3, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
|
||||
SERIAL_LSRMST_ESCAPE = 0x00
|
||||
SERIAL_LSRMST_LSR_DATA = 0x01
|
||||
SERIAL_LSRMST_LSR_NODATA = 0x02
|
||||
SERIAL_LSRMST_MST = 0x03
|
||||
SERIAL_IOC_FCR_FIFO_ENABLE = 0x00000001
|
||||
SERIAL_IOC_FCR_RCVR_RESET = 0x00000002
|
||||
SERIAL_IOC_FCR_XMIT_RESET = 0x00000004
|
||||
SERIAL_IOC_FCR_DMA_MODE = 0x00000008
|
||||
SERIAL_IOC_FCR_RES1 = 0x00000010
|
||||
SERIAL_IOC_FCR_RES2 = 0x00000020
|
||||
SERIAL_IOC_FCR_RCVR_TRIGGER_LSB = 0x00000040
|
||||
SERIAL_IOC_FCR_RCVR_TRIGGER_MSB = 0x00000080
|
||||
SERIAL_IOC_MCR_DTR = 0x00000001
|
||||
SERIAL_IOC_MCR_RTS = 0x00000002
|
||||
SERIAL_IOC_MCR_OUT1 = 0x00000004
|
||||
SERIAL_IOC_MCR_OUT2 = 0x00000008
|
||||
SERIAL_IOC_MCR_LOOP = 0x00000010
|
||||
FSCTL_REQUEST_OPLOCK_LEVEL_1 = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_REQUEST_OPLOCK_LEVEL_2 = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 1, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_REQUEST_BATCH_OPLOCK = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 3, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_OPBATCH_ACK_CLOSE_PENDING = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 4, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_OPLOCK_BREAK_NOTIFY = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 5, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_LOCK_VOLUME = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 6, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_UNLOCK_VOLUME = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 7, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_DISMOUNT_VOLUME = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 8, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_IS_VOLUME_MOUNTED = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 10, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_IS_PATHNAME_VALID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 11, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_MARK_VOLUME_DIRTY = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_QUERY_RETRIEVAL_POINTERS = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 14, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_COMPRESSION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_SET_COMPRESSION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 16, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA)
|
||||
FSCTL_MARK_AS_SYSTEM_HIVE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 19, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_OPLOCK_BREAK_ACK_NO_2 = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 20, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_INVALIDATE_VOLUMES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 21, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_QUERY_FAT_BPB = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 22, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_REQUEST_FILTER_OPLOCK = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 23, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_FILESYSTEM_GET_STATISTICS = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 24, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_NTFS_VOLUME_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 25, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_NTFS_FILE_RECORD = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 26, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_VOLUME_BITMAP = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 27, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_RETRIEVAL_POINTERS = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 28, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_MOVE_FILE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 29, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_IS_VOLUME_DIRTY = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 30, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_ALLOW_EXTENDED_DASD_IO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 32, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_FIND_FILES_BY_SID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 35, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_SET_OBJECT_ID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 38, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_GET_OBJECT_ID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 39, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_DELETE_OBJECT_ID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 40, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_SET_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_GET_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_DELETE_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 43, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_ENUM_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 44, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_SECURITY_ID_CHECK = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 45, METHOD_NEITHER, FILE_READ_DATA)
|
||||
FSCTL_READ_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 46, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_SET_OBJECT_ID_EXTENDED = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 47, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_CREATE_OR_GET_OBJECT_ID = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 48, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_SET_SPARSE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 49, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_SET_ZERO_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 50, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_QUERY_ALLOCATED_RANGES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 51, METHOD_NEITHER, FILE_READ_DATA)
|
||||
FSCTL_SET_ENCRYPTION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 53, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_ENCRYPTION_FSCTL_IO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 54, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_WRITE_RAW_ENCRYPTED = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 55, METHOD_NEITHER, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_READ_RAW_ENCRYPTED = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 56, METHOD_NEITHER, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_CREATE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 57, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_READ_FILE_USN_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 58, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_WRITE_USN_CLOSE_RECORD = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 59, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_EXTEND_VOLUME = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 60, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_QUERY_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 61, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_DELETE_USN_JOURNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 62, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_MARK_HANDLE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 63, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_SIS_COPYFILE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 64, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_SIS_LINK_FILES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 65, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA)
|
||||
FSCTL_HSM_MSG = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 66, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA)
|
||||
FSCTL_HSM_DATA = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 68, METHOD_NEITHER, FILE_READ_DATA | FILE_WRITE_DATA)
|
||||
FSCTL_RECALL_FILE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 69, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_READ_FROM_PLEX = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 71, METHOD_OUT_DIRECT, FILE_READ_DATA)
|
||||
FSCTL_FILE_PREFETCH = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 72, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_MAKE_MEDIA_COMPATIBLE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 76, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_SET_DEFECT_MANAGEMENT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 77, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_QUERY_SPARING_INFO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 78, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_QUERY_ON_DISK_VOLUME_INFO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 79, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_SET_VOLUME_COMPRESSION_STATE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 80, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_TXFS_MODIFY_RM = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 81, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_QUERY_RM_INFORMATION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 82, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_TXFS_ROLLFORWARD_REDO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 84, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_ROLLFORWARD_UNDO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 85, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_START_RM = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 86, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_SHUTDOWN_RM = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 87, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_READ_BACKUP_INFORMATION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 88, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_TXFS_WRITE_BACKUP_INFORMATION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 89, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_CREATE_SECONDARY_RM = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 90, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_GET_METADATA_INFO = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 91, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_TXFS_GET_TRANSACTED_VERSION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 92, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_TXFS_CREATE_MINIVERSION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 95, METHOD_BUFFERED, FILE_WRITE_DATA)
|
||||
FSCTL_TXFS_TRANSACTION_ACTIVE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 99, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_SET_ZERO_ON_DEALLOCATION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 101, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_SET_REPAIR = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 102, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_GET_REPAIR = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 103, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_WAIT_FOR_REPAIR = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 104, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_INITIATE_REPAIR = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 106, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_CSC_INTERNAL = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 107, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
FSCTL_SHRINK_VOLUME = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 108, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
|
||||
FSCTL_SET_SHORT_NAME_BEHAVIOR = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 109, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_DFSR_SET_GHOST_HANDLE_STATE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 110, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 120, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_TXFS_LIST_TRANSACTIONS = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 121, METHOD_BUFFERED, FILE_READ_DATA)
|
||||
FSCTL_QUERY_PAGEFILE_ENCRYPTION = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 122, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
|
||||
IOCTL_VOLUME_BASE = ord('V')
|
||||
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS = CTL_CODE(IOCTL_VOLUME_BASE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
IOCTL_VOLUME_IS_CLUSTERED = CTL_CODE(IOCTL_VOLUME_BASE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
|
||||
|
||||
## enums
|
||||
## STORAGE_MEDIA_TYPE
|
||||
DDS_4mm = 32
|
||||
MiniQic = 33
|
||||
Travan = 34
|
||||
QIC = 35
|
||||
MP_8mm = 36
|
||||
AME_8mm = 37
|
||||
AIT1_8mm = 38
|
||||
DLT = 39
|
||||
NCTP = 40
|
||||
IBM_3480 = 41
|
||||
IBM_3490E = 42
|
||||
IBM_Magstar_3590 = 43
|
||||
IBM_Magstar_MP = 44
|
||||
STK_DATA_D3 = 45
|
||||
SONY_DTF = 46
|
||||
DV_6mm = 47
|
||||
DMI = 48
|
||||
SONY_D2 = 49
|
||||
CLEANER_CARTRIDGE = 50
|
||||
CD_ROM = 51
|
||||
CD_R = 52
|
||||
CD_RW = 53
|
||||
DVD_ROM = 54
|
||||
DVD_R = 55
|
||||
DVD_RW = 56
|
||||
MO_3_RW = 57
|
||||
MO_5_WO = 58
|
||||
MO_5_RW = 59
|
||||
MO_5_LIMDOW = 60
|
||||
PC_5_WO = 61
|
||||
PC_5_RW = 62
|
||||
PD_5_RW = 63
|
||||
ABL_5_WO = 64
|
||||
PINNACLE_APEX_5_RW = 65
|
||||
SONY_12_WO = 66
|
||||
PHILIPS_12_WO = 67
|
||||
HITACHI_12_WO = 68
|
||||
CYGNET_12_WO = 69
|
||||
KODAK_14_WO = 70
|
||||
MO_NFR_525 = 71
|
||||
NIKON_12_RW = 72
|
||||
IOMEGA_ZIP = 73
|
||||
IOMEGA_JAZ = 74
|
||||
SYQUEST_EZ135 = 75
|
||||
SYQUEST_EZFLYER = 76
|
||||
SYQUEST_SYJET = 77
|
||||
AVATAR_F2 = 78
|
||||
MP2_8mm = 79
|
||||
DST_S = 80
|
||||
DST_M = 81
|
||||
DST_L = 82
|
||||
VXATape_1 = 83
|
||||
VXATape_2 = 84
|
||||
STK_9840 = 85
|
||||
LTO_Ultrium = 86
|
||||
LTO_Accelis = 87
|
||||
DVD_RAM = 88
|
||||
AIT_8mm = 89
|
||||
ADR_1 = 90
|
||||
ADR_2 = 91
|
||||
STK_9940 = 92
|
||||
|
||||
## STORAGE_BUS_TYPE
|
||||
BusTypeUnknown = 0
|
||||
BusTypeScsi = 1
|
||||
BusTypeAtapi = 2
|
||||
BusTypeAta = 3
|
||||
BusType1394 = 4
|
||||
BusTypeSsa = 5
|
||||
BusTypeFibre = 6
|
||||
BusTypeUsb = 7
|
||||
BusTypeRAID = 8
|
||||
BusTypeiScsi = 9
|
||||
BusTypeSas = 10
|
||||
BusTypeSata = 11
|
||||
BusTypeMaxReserved = 127
|
||||
|
||||
## MEDIA_TYPE
|
||||
Unknown = 0
|
||||
F5_1Pt2_512 = 1
|
||||
F3_1Pt44_512 = 2
|
||||
F3_2Pt88_512 = 3
|
||||
F3_20Pt8_512 = 4
|
||||
F3_720_512 = 5
|
||||
F5_360_512 = 6
|
||||
F5_320_512 = 7
|
||||
F5_320_1024 = 8
|
||||
F5_180_512 = 9
|
||||
F5_160_512 = 10
|
||||
RemovableMedia = 11
|
||||
FixedMedia = 12
|
||||
F3_120M_512 = 13
|
||||
F3_640_512 = 14
|
||||
F5_640_512 = 15
|
||||
F5_720_512 = 16
|
||||
F3_1Pt2_512 = 17
|
||||
F3_1Pt23_1024 = 18
|
||||
F5_1Pt23_1024 = 19
|
||||
F3_128Mb_512 = 20
|
||||
F3_230Mb_512 = 21
|
||||
F8_256_128 = 22
|
||||
F3_200Mb_512 = 23
|
||||
F3_240M_512 = 24
|
||||
F3_32M_512 = 25
|
||||
|
||||
## PARTITION_STYLE
|
||||
PARTITION_STYLE_MBR = 0
|
||||
PARTITION_STYLE_GPT = 1
|
||||
PARTITION_STYLE_RAW = 2
|
||||
|
||||
## DETECTION_TYPE
|
||||
DetectNone = 0
|
||||
DetectInt13 = 1
|
||||
DetectExInt13 = 2
|
||||
|
||||
## DISK_CACHE_RETENTION_PRIORITY
|
||||
EqualPriority = 0
|
||||
KeepPrefetchedData = 1
|
||||
KeepReadData = 2
|
||||
|
||||
## DISK_WRITE_CACHE_STATE - ?????? this enum has disappeared from winioctl.h in windows 2003 SP1 sdk ??????
|
||||
DiskWriteCacheNormal = 0
|
||||
DiskWriteCacheForceDisable = 1
|
||||
DiskWriteCacheDisableNotSupported = 2
|
||||
|
||||
## BIN_TYPES
|
||||
RequestSize = 0
|
||||
RequestLocation = 1
|
||||
|
||||
## CHANGER_DEVICE_PROBLEM_TYPE
|
||||
DeviceProblemNone = 0
|
||||
DeviceProblemHardware = 1
|
||||
DeviceProblemCHMError = 2
|
||||
DeviceProblemDoorOpen = 3
|
||||
DeviceProblemCalibrationError = 4
|
||||
DeviceProblemTargetFailure = 5
|
||||
DeviceProblemCHMMoveError = 6
|
||||
DeviceProblemCHMZeroError = 7
|
||||
DeviceProblemCartridgeInsertError = 8
|
||||
DeviceProblemPositionError = 9
|
||||
DeviceProblemSensorError = 10
|
||||
DeviceProblemCartridgeEjectError = 11
|
||||
DeviceProblemGripperError = 12
|
||||
DeviceProblemDriveError = 13
|
||||
1299
Pywin32/lib/x32/win32/lib/winnt.py
Normal file
140
Pywin32/lib/x32/win32/lib/winperf.py
Normal file
@@ -0,0 +1,140 @@
|
||||
# Generated by h2py from winperf.h
|
||||
PERF_DATA_VERSION = 1
|
||||
PERF_DATA_REVISION = 1
|
||||
PERF_NO_INSTANCES = -1
|
||||
PERF_SIZE_DWORD = 0x00000000
|
||||
PERF_SIZE_LARGE = 0x00000100
|
||||
PERF_SIZE_ZERO = 0x00000200
|
||||
PERF_SIZE_VARIABLE_LEN = 0x00000300
|
||||
PERF_TYPE_NUMBER = 0x00000000
|
||||
PERF_TYPE_COUNTER = 0x00000400
|
||||
PERF_TYPE_TEXT = 0x00000800
|
||||
PERF_TYPE_ZERO = 0x00000C00
|
||||
PERF_NUMBER_HEX = 0x00000000
|
||||
PERF_NUMBER_DECIMAL = 0x00010000
|
||||
PERF_NUMBER_DEC_1000 = 0x00020000
|
||||
PERF_COUNTER_VALUE = 0x00000000
|
||||
PERF_COUNTER_RATE = 0x00010000
|
||||
PERF_COUNTER_FRACTION = 0x00020000
|
||||
PERF_COUNTER_BASE = 0x00030000
|
||||
PERF_COUNTER_ELAPSED = 0x00040000
|
||||
PERF_COUNTER_QUEUELEN = 0x00050000
|
||||
PERF_COUNTER_HISTOGRAM = 0x00060000
|
||||
PERF_TEXT_UNICODE = 0x00000000
|
||||
PERF_TEXT_ASCII = 0x00010000
|
||||
PERF_TIMER_TICK = 0x00000000
|
||||
PERF_TIMER_100NS = 0x00100000
|
||||
PERF_OBJECT_TIMER = 0x00200000
|
||||
PERF_DELTA_COUNTER = 0x00400000
|
||||
PERF_DELTA_BASE = 0x00800000
|
||||
PERF_INVERSE_COUNTER = 0x01000000
|
||||
PERF_MULTI_COUNTER = 0x02000000
|
||||
PERF_DISPLAY_NO_SUFFIX = 0x00000000
|
||||
PERF_DISPLAY_PER_SEC = 0x10000000
|
||||
PERF_DISPLAY_PERCENT = 0x20000000
|
||||
PERF_DISPLAY_SECONDS = 0x30000000
|
||||
PERF_DISPLAY_NOSHOW = 0x40000000
|
||||
PERF_COUNTER_COUNTER = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)
|
||||
PERF_COUNTER_TIMER = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)
|
||||
PERF_COUNTER_QUEUELEN_TYPE = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_LARGE_QUEUELEN_TYPE = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_QUEUELEN |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_BULK_COUNT = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_PER_SEC)
|
||||
PERF_COUNTER_TEXT = \
|
||||
(PERF_SIZE_VARIABLE_LEN | PERF_TYPE_TEXT | PERF_TEXT_UNICODE |\
|
||||
PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_RAWCOUNT = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\
|
||||
PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_LARGE_RAWCOUNT = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_DECIMAL |\
|
||||
PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_RAWCOUNT_HEX = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\
|
||||
PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_LARGE_RAWCOUNT_HEX = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_NUMBER | PERF_NUMBER_HEX |\
|
||||
PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_SAMPLE_FRACTION = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\
|
||||
PERF_DELTA_COUNTER | PERF_DELTA_BASE | PERF_DISPLAY_PERCENT)
|
||||
PERF_SAMPLE_COUNTER = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_NODATA = \
|
||||
(PERF_SIZE_ZERO | PERF_DISPLAY_NOSHOW)
|
||||
PERF_COUNTER_TIMER_INV = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_TICK | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER | \
|
||||
PERF_DISPLAY_PERCENT)
|
||||
PERF_SAMPLE_BASE = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\
|
||||
PERF_DISPLAY_NOSHOW |\
|
||||
0x00000001)
|
||||
PERF_AVERAGE_TIMER = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\
|
||||
PERF_DISPLAY_SECONDS)
|
||||
PERF_AVERAGE_BASE = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\
|
||||
PERF_DISPLAY_NOSHOW |\
|
||||
0x00000002)
|
||||
PERF_AVERAGE_BULK = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\
|
||||
PERF_DISPLAY_NOSHOW)
|
||||
PERF_100NSEC_TIMER = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_DISPLAY_PERCENT)
|
||||
PERF_100NSEC_TIMER_INV = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_TIMER_100NS | PERF_DELTA_COUNTER | PERF_INVERSE_COUNTER |\
|
||||
PERF_DISPLAY_PERCENT)
|
||||
PERF_COUNTER_MULTI_TIMER = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_DELTA_COUNTER | PERF_TIMER_TICK | PERF_MULTI_COUNTER |\
|
||||
PERF_DISPLAY_PERCENT)
|
||||
PERF_COUNTER_MULTI_TIMER_INV = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_RATE |\
|
||||
PERF_DELTA_COUNTER | PERF_MULTI_COUNTER | PERF_TIMER_TICK |\
|
||||
PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)
|
||||
PERF_COUNTER_MULTI_BASE = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\
|
||||
PERF_MULTI_COUNTER | PERF_DISPLAY_NOSHOW)
|
||||
PERF_100NSEC_MULTI_TIMER = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\
|
||||
PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\
|
||||
PERF_DISPLAY_PERCENT)
|
||||
PERF_100NSEC_MULTI_TIMER_INV = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_DELTA_COUNTER |\
|
||||
PERF_COUNTER_RATE | PERF_TIMER_100NS | PERF_MULTI_COUNTER |\
|
||||
PERF_INVERSE_COUNTER | PERF_DISPLAY_PERCENT)
|
||||
PERF_RAW_FRACTION = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_FRACTION |\
|
||||
PERF_DISPLAY_PERCENT)
|
||||
PERF_RAW_BASE = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_BASE |\
|
||||
PERF_DISPLAY_NOSHOW |\
|
||||
0x00000003)
|
||||
PERF_ELAPSED_TIME = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_ELAPSED |\
|
||||
PERF_OBJECT_TIMER | PERF_DISPLAY_SECONDS)
|
||||
PERF_COUNTER_HISTOGRAM_TYPE = -2147483648 # 0x80000000
|
||||
PERF_COUNTER_DELTA = \
|
||||
(PERF_SIZE_DWORD | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\
|
||||
PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_COUNTER_LARGE_DELTA = \
|
||||
(PERF_SIZE_LARGE | PERF_TYPE_COUNTER | PERF_COUNTER_VALUE |\
|
||||
PERF_DELTA_COUNTER | PERF_DISPLAY_NO_SUFFIX)
|
||||
PERF_DETAIL_NOVICE = 100
|
||||
PERF_DETAIL_ADVANCED = 200
|
||||
PERF_DETAIL_EXPERT = 300
|
||||
PERF_DETAIL_WIZARD = 400
|
||||
PERF_NO_UNIQUE_ID = -1
|
||||
23
Pywin32/lib/x32/win32/lib/winxptheme.py
Normal file
@@ -0,0 +1,23 @@
|
||||
"""A useful wrapper around the "_winxptheme" module.
|
||||
Unlike _winxptheme, this module will load on any version of Windows.
|
||||
|
||||
If _winxptheme is not available, then this module will have only 2 functions -
|
||||
IsAppThemed() and IsThemeActive, which will both always return False.
|
||||
|
||||
If _winxptheme is available, this module will have all methods in that module,
|
||||
including real implementations of IsAppThemed() and IsThemeActive().
|
||||
"""
|
||||
|
||||
import win32api
|
||||
try:
|
||||
win32api.FreeLibrary(win32api.LoadLibrary("Uxtheme.dll"))
|
||||
# Life is good, everything is available.
|
||||
from _winxptheme import *
|
||||
except win32api.error:
|
||||
# Probably not running XP.
|
||||
def IsAppThemed():
|
||||
return False
|
||||
def IsThemeActive():
|
||||
return False
|
||||
|
||||
del win32api
|
||||
BIN
Pywin32/lib/x32/win32/libs/pywintypes.lib
Normal file
30
Pywin32/lib/x32/win32/license.txt
Normal file
@@ -0,0 +1,30 @@
|
||||
Unless stated in the specfic source file, this work is
|
||||
Copyright (c) 1994-2008, Mark Hammond
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither name of Mark Hammond nor the name of contributors may be used
|
||||
to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
|
||||
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
BIN
Pywin32/lib/x32/win32/mmapfile.pyd
Normal file
BIN
Pywin32/lib/x32/win32/odbc.pyd
Normal file
BIN
Pywin32/lib/x32/win32/perfmon.pyd
Normal file
BIN
Pywin32/lib/x32/win32/perfmondata.dll
Normal file
BIN
Pywin32/lib/x32/win32/pythoncom33.dll
Normal file
BIN
Pywin32/lib/x32/win32/pythonservice.exe
Normal file
BIN
Pywin32/lib/x32/win32/pywintypes33.dll
Normal file
BIN
Pywin32/lib/x32/win32/servicemanager.pyd
Normal file
BIN
Pywin32/lib/x32/win32/timer.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win2kras.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32api.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32clipboard.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32console.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32cred.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32crypt.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32event.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32evtlog.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32file.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32gui.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32help.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32inet.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32job.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32lz.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32net.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32pdh.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32pipe.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32print.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32process.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32profile.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32ras.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32security.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32service.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32trace.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32transaction.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32ts.pyd
Normal file
BIN
Pywin32/lib/x32/win32/win32wnet.pyd
Normal file
BIN
Pywin32/lib/x32/win32/winxpgui.pyd
Normal file
104
Pywin32/lib/x32/win32com/HTML/GeneratedSupport.html
Normal file
@@ -0,0 +1,104 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>Generated Python COM Support</TITLE>
|
||||
<META NAME="Version" CONTENT="8.0.3410">
|
||||
<META NAME="Date" CONTENT="10/11/96">
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY TEXT="#000000" LINK="#0000ff" VLINK="#800080" BGCOLOR="#ffffff">
|
||||
|
||||
<P><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></P>
|
||||
<H1>Generated Python COM Support</H1>
|
||||
<P>This file describes how the Python COM extensions support "generated files". The information contained here is for expert Python users, and people who need to take advantage of the advanced features of the support. More general information is available in the <A HREF="QuickStartClientCom.html">Quick Start to Client Side COM</A> documentation.</P>
|
||||
<H2>Introduction</H2>
|
||||
<P>Generated Python COM support means that a .py file exists behind a particular COM object. This .py file is created by a generation process from a COM type library.</P>
|
||||
<P>This documentation talks about the process of the creation of the .py files.</P>
|
||||
<H2>Design Goals</H2>
|
||||
<P>The main design goal is that the Python programmer need not know much about the type library they wish to work with. They need not know the name of a specific Python module to use a type library. COM uses an IID, version and LCID to identify a type library. Therefore, the Python programmer only need know this information to obtain a Python module.</P>
|
||||
<H2>How to generate support files</H2>
|
||||
<P>Support files can be generated either "off-line" by the makepy utility, or in custom Python code.</P>
|
||||
<P>Using makepy is in many ways far simpler - you simply pick the type library and you are ready to go! The <A HREF="QuickStartClientCom.html">Quick Start to Client Side COM</A> documentation describes this process.</P>
|
||||
<P>Often however, you will want to use code to ensure the type library has been processed. This document describes that process.</P>
|
||||
<H2>Usage</H2>
|
||||
<P>The win32com.client.gencache module implements all functionality. As described above, if you wish to generate support from code, you need to know the IID, version and LCID of the type library.</P>
|
||||
<P>The following functions are defined. The best examples of their usage is probably in the Pythonwin OCX Demos, and the COM Test Suite (particularly testMSOffice.py)</P>
|
||||
<P>Note that the gencache.py file supports being run from the command line, and provides some utilities for managing the cache. Run the file to see usage options.</P>
|
||||
<H2>Using makepy to help with the runtime generation</H2>
|
||||
<P>makepy supports a "-i" option, to print information about a type library. When you select a type library, makepy will print out 2 lines of code that you cant paste into your application. This will then allow your module to generate the makepy .py file at runtime, but will only take you a few seconds!</P>
|
||||
<H2>win32com.client.gencache functions</H2>
|
||||
<H3>def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None):</H3>
|
||||
<P>Generate support for a type library.</P>
|
||||
<P>Given the IID, LCID and version information for a type library, generate and import the necessary support files.</P>
|
||||
<B><P>Returns</P>
|
||||
</B><P>The Python module. No exceptions are caught.</P>
|
||||
<B><P>Params</P>
|
||||
</B><I><P>typelibCLSID</I><BR>
|
||||
IID of the type library.</P>
|
||||
<I><P>major</I><BR>
|
||||
Integer major version.</P>
|
||||
<I><P>minor</I><BR>
|
||||
Integer minor version.</P>
|
||||
<I><P>lcid</I><BR>
|
||||
Integer LCID for the library.</P>
|
||||
<I><P>progressInstance</I><BR>
|
||||
A class instance to use as the progress indicator, or None to use the default GUI one. </P>
|
||||
<H3>def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None):</H3>
|
||||
<P>Ensure Python support is loaded for a type library, generating if necessary.</P>
|
||||
<P>Given the IID, LCID and version information for a type library, check and if necessary generate, then import the necessary support files.</P>
|
||||
<P>Returns:</P>
|
||||
<P>The Python module. No exceptions are caught during the generate process.</P>
|
||||
<B><P>Params</P>
|
||||
</B><I><P>typelibCLSID</I><BR>
|
||||
IID of the type library.</P>
|
||||
<I><P>major</I><BR>
|
||||
Integer major version.</P>
|
||||
<I><P>minor</I><BR>
|
||||
Integer minor version.</P>
|
||||
<I><P>lcid</I><BR>
|
||||
Integer LCID for the library.</P>
|
||||
<I><P>progressInstance</I><BR>
|
||||
A class instance to use as the progress indicator, or None to use the default GUI one. </P>
|
||||
<P> </P>
|
||||
<H3>def GetClassForProgID(<I>progid</I>):</H3>
|
||||
<P>Get a Python class for a Program ID</P>
|
||||
<P>Given a Program ID, return a Python class which wraps the COM object</P>
|
||||
<B><P>Returns</P>
|
||||
</B><P>The Python class, or None if no module is available.</P>
|
||||
<B><P>Params</P>
|
||||
</B><I><P>progid<BR>
|
||||
</I>A COM ProgramID or IID (eg, "Word.Application")</P>
|
||||
<P> </P>
|
||||
<H3>def GetModuleForProgID(progid):</H3>
|
||||
<P>Get a Python module for a Program ID</P>
|
||||
<P>Given a Program ID, return a Python module which contains the class which wraps the COM object.</P>
|
||||
<B><P>Returns</P>
|
||||
</B><P>The Python module, or None if no module is available.</P>
|
||||
<B><P>Params:</P>
|
||||
</B><I><P>progid <BR>
|
||||
</I>A COM ProgramID or IID (eg, "Word.Application")</P>
|
||||
<P> </P>
|
||||
<H3>def GetModuleForCLSID(clsid):</H3>
|
||||
<P>Get a Python module for a CLSID</P>
|
||||
<P>Given a CLSID, return a Python module which contains the class which wraps the COM object.</P>
|
||||
<B><P>Returns</P>
|
||||
</B><P>The Python module, or None if no module is available.</P>
|
||||
<B><P>Params</P>
|
||||
</B><I><P>progid<BR>
|
||||
</I>A COM CLSID (ie, not the description)</P>
|
||||
<P> </P>
|
||||
<H3>def GetModuleForTypelib(typelibCLSID, lcid, major, minor):</H3>
|
||||
<P>Get a Python module for a type library ID</P>
|
||||
<B><P>Returns</P>
|
||||
</B><P>An imported Python module, else None</P>
|
||||
<B><P>Params</B>:</P>
|
||||
<I><P>typelibCLSID</I><BR>
|
||||
IID of the type library.</P>
|
||||
<I><P>major</I><BR>
|
||||
Integer major version.</P>
|
||||
<I><P>minor</I><BR>
|
||||
Integer minor version</P>
|
||||
<I><P>lcid</I><BR>
|
||||
Integer LCID for the library.</P></BODY>
|
||||
</HTML>
|
||||
90
Pywin32/lib/x32/win32com/HTML/PythonCOM.html
Normal file
@@ -0,0 +1,90 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>Untitled</TITLE>
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY LINK="#0000ff" VLINK="#800080">
|
||||
|
||||
<H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
|
||||
<H1>Python and COM - Implementation Details </H1>
|
||||
<H2>Introduction </H2>
|
||||
<P>This document describes the technical implementation of the COM support in Python. It is primarily concerned with the underlying C++ interface to COM, although general Python issues are touched. </P>
|
||||
<P>This document is targeted at people who wish to maintain/enhance the standard COM support (typically by writing extension modules). For information on using Python and COM from a Python programmers perspective, please see the <A HREF="docindex.html">documentation index</A>. </P>
|
||||
<H2>General COM Support. </H2>
|
||||
<P>COM support in Python can be broken into 2 general areas - C++ support, and Python support. C++ support exists in the core PythonCOM module (plus any PythonCOM extension modules). Python support exists in the .py files that accompany the core module. </P>
|
||||
<H2>Naming Conventions </H2>
|
||||
<P>The naming conventions used by Python code will be: </P>
|
||||
|
||||
<UL>
|
||||
<LI>The Python "New Import" (ni) module will be used, allowing packages, or nested modules. </LI>
|
||||
<LI>The package name will be "win32com". </LI>
|
||||
<LI>The core module name will be "pythoncom" (ie, "win32com.pythoncom") </LI></UL>
|
||||
|
||||
<P>The rest of the naming conventions are yet to be worked out. </P>
|
||||
<H2>Core COM support. </H2>
|
||||
<P>This section is involved with the core C++ support in "pythoncom". </P>
|
||||
<P>The organisation of PythonCOM support falls into 3 discrete areas. </P>
|
||||
<H3>COM Client Support </H3>
|
||||
<P>This is the ability to manipulate other COM objects via their exposed interface. This includes use of IDispatch (eg using Python to start Microsoft Word, open a file, and print it.) but also all client side IUnknown derived objects fall into this category, including ITypeLib and IConnectionPoint support. </P>
|
||||
<H3>COM Server Support </H3>
|
||||
<P>This is ability for Python to create COM Servers, which can be manipulated by another COM client. This includes server side IDispatch (eg, Visual Basic starting a Python interpreter, and asking it to evaluate some code) but also all supported server side IUnknown derived classes. </P>
|
||||
<H3>Python/COM type and value conversion </H3>
|
||||
<P>This is internal code used by the above areas to managed the conversion to and from Python/COM types and values. This includes code to convert an arbitrary Python object into a COM variant, manages return types, and a few other helpers. </P>
|
||||
<H2>COM Structures and Python Types </H2>
|
||||
<P>OLE supports many C level structures for the COM API, which must be mapped to Python. </P>
|
||||
<H3>VARIANT </H3>
|
||||
<P>Variants are never exposed as such to Python programs. The internal framework always converts all variants to and from Python types. In some cases, type descriptions may be used, which force specific mappings, although in general the automatic conversion works fine. </P>
|
||||
<H3>TYPEDESC </H3>
|
||||
<P>A tuple, containing the elements of the C union. This union will be correctly decoded by the support code. </P>
|
||||
<H3>ELEMDESC </H3>
|
||||
<P>A tuple of TYPEDESC and PARAMDESC objects. </P>
|
||||
<H3>FUNCDESC </H3>
|
||||
<P>A funcdesc is a large and unwieldy tuple. Documentation to be supplied. </P>
|
||||
<H3>IID/CLSID </H3>
|
||||
<P>A native IID in Python is a special type, defined in pythoncom. Whenever a CLSID/IID is required, typically either an object, a tuple of type "iii(iiiiiiii)" or string can be used. </P>
|
||||
<P>Helper functions are available to convert to and from IID/CLSID and strings. </P>
|
||||
<H2>COM Framework </H2>
|
||||
<P>Both client and server side support have a specific framework in place to assist in supporting the widest possible set of interfaces. The framework allows external extension DLLs to be written, which extend the interfaces available to the Python user. </P>
|
||||
<P>This allows the core PythonCOM module to support a wide set of common interfaces, and other extensions to support anything obscure. </P>
|
||||
<H3>Client Framework </H3>
|
||||
<H4>QueryInterface and Types </H4>
|
||||
<P>When the only support required by Python is IDispatch, everything is simple - every object returned from QueryInterface is a PyIDispatch object. But this does not extend to other types, such as ITypeLib, IConnectionPoint etc., which are required for full COM support. </P>
|
||||
<P>For example, consider the following C++ psuedo-code: </P>
|
||||
<CODE><P>IConnectionPoint *conPt;<BR>
|
||||
someIDispatch->QueryInterface(IID_IConnectionPoint, (void **)&conPt);<BR>
|
||||
// Note the IID_ and type of the * could be anything!</CODE> </P>
|
||||
<P>This cast, and knowledge of a specific IID_* to type must be simulated in Python. </P>
|
||||
<P>Python/COM will therefore maintain a map of UID's to Python type objects. Whenever QueryInterface is called, Python will lookup this map, to determine if the object type is supported. If the object is supported, then an object of that type will be returned. If the object is not supported, then a PyIUnknown object will be returned. </P>
|
||||
<P>Note that PyIDispatch will be supported by the core engine. Therefore: </P>
|
||||
<CODE><P>>>> disp=someobj.QueryInterface(win32com.IID_Dispatch) </P>
|
||||
</CODE><P>will return a PyIDispatch object, whereas </P>
|
||||
<CODE><P>>>> unk=someobj.QueryInterface(SomeUnknownIID) # returns PyIUnknown<BR>
|
||||
>>> disp=unk.QueryInterface(win32com.IID_Dispatch) <BR>
|
||||
>>> unk.Release() # Clean up now, rather than waiting for unk death.</CODE> </P>
|
||||
<P>Is needed to convert to an IDispatch object. </P>
|
||||
<H4>Core Support </H4>
|
||||
<P>The core COM support module will support the IUnknown, IDispatch, ITypeInfo, ITypeLib and IConnectionPointContainer and IConnectionPoint interfaces. This implies the core COM module supports 6 different OLE client object types, mapped to the 6 IID_*'s representing the objects. (The IConnection* objects allow for Python to repsond to COM events) </P>
|
||||
<P>A psuedo-inheritance scheme is used. The Python types are all derived from the Python IUnknown type (PyIUnknown). Therefore all IUnknown methods are automatically available to all types, just as it should be. The PyIUnknown type manages all object reference counts and destruction. </P>
|
||||
<H4>Extensibility </H4>
|
||||
<P>To provide the above functionality, a Python map is provided, which maps from a GUID to a Python type object. </P>
|
||||
<P>The advantage of this scheme is an external extension modules can hook into the core support. For example, imagine the following code: </P>
|
||||
<CODE><P>>>> import myextracom # external .pyd supporting some interface.<BR>
|
||||
# myextracom.pyd will do the equivilent of</CODE> </P>
|
||||
<CODE><P># pythoncom.mapSupportedTypes(myextracom.IID_Extra, myextracom.ExtraType) <BR>
|
||||
>>> someobj.QueryInterface(myextracom.IID_Extra)</CODE> </P>
|
||||
<P>Would correctly return an object defined in the extension module. </P>
|
||||
<H3>Server Framework </H3>
|
||||
<H4>General Framework </H4>
|
||||
<P>A server framework has been put in place which provides the following features: </P>
|
||||
<P>All Interfaces provide VTBL support - this means that the Servers exposed by Python are callable from C++ and other compiled languages. </P>
|
||||
<P>Supports full "inproc" servers. This means that no external .EXE is needed making Python COM servers available in almost all cases. </P>
|
||||
<P>An extensible model which allows for extension modules to provide server support for interfaces defined in that module. A map is provided which maps from a GUID to a function pointer which creates the interface. </P>
|
||||
<H3>Python and Variant Types Conversion </H3>
|
||||
<P>In general, Python and COM are both "type-less". COM is type-less via the VARIANT object, which supports many types, and Python is type-less due to its object model. </P>
|
||||
<P>There are a number of areas where Python and OLE clash. </P>
|
||||
<H4>Parameters and conversions. </H4>
|
||||
<P>For simple calls, there are 2 helpers available which will convert to and from PyObjects and VARIANTS. The call to convert a Python object to a VARIANT is simple in that it returns a VARIANT of the most appropriate type for the Python object - ie, the type of the Python object determines the resulting VARIANT type. </P>
|
||||
<P>There are also more complex conversion routines available, wrapped in a C++ helper class. Typically, these helpers are used whenever a specific variant type is known (eg, when an ITypeInfo is available for the object being used). In this case, all efforts are made to convert the Python type to the requested variant type - ie, in this situation, the VARIANT type determines how the Python object is coerced. In addition, this code supports the use of "ByRef" and pointer paramaters, providing and freeing any buffers necessary for the call. </P></BODY>
|
||||
</HTML>
|
||||
82
Pywin32/lib/x32/win32com/HTML/QuickStartClientCom.html
Normal file
@@ -0,0 +1,82 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>Quick Start to Client side COM and Python</TITLE>
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY LINK="#0000ff" VLINK="#800080">
|
||||
|
||||
<H1>Quick Start to Client side COM and Python</H1>
|
||||
<H2>Introduction</H2>
|
||||
<P>This documents how to quickly start using COM from Python. It is not a thorough discussion of the COM system, or of the concepts introduced by COM.</P>
|
||||
<P>Other good information on COM can be found in various conference tutorials - please see <A HREF="http://starship.python.net/crew/mhammond/conferences">the collection of Mark's conference tutorials</A></P>
|
||||
<P>For information on implementing COM objects using Python, please see <A HREF="http://www.python.org/windows/win32com/QuickStartServerCom.html">a Quick Start to Server side COM and Python</A></P>
|
||||
<P>In this document we discuss the following topics:</P>
|
||||
|
||||
<UL>
|
||||
<LI><A HREF="#Using">Using a COM object from Python</A> </LI>
|
||||
<LI><A HREF="#WhatObjects">How do I know which objects are available?</A> </LI>
|
||||
<LI><A HREF="#StaticDispatch">Static Dispatch/Type Safe objects (using the new improved makepy.py)</A></LI>
|
||||
<LI><A HREF="#UsingComConstants">Using COM Constants with makepy.</A></LI></UL>
|
||||
|
||||
<H2>Quick Start</H2>
|
||||
<H3><A NAME="Using">To use a COM object from Python</A></H3>
|
||||
<CODE><P>import win32com.client<BR>
|
||||
o = win32com.client.Dispatch("Object.Name")<BR>
|
||||
o.Method()<BR>
|
||||
o.property = "New Value"<BR>
|
||||
print o.property</P>
|
||||
</CODE><P>Example</P>
|
||||
<CODE><P>o = win32com.client.Dispatch("Excel.Application")<BR>
|
||||
o.Visible = 1<BR>
|
||||
o.Workbooks.Add() # for office 97 <20> 95 a bit different!<BR>
|
||||
o.Cells(1,1).Value = "Hello"</CODE> </P>
|
||||
<P>And we will see the word "Hello" appear in the top cell. </P>
|
||||
<H3><A NAME="WhatObjects">How do I know which methods and properties are available?</A></H3>
|
||||
<P>Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are just expected to know.</P>
|
||||
<H4>The Python COM browser</H4>
|
||||
<P>PythonCOM comes with a basic COM browser that may show you the information you need. Note that this package requires Pythonwin (ie, the MFC GUI environment) to be installed for this to work.</P>
|
||||
<P>There are far better COM browsers available - I tend to use the one that comes with MSVC, or this one!</P>
|
||||
<P>To run the browser, simply select it from the Pythonwin <I>Tools</I> menu, or double-click on the file <I>win32com\client\combrowse.py</I></P>
|
||||
<H2><A NAME="StaticDispatch">Static Dispatch (or Type Safe) objects</A></H2>
|
||||
<P>In the above examples, if we printed the '<CODE>repr(o)</CODE>' object above, it would have resulted in</P>
|
||||
<CODE><P><COMObject Excel.Application></P>
|
||||
</CODE><P>This reflects that the object is a generic COM object that Python has no special knowledge of (other than the name you used to create it!). This is known as a "dynamic dispatch" object, as all knowledge is built dynamically. The win32com package also has the concept of <I>static dispatch</I> objects, which gives Python up-front knowledge about the objects that it is working with (including arguments, argument types, etc)</P>
|
||||
<P>In a nutshell, Static Dispatch involves the generation of a .py file that contains support for the specific object. For more overview information, please see the documentation references above.</P>
|
||||
<P>The generation and management of the .py files is somewhat automatic, and involves one of 2 steps:</P>
|
||||
|
||||
<UL>
|
||||
<LI>Using <I>makepy.py</I> to select a COM library. This process is very similar to Visual Basic, where you select from a list of all objects installed on your system, and once selected the objects are magically useable. </LI></UL>
|
||||
|
||||
<P>or</P>
|
||||
|
||||
<UL>
|
||||
<LI>Use explicit code to check for, and possibly generate, support at run-time. This is very powerful, as it allows the developer to avoid ensuring the user has selected the appropriate type library. This option is extremely powerful for OCX users, as it allows Python code to sub-class an OCX control, but the actual sub-class can be generated at run-time. Use <I>makepy.py</I> with a </I>-i</I> option to see how to include this support in your Python code.</LI></UL>
|
||||
|
||||
<P>The <I>win32com.client.gencache</I> module manages these generated files. This module has <A HREF="GeneratedSupport.html">some documentation of its own</A>, but you probably don't need to know the gory details!</P>
|
||||
<H3>How do I get at the generated module?</H3>
|
||||
<P>You will notice that the generated file name is long and cryptic - obviously not designed for humans to work with! So how do you get at the module object for the generated code?</P>
|
||||
<P>Hopefully, the answer is <I>you shouldn't need to</I>. All generated file support is generally available directly via <I>win32com.client.Dispatch</I> and <I>win32com.client.constants</I>. But should you ever really need the Python module object, the win32com.client.gencache module has functions specifically for this. The functions GetModuleForCLSID and GetModuleForProgID both return Python module objects that you can use in your code. See the docstrings in the gencache code for more details.</P>
|
||||
<H3>To generate Python Sources supporting a COM object</H3>
|
||||
<H4>Example using Microsoft Office 97.</H4>
|
||||
<P>Either:</P>
|
||||
|
||||
<UL>
|
||||
<LI>Run '<CODE>win32com\client\makepy.py</CODE>' (eg, run it from the command window, or double-click on it) and a list will be presented. Select the Type Library '<CODE>Microsoft Word 8.0 Object Library</CODE>' </LI>
|
||||
<LI>From a command prompt, run the command '<CODE>makepy.py "Microsoft Word 8.0 Object Library"</CODE>' (include the double quotes). This simply avoids the selection process. </LI>
|
||||
<LI>If you desire, you can also use explicit code to generate it just before you need to use it at runtime. Run <CODE>'makepy.py -i "Microsoft Word 8.0 Object Library"</CODE>' (include the double quotes) to see how to do this.</LI></UL>
|
||||
|
||||
<P>And that is it! Nothing more needed. No special import statements needed! Now, you simply need say</P>
|
||||
<CODE><P>>>> import win32com.client</P>
|
||||
<P>>>> w=win32com.client.Dispatch("Word.Application")</P>
|
||||
<P>>>> w.Visible=1</P>
|
||||
<P>>>> w</P>
|
||||
<P><win32com.gen_py.Microsoft Word 8.0 Object Library._Application></P>
|
||||
</CODE><P>Note that now Python knows the explicit type of the object.</P>
|
||||
<H3><A NAME="UsingComConstants">Using COM Constants</A></H3>
|
||||
<P>Makepy automatically installs all generated constants from a type library in an object called <I>win32com.clients.constants</I>. You do not need to do anything special to make these constants work, other than create the object itself (ie, in the example above, the constants relating to <I>Word</I> would automatically be available after the <CODE>w=win32com.client.Dispatch("Word.Application</CODE>") statement<CODE>.</P>
|
||||
</CODE><P>For example, immediately after executing the code above, you could execute the following:</P>
|
||||
<CODE><P>>>> w.WindowState = win32com.client.constants.wdWindowStateMinimize</P>
|
||||
</CODE><P>and Word will Minimize.</P></BODY>
|
||||
</HTML>
|
||||
195
Pywin32/lib/x32/win32com/HTML/QuickStartServerCom.html
Normal file
@@ -0,0 +1,195 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>Quick Start to Server Side COM and Python</TITLE>
|
||||
<META NAME="Version" CONTENT="8.0.3410">
|
||||
<META NAME="Date" CONTENT="10/11/96">
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY TEXT="#000000" LINK="#0000ff" VLINK="#800080" BGCOLOR="#ffffff">
|
||||
|
||||
<H1>Quick Start to Server side COM and Python</H1>
|
||||
<H2>Introduction</H2>
|
||||
<P>This documents how to quickly start implementing COM objects in Python. It is not a thorough discussion of the COM system, or of the concepts introduced by COM.</P>
|
||||
<P>For more details information on Python and COM, please see the <A HREF="http://www.python.org/windows/win32com/COMTutorial/index.htm">COM Tutorial given by Greg Stein and Mark Hammond at SPAM 6 (HTML format)</A> or download the same tutorial <A HREF="http://www.python.org/windows/win32com/COMTutorial.ppt">in PowerPoint format.</A></P>
|
||||
<P>For information on using external COM objects from Python, please see <A HREF="QuickStartClientCom.html">a Quick Start to Client side COM and Python</A>.</P>
|
||||
<P>In this document we discuss the <A HREF="#core">core functionality</A>, <A HREF="#Registering">registering the server</A>, <A HREF="#testing">testing the class</A>, <A HREF="#debugging">debugging the class</A>, <A HREF="#Exception">exception handling</A> and <A HREF="#Policies">server policies</A> (phew!)</P>
|
||||
<H2><A NAME="core">Implement the core functionality</A></H2>
|
||||
<H3><A NAME="Using">Implement a stand-alone Python class with your functionality</A></H3>
|
||||
<CODE><P>class HelloWorld:</P><DIR>
|
||||
<DIR>
|
||||
|
||||
<P>def __init__(self):</P><DIR>
|
||||
<DIR>
|
||||
|
||||
<P>self.softspace = 1</P>
|
||||
<P>self.noCalls = 0</P></DIR>
|
||||
</DIR>
|
||||
|
||||
<P>def Hello(self, who):</P><DIR>
|
||||
<DIR>
|
||||
|
||||
<P>self.noCalls = self.noCalls + 1</P>
|
||||
<P># insert "softspace" number of spaces</P>
|
||||
<P>return "Hello" + " " * self.softspace + who</P></DIR>
|
||||
</DIR>
|
||||
</DIR>
|
||||
</DIR>
|
||||
|
||||
</CODE><P>This is obviously a very simple server. In particular, custom error handling would be needed for a production class server. In addition, there are some contrived properties just for demonstration purposes.</P>
|
||||
<H3>Make Unicode concessions</H3>
|
||||
<P>At this stage, Python and Unicode don<6F>t really work well together. All strings which come from COM will actually be Unicode objects rather than string objects.</P>
|
||||
<P>To make this code work in a COM environment, the last line of the "Hello" method must become:</P><DIR>
|
||||
<DIR>
|
||||
<DIR>
|
||||
<DIR>
|
||||
|
||||
<CODE><P>return "Hello" + " " * self.softspace + str(who)</P></DIR>
|
||||
</DIR>
|
||||
</DIR>
|
||||
</DIR>
|
||||
|
||||
</CODE><P>Note the conversion of the "who" to "str(who)". This forces the Unicode object into a native Python string object.</P>
|
||||
<P>For details on how to debug COM Servers to find this sort of error, please see <A HREF="#debugging">debugging the class</A></P>
|
||||
<H3>Annotate the class with win32com specific attributes</H3>
|
||||
<P>This is not a complete list of names, simply a list of properties used by this sample.</P>
|
||||
<TABLE CELLSPACING=0 BORDER=0 CELLPADDING=7 WIDTH=637>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P><B>Property Name</B></TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<B><P>Description</B></TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P>_public_methods_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<P>List of all method names exposed to remote COM clients</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P>_public_attrs_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<P>List of all attribute names exposed to remote COM clients</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>_readonly_attrs_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>List of all attributes which can be accessed, but not set.</TD>
|
||||
</TR>
|
||||
</TABLE>
|
||||
|
||||
<P>We change the class header to become:</P>
|
||||
<CODE><P>class HelloWorld:</P><DIR>
|
||||
<DIR>
|
||||
|
||||
<P>_public_methods_ = ['Hello']</P>
|
||||
<P>_public_attrs_ = ['softspace', 'noCalls']</P>
|
||||
<P>_readonly_attrs_ = ['noCalls']</P>
|
||||
<P>def __init__(self):</P>
|
||||
<P>[Same from here<72>]</P></DIR>
|
||||
</DIR>
|
||||
|
||||
</CODE><H3><A NAME="Registering">Registering and assigning a CLSID for the object</A></H3>
|
||||
<P>COM requires that all objects use a unique CLSID and be registered under a "user friendly" name. This documents the process.</P>
|
||||
<H4>Generating the CLSID</H4>
|
||||
<P>Microsoft Visual C++ comes with various tools for generating CLSID's, which are quite suitable. Alternatively, the pythoncom module exports the function CreateGuid() to generate these identifiers.</P>
|
||||
<CODE><P>>>> import pythoncom<BR>
|
||||
>>> print pythoncom.CreateGuid()<BR>
|
||||
{7CC9F362-486D-11D1-BB48-0000E838A65F}</P>
|
||||
</CODE><P>Obviously the GUID that you get will be different than that displayed here.</P>
|
||||
<H4>Preparing for registration of the Class</H4>
|
||||
<P>The win32com package allows yet more annotations to be applied to a class, allowing registration to be effected with 2 lines in your source file. The registration annotations used by this sample are:</P>
|
||||
<TABLE CELLSPACING=0 BORDER=0 CELLPADDING=7 WIDTH=636>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P><B>Property Name</B></TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<B><P>Description</B></TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P>_reg_clsid_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<P>The CLSID of the COM object</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP">
|
||||
<P>_reg_progid_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP">
|
||||
<P>The "program ID", or Name, of the COM Server. This is the name the user usually uses to instantiate the object</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>_reg_desc_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>Optional: The description of the COM Server. Used primarily for COM browsers. If not specified, the _reg_progid_ is used as the description.</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>_reg_class_spec_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>Optional: A string which represents how Python can create the class instance. The string is of format<BR>
|
||||
[package.subpackage.]module.class</P>
|
||||
<P>The portion up to the class name must be valid for Python to "import", and the class portion must be a valid attribute in the specified class.</P>
|
||||
<P>This is optional from build 124 of Pythoncom., and has been removed from this sample.</TD>
|
||||
</TR>
|
||||
<TR><TD WIDTH="34%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>_reg_remove_keys_</TD>
|
||||
<TD WIDTH="66%" VALIGN="TOP" HEIGHT=5>
|
||||
<P>Optional: A list of tuples of extra registry keys to be removed when uninstalling the server. Each tuple is of format ("key", root), where key is a string, and root is one of the win32con.HKEY_* constants (this item is optional, defaulting to HKEY_CLASSES_ROOT)</TD>
|
||||
</TR>
|
||||
</TABLE>
|
||||
|
||||
<P>Note there are quite a few other keys available. Also note that these annotations are <I>not</I> required - they just make registration simple. Helper functions in the module <CODE>win32com.server.register</CODE> allow you to explicitly specify each of these attributes without attaching them to the class.</P>
|
||||
<P>The header of our class now becomes:</P>
|
||||
<CODE><P>class HelloWorld:</P><DIR>
|
||||
<DIR>
|
||||
|
||||
<P>_reg_clsid_ = "{7CC9F362-486D-11D1-BB48-0000E838A65F}"</P>
|
||||
<P>_reg_desc_ = "Python Test COM Server"</P>
|
||||
<P>_reg_progid_ = "Python.TestServer"</P>
|
||||
<P>_public_methods_ = ['Hello']</P>
|
||||
<P>[same from here]</P></DIR>
|
||||
</DIR>
|
||||
|
||||
</CODE><H4>Registering the Class</H4>
|
||||
<P>The idiom that most Python COM Servers use is that they register themselves when run as a script (ie, when executed from the command line.) Thus the standard "<CODE>if __name__=='__main___':</CODE>" technique works well.</P>
|
||||
<P>win32com.server.register contains a number of helper functions. The easiest to use is "<CODE>UseCommandLine</CODE>".</P>
|
||||
<P>Registration becomes as simple as:</P>
|
||||
<CODE><P>if __name__=='__main__':<BR>
|
||||
	# ni only for 1.4!<BR>
|
||||
	import ni, win32com.server.register <BR>
|
||||
	win32com.server.register.UseCommandLine(HelloWorld)</P>
|
||||
</CODE><P>Running the script will register our test server.</P>
|
||||
<H2><A NAME="testing">Testing our Class</A></H2>
|
||||
<P>For the purposes of this demonstration, we will test the class using Visual Basic. This code should run under any version of Visual Basic, including VBA found in Microsoft Office. Any COM compliant package could be used alternatively. VB has been used just to prove there is no "smoke and mirrors. For information on how to test the server using Python, please see the <A HREF="QuickStartClientCom.html">Quick Start to Client side COM</A> documentation.</P>
|
||||
<P>This is not a tutorial in VB. The code is just presented! Run it, and it will work!</P>
|
||||
<H2><A NAME="debugging">Debugging the COM Server</A></H2>
|
||||
<P>When things go wrong in COM Servers, there is often nowhere useful for the Python traceback to go, even if such a traceback is generated.</P>
|
||||
<P>Rather than discuss how it works, I will just present the procedure to debug your server:</P>
|
||||
<B><P>To register a debug version of your class</B>, run the script (as above) but pass in a "<CODE>--debug</CODE>" parameter. Eg, for the server above, use the command line "<CODE>testcomserver.py --debug</CODE>".</P>
|
||||
<B><P>To see the debug output generated</B> (and any print statements you may choose to add!) you can simply select the "Remote Debug Trace Collector" from the Pythonwin Tools menu, or run the script "win32traceutil.py" from Windows Explorer or a Command Prompt.</P>
|
||||
<H2><A NAME="Exception">Exception Handling </A></H2>
|
||||
<P>Servers need to be able to provide exception information to their client. In some cases, it may be a simple return code (such as E_NOTIMPLEMENTED), but often it can contain much richer information, describing the error on detail, and even a help file and topic where more information can be found. </P>
|
||||
<P>We use Python class based exceptions to provide this information. The COM framework will examine the exception, and look for certain known attributes. These attributes will be copied across to the COM exception, and passed back to the client. </P>
|
||||
<P>The following attributes are supported, and correspond to the equivalent entry in the COM Exception structure:<BR>
|
||||
<CODE>scode, code, description, source, helpfile and helpcontext</P>
|
||||
</CODE><P>To make working with exceptions easier, there is a helper module "win32com.server.exception.py", which defines a single class. An example of its usage would be: </P>
|
||||
<CODE><P>raise COMException(desc="Must be a string",scode=winerror.E_INVALIDARG,helpfile="myhelp.hlp",...)</CODE> </P>
|
||||
<P>(Note the <CODE>COMException class supports (and translates) "desc" as a shortcut for "description", but the framework requires "description")</P>
|
||||
</CODE><H2><A NAME="Policies">Server Policies</A></H2>
|
||||
<P>This is information about how it all hangs together. The casual COM author need not know this. </P>
|
||||
<P>Whenever a Python Server needs to be created, the C++ framework first instantiates a "policy" object. This "policy" object is the gatekeeper for the COM Server - it is responsible for creating the underlying Python object that is the server (ie, your object), and also for translating the underlying COM requests for the object. </P>
|
||||
<P>This policy object handles all of the underlying COM functionality. For example, COM requires all methods and properties to have unique numeric ID's associated with them. The policy object manages the creation of these ID's for the underlying Python methods and attributes. Similarly, when the client whishes to call a method with ID 123, the policy object translates this back to the actual method, and makes the call. </P>
|
||||
<P>It should be noted that the operation of the "policy" object could be dictated by the Python object - the policy object has many defaults, but the actual Python class can always dictate its operation. </P>
|
||||
<H3>Default Policy attributes </H3>
|
||||
<P>The default policy object has a few special attributes that define who the object is exposed to COM. The example above shows the _public_methods attribute, but this section describes all such attributes in detail. </P>
|
||||
<H5>_public_methods_ </H5>
|
||||
<P>Required list of strings, containing the names of all methods to be exposed to COM. It is possible this will be enhanced in the future (eg, possibly '*' will be recognised to say all methods, or some other ideas<61>) </P>
|
||||
<H5>_public_attrs_ </H5>
|
||||
<P>Optional list of strings containing all attribute names to be exposed, both for reading and writing. The attribute names must be valid instance variables. </P>
|
||||
<H5>_readonly_attrs_ </H5>
|
||||
<P>Optional list of strings defining the name of attributes exposed read-only. </P>
|
||||
<H5>_com_interfaces_ </H5>
|
||||
<P>Optional list of IIDs exposed by this object. If this attribute is missing, IID_IDispatch is assumed (ie, if not supplied, the COM object will be created as a normal Automation object.</P>
|
||||
<P>and actual instance attributes: </P>
|
||||
<P>_dynamic_ : optional method </P>
|
||||
<P>_value_ : optional attribute </P>
|
||||
<P>_query_interface_ : optional method </P>
|
||||
<P>_NewEnum : optional method </P>
|
||||
<P>_Evaluate : optional method </P></BODY>
|
||||
</HTML>
|
||||
22
Pywin32/lib/x32/win32com/HTML/docindex.html
Normal file
@@ -0,0 +1,22 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>win32com Documentation Index</TITLE>
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY LINK="#0000ff" VLINK="#800080">
|
||||
|
||||
<H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
|
||||
<H1>PythonCOM Documentation Index</H1>
|
||||
<P>The following documentation is available</P>
|
||||
<P><A HREF="QuickStartClientCom.html">A Quick Start to Client Side COM</A> (including makepy)</P>
|
||||
<P><A HREF="QuickStartServerCom.html">A Quick Start to Server Side COM</A></P>
|
||||
<P><A HREF="GeneratedSupport.html">Information on generated Python files (ie, what makepy generates)</A></P>
|
||||
<P><A HREF="variant.html">An advanced VARIANT object which can give more control over parameter types</A></P>
|
||||
<P><A HREF="package.html">A brief description of the win32com package structure</A></P>
|
||||
<P><A HREF="PythonCOM.html">Python COM Implementation documentation</A></P>
|
||||
<P><A HREF="misc.html">Misc stuff I don<6F>t know where to put anywhere else</A></P>
|
||||
<H3>ActiveX Scripting</H3>
|
||||
<P><A HREF="../../win32comext/axscript/demos/client/ie/demo.htm">ActiveX Scripting Demos</A></P></BODY>
|
||||
</HTML>
|
||||
BIN
Pywin32/lib/x32/win32com/HTML/image/BTN_HomePage.gif
Normal file
|
After Width: | Height: | Size: 211 B |
BIN
Pywin32/lib/x32/win32com/HTML/image/BTN_ManualTop.gif
Normal file
|
After Width: | Height: | Size: 215 B |
BIN
Pywin32/lib/x32/win32com/HTML/image/BTN_NextPage.gif
Normal file
|
After Width: | Height: | Size: 218 B |
BIN
Pywin32/lib/x32/win32com/HTML/image/BTN_PrevPage.gif
Normal file
|
After Width: | Height: | Size: 216 B |
BIN
Pywin32/lib/x32/win32com/HTML/image/blank.gif
Normal file
|
After Width: | Height: | Size: 864 B |
BIN
Pywin32/lib/x32/win32com/HTML/image/pycom_blowing.gif
Normal file
|
After Width: | Height: | Size: 20 KiB |
BIN
Pywin32/lib/x32/win32com/HTML/image/pythoncom.gif
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
BIN
Pywin32/lib/x32/win32com/HTML/image/www_icon.gif
Normal file
|
After Width: | Height: | Size: 275 B |
31
Pywin32/lib/x32/win32com/HTML/index.html
Normal file
@@ -0,0 +1,31 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>win32com</TITLE>
|
||||
<META NAME="Template" CONTENT="C:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY TEXT="#000000" LINK="#0000ff" VLINK="#0000ff">
|
||||
<DIR>
|
||||
|
||||
<P><!-- Enclose the entire page in UL, so bullets don't indent. --></P>
|
||||
<H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99></H1>
|
||||
<H2>Python and COM</H2>
|
||||
<H3>Introduction</H3>
|
||||
<P>Python has an excellent interface to COM (also known variously as OLE2, ActiveX, etc).</P>
|
||||
<P>The Python COM package can be used to interface to almost any COM program (such as the MS-Office suite), write servers that can be hosted by any COM client (such as Visual Basic or C++), and has even been used to provide the core ActiveX Scripting Support. </P>
|
||||
|
||||
|
||||
<UL>
|
||||
<LI>Note that win32com is now released in the win32all installation package. The <A HREF="../win32all/win32all.exe">installation EXE can be downloaded</A>, or you <A HREF="../win32all/">can jump to the win32all readme</A> for more details. </LI>
|
||||
<LI>Here is the <A HREF="win32com_src.zip">win32com source code</A> in a zip file. </LI></UL>
|
||||
</DIR>
|
||||
<DIR>
|
||||
|
||||
<H3>Documentation</H3>
|
||||
<P><A HREF="ActiveXScripting.html">Preliminary Active Scripting and Debugging documentation</A> is available.</P>
|
||||
<P>2 Quick-Start guides have been provided, which also contain other links. See the <A HREF="QuickStartClientCom.html">Quick Start for Client side COM</A> and the <A HREF="QuickStartServerCom.html">Quick Start for Server side COM</A> </P>
|
||||
</P></DIR>
|
||||
</DIR>
|
||||
</BODY>
|
||||
</HTML>
|
||||
18
Pywin32/lib/x32/win32com/HTML/misc.html
Normal file
@@ -0,0 +1,18 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>Misc win32com Stuff</TITLE>
|
||||
<META NAME="Version" CONTENT="8.0.3410">
|
||||
<META NAME="Date" CONTENT="10/11/96">
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\HTML.DOT">
|
||||
</HEAD>
|
||||
<BODY TEXT="#000000" BGCOLOR="#ffffff">
|
||||
|
||||
<H1>Misc stuff I don<6F>t know where to put anywhere else</H1>
|
||||
<H4>Client Side Dispatch</H4>
|
||||
<P>Using win32com.client.Dispatch automatically invokes all the win32com client side "smarts", including automatic usage of generated .py files etc.</P>
|
||||
<P>If you wish to avoid that, and use truly "dynamic" objects (ie, there is generated .py support available, but you wish to avoid it), you can use win32com.client.dynamic.Dispatch</P>
|
||||
<B><P>_print_details_() method</B><BR>
|
||||
If win32com.client.dynamic.Dispatch is used, the objects have a _print_details_() method available, which prints all relevant knowledge about an object (for example, all methods and properties). For objects that do not expose runtime type information, _print_details_ may not list anything.</P></BODY>
|
||||
</HTML>
|
||||
37
Pywin32/lib/x32/win32com/HTML/package.html
Normal file
@@ -0,0 +1,37 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252">
|
||||
<META NAME="Generator" CONTENT="Microsoft Word 97">
|
||||
<TITLE>The win32com package</TITLE>
|
||||
<META NAME="Template" CONTENT="D:\Program Files\Microsoft Office\Office\html.dot">
|
||||
</HEAD>
|
||||
<BODY LINK="#0000ff" VLINK="#800080">
|
||||
|
||||
<H1><IMG SRC="image/pycom_blowing.gif" WIDTH=549 HEIGHT=99 ALT="Python and COM - Blowing the others away"></H1>
|
||||
<H1>The win32com package </H1>
|
||||
<FONT SIZE=2><P>This document describes the win32com package in general terms.</FONT> </P>
|
||||
<FONT SIZE=2><P>The COM support can be thought of as existing in 2 main portions - the C++ support code (the core PythonCOM module), and helper code, implemented in Python. The total package is known as "win32com".</FONT> </P>
|
||||
<FONT SIZE=2><P>The win32com support is stand-alone. It does not require Pythonwin.</FONT> </P>
|
||||
<H2>The win32com package </H2>
|
||||
<FONT SIZE=2><P>To facilitate an orderly framework, the Python "ni" module has been used, and the entire package is known as "win32com". As is normal for such packages, win32com itself does not provide any functionality. Some of the modules are described below:</FONT> </P>
|
||||
|
||||
<UL>
|
||||
<B><FONT SIZE=2><LI>win32com.pythoncom - core C++ support</B>. <BR>
|
||||
This module is rarely used directly by programmers - instead the other "helper" module are used, which themselves draw on the core pythoncom services.</FONT> </LI>
|
||||
<B><FONT SIZE=2><LI>win32com.client package<BR>
|
||||
</B>Support for COM clients used by Python. Some of the modules in this package allow for dynamic usage of COM clients, a module for generating .py files for certain COM servers, etc.</FONT> </LI>
|
||||
<B><FONT SIZE=2><LI>win32com.server package<BR>
|
||||
</B>Support for COM servers written in Python. The modules in this package provide most of the underlying framework for magically turning Python classes into COM servers, exposing the correct public methods, registering your server in the registry, etc. </LI>
|
||||
<B><LI>win32com.axscript<BR>
|
||||
</B>ActiveX Scripting implementation for Python.</FONT> </LI>
|
||||
<B><FONT SIZE=2><LI>win32com.axdebug<BR>
|
||||
</B>Active Debugging implementation for Python</FONT> </LI>
|
||||
<B><FONT SIZE=2><LI>win32com.mapi<BR>
|
||||
</B>Utilities for working with MAPI and the Microsoft Exchange Server</LI></UL>
|
||||
|
||||
</FONT><P> </P>
|
||||
<H2>The pythoncom module </H2>
|
||||
<FONT SIZE=2><P>The pythoncom module is the underlying C++ support for all COM related objects. In general, Python programmers will not use this module directly, but use win32com helper classes and functions. </P>
|
||||
<P>This module exposes a C++ like interface to COM - there are objects implemented in pythoncom that have methods "QueryInterface()", "Invoke()", just like the C++ API. If you are using COM in C++, you would not call a method directly, you would use pObject->Invoke( <20>, MethodId, argArray<61>). Similarly, if you are using pythoncom directly, you must also use the Invoke method to call an object's exposed method.</FONT> </P>
|
||||
<FONT SIZE=2><P>There are some Python wrappers for hiding this raw interface, meaning you should almost never need to use the pythoncom module directly. These helpers translate a "natural" looking interface (eg, obj.SomeMethod()) into the underlying Invoke call.</P></FONT></BODY>
|
||||
</HTML>
|
||||
162
Pywin32/lib/x32/win32com/HTML/variant.html
Normal file
@@ -0,0 +1,162 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<TITLE>win32com.client.VARIANT</TITLE>
|
||||
</HEAD>
|
||||
<BODY>
|
||||
|
||||
<H2>Introduction</H2>
|
||||
<p>
|
||||
win32com attempts to provide a seamless COM interface and hide many COM
|
||||
implementation details, including the use of COM VARIANT structures. This
|
||||
means that in most cases, you just call a COM object using normal Python
|
||||
objects as parameters and get back normal Python objects as results.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
However, in some cases this doesn't work very well, particularly when using
|
||||
"dynamic" (aka late-bound) objects, or when using "makepy" (aka early-bound)
|
||||
objects which only declare a parameter is a VARIANT.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
The <code>win32com.client.VARIANT</code> object is designed to overcome these
|
||||
problems.
|
||||
</p>
|
||||
|
||||
<h2>Drawbacks</h2>
|
||||
The primary issue with this approach is that the programmer must learn more
|
||||
about COM VARIANTs than otherwise - they need to know concepts such as
|
||||
variants being <em>byref</em>, holding arrays, or that some may hold 32bit
|
||||
unsigned integers while others hold 64bit signed ints, and they need to
|
||||
understand this in the context of a single method call. In short, this is
|
||||
a relatively advanced feature. The good news though is that use of these
|
||||
objects should never cause your program to hard-crash - the worst you should
|
||||
expect are Python or COM exceptions being thrown.
|
||||
|
||||
<h2>The VARIANT object</h2>
|
||||
|
||||
The VARIANT object lives in <code>win32com.client</code>. The constructor
|
||||
takes 2 parameters - the 'variant type' and the value. The 'variant type' is
|
||||
an integer and can be one or more of the <code>pythoncom.VT_*</code> values,
|
||||
possibly or'd together.
|
||||
|
||||
<p>For example, to create a VARIANT object which defines a byref array of
|
||||
32bit integers, you could use:
|
||||
|
||||
<pre>
|
||||
>>> from win32com.client import VARIANT
|
||||
>>> import pythoncom
|
||||
>>> v = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_ARRAY | pythoncom.VT_I4,
|
||||
... [1,2,3,4])
|
||||
>>> v
|
||||
win32com.client.VARIANT(24579, [1, 2, 3, 4])
|
||||
>>>
|
||||
</pre>
|
||||
|
||||
This variable can then be used whereever a COM VARIANT is expected.
|
||||
|
||||
<h2>Example usage with dynamic objects.</h2>
|
||||
|
||||
For this example we will use the COM object used for win32com testing,
|
||||
<code>PyCOMTest.PyCOMTest</code>. This object defines a method which is
|
||||
defined in IDL as:
|
||||
<pre>
|
||||
HRESULT DoubleInOutString([in,out] BSTR *str);
|
||||
</pre>
|
||||
|
||||
As you can see, it takes a single string parameter which is also used as
|
||||
an "out" parameter - the single parameter will be updated after the call.
|
||||
The implementation of the method simply "doubles" the string.
|
||||
|
||||
<p>If the object has a type-library, this method works fine with makepy
|
||||
generated support. For example:
|
||||
|
||||
<pre>
|
||||
>>> from win32com.client.gencache import EnsureDispatch
|
||||
>>> ob = EnsureDispatch("PyCOMTest.PyCOMTest")
|
||||
>>> ob.DoubleInOutString("Hello")
|
||||
u'HelloHello'
|
||||
>>>
|
||||
</pre>
|
||||
|
||||
However, if makepy support is not available the method does not work as
|
||||
expected. For the next example we will use <code>DumbDispatch</code> to
|
||||
simulate the object not having a type-library.
|
||||
|
||||
<pre>
|
||||
>>> import win32com.client.dynamic
|
||||
>>> ob = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
|
||||
>>> ob.DoubleInOutString("Hello")
|
||||
>>>
|
||||
</pre>
|
||||
|
||||
As you can see, no result came back from the function. This is because
|
||||
win32com has no type information available to use, so doesn't know the
|
||||
parameter should be passed as a <code>byref</code> parameter. To work
|
||||
around this, we can use the <code>VARIANT</code> object.
|
||||
|
||||
<p>The following example explicitly creates a VARIANT object with a
|
||||
variant type of a byref string and a value 'Hello'. After making the
|
||||
call with this VARIANT the value is updated.
|
||||
|
||||
<pre>
|
||||
>>> import win32com.client.dynamic
|
||||
>>> from win32com.client import VARIANT
|
||||
>>> import pythoncom
|
||||
>>> ob = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
|
||||
>>> variant = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Hello")
|
||||
>>> variant.value # check the value before the call.
|
||||
'Hello'
|
||||
>>> ob.DoubleInOutString(variant)
|
||||
>>> variant.value
|
||||
u'HelloHello'
|
||||
>>>
|
||||
</pre>
|
||||
|
||||
<h2>Usage with generated objects</h2>
|
||||
|
||||
In most cases, objects with makepy support (ie, 'generated' objects) don't
|
||||
need to use the VARIANT object - the type information means win32com can guess
|
||||
the right thing to pass. However, in some cases the VARIANT object can still
|
||||
be useful.
|
||||
|
||||
Imagine a poorly specified object with IDL like:
|
||||
|
||||
<pre>
|
||||
HRESULT DoSomething([in] VARIANT value);
|
||||
</pre>
|
||||
|
||||
But also imagine that the object has a limitation that if the parameter is an
|
||||
integer, it must be a 32bit unsigned value - any other integer representation
|
||||
will fail.
|
||||
|
||||
<p>If you just pass a regular Python integer to this function, it will
|
||||
generally be passed as a 32bit signed integer and given the limitation above,
|
||||
will fail. The VARIANT object allows you to work around the limitation - just
|
||||
create a variant object <code>VARIANT(pythoncom.VT_UI4, int_value)</code> and
|
||||
pass that - the function will then be called with the explicit type you
|
||||
specified and will succeed.
|
||||
|
||||
<p>Note that you can not use a VARIANT object to override the types described
|
||||
in a type library. If a makepy generated class specifies that a VT_UI2 is
|
||||
expected, attempting to pass a VARIANT object will fail. In this case you
|
||||
would need to hack around the problem. For example, imagine <code>ob</code>
|
||||
was a COM object which a method called <code>foo</code> and you wanted to
|
||||
override the type declaration for <code>foo</code> by passing a VARIANT.
|
||||
You could do something like:
|
||||
|
||||
<pre>
|
||||
>>> import win32com.client.dynamic
|
||||
>>> from win32com.client import VARIANT
|
||||
>>> import pythoncom
|
||||
>>> dumbob = win32com.client.dynamic.DumbDispatch(ob)
|
||||
>>> variant = VARIANT(pythoncom.VT_BYREF | pythoncom.VT_BSTR, "Hello")
|
||||
>>> dumbob.foo(variant)
|
||||
</pre>
|
||||
|
||||
The code above converts the makepy supported <code>ob</code> into a
|
||||
'dumb' (ie, non-makepy supported) version of the object, which will then
|
||||
allow you to use VARIANT objects for the problematic methods.
|
||||
|
||||
</BODY>
|
||||
</HTML>
|
||||
30
Pywin32/lib/x32/win32com/License.txt
Normal file
@@ -0,0 +1,30 @@
|
||||
Unless stated in the specfic source file, this work is
|
||||
Copyright (c) 1996-2008, Greg Stein and Mark Hammond.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither names of Greg Stein, Mark Hammond nor the name of contributors may be used
|
||||
to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
|
||||
IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
120
Pywin32/lib/x32/win32com/__init__.py
Normal file
@@ -0,0 +1,120 @@
|
||||
#
|
||||
# Initialization for the win32com package
|
||||
#
|
||||
|
||||
import win32api, sys, os
|
||||
import pythoncom
|
||||
|
||||
# flag if we are in a "frozen" build.
|
||||
_frozen = getattr(sys, "frozen", 1==0)
|
||||
# pythoncom dumbly defaults this to zero - we believe sys.frozen over it.
|
||||
if _frozen and not getattr(pythoncom, "frozen", 0):
|
||||
pythoncom.frozen = sys.frozen
|
||||
|
||||
# Add support for an external "COM Extensions" path.
|
||||
# Concept is that you can register a seperate path to be used for
|
||||
# COM extensions, outside of the win32com directory. These modules, however,
|
||||
# look identical to win32com built-in modules.
|
||||
# This is the technique that we use for the "standard" COM extensions.
|
||||
# eg "win32com.mapi" or "win32com.axscript" both work, even though they do not
|
||||
# live under the main win32com directory.
|
||||
__gen_path__ = ''
|
||||
__build_path__ = None
|
||||
### TODO - Load _all_ \\Extensions subkeys - for now, we only read the default
|
||||
### Modules will work if loaded into "win32comext" path.
|
||||
|
||||
def SetupEnvironment():
|
||||
HKEY_LOCAL_MACHINE = -2147483646 # Avoid pulling in win32con for just these...
|
||||
KEY_QUERY_VALUE = 0x1
|
||||
# Open the root key once, as this is quite slow on NT.
|
||||
try:
|
||||
keyName = "SOFTWARE\\Python\\PythonCore\\%s\\PythonPath\\win32com" % sys.winver
|
||||
key = win32api.RegOpenKey(HKEY_LOCAL_MACHINE , keyName, 0, KEY_QUERY_VALUE)
|
||||
except (win32api.error, AttributeError):
|
||||
key = None
|
||||
|
||||
try:
|
||||
found = 0
|
||||
if key is not None:
|
||||
try:
|
||||
__path__.append( win32api.RegQueryValue(key, "Extensions" ))
|
||||
found = 1
|
||||
except win32api.error:
|
||||
# Nothing registered
|
||||
pass
|
||||
if not found:
|
||||
try:
|
||||
__path__.append( win32api.GetFullPathName( __path__[0] + "\\..\\win32comext") )
|
||||
except win32api.error:
|
||||
# Give up in disgust!
|
||||
pass
|
||||
|
||||
# For the sake of developers, we also look up a "BuildPath" key
|
||||
# If extension modules add support, we can load their .pyd's from a completely
|
||||
# different directory (see the comments below)
|
||||
try:
|
||||
if key is not None:
|
||||
global __build_path__
|
||||
__build_path__ = win32api.RegQueryValue(key, "BuildPath")
|
||||
__path__.append(__build_path__)
|
||||
except win32api.error:
|
||||
# __build_path__ neednt be defined.
|
||||
pass
|
||||
global __gen_path__
|
||||
if key is not None:
|
||||
try:
|
||||
__gen_path__ = win32api.RegQueryValue(key, "GenPath")
|
||||
except win32api.error:
|
||||
pass
|
||||
finally:
|
||||
if key is not None:
|
||||
key.Close()
|
||||
|
||||
# A Helper for developers. A sub-package's __init__ can call this help function,
|
||||
# which allows the .pyd files for the extension to live in a special "Build" directory
|
||||
# (which the win32com developers do!)
|
||||
def __PackageSupportBuildPath__(package_path):
|
||||
# See if we have a special directory for the binaries (for developers)
|
||||
if not _frozen and __build_path__:
|
||||
package_path.append(__build_path__)
|
||||
|
||||
if not _frozen:
|
||||
SetupEnvironment()
|
||||
|
||||
# If we don't have a special __gen_path__, see if we have a gen_py as a
|
||||
# normal module and use that (ie, "win32com.gen_py" may already exist as
|
||||
# a package.
|
||||
if not __gen_path__:
|
||||
try:
|
||||
import win32com.gen_py
|
||||
# hrmph - 3.3 throws: TypeError: '_NamespacePath' object does not support indexing
|
||||
# attempting to get __path__[0] - but I can't quickly repro this stand-alone.
|
||||
# Work around it by using an iterator.
|
||||
__gen_path__ = next(iter(sys.modules["win32com.gen_py"].__path__))
|
||||
except ImportError:
|
||||
# If a win32com\gen_py directory already exists, then we use it
|
||||
# (gencache doesn't insist it have an __init__, but our __import__
|
||||
# above does!
|
||||
__gen_path__ = os.path.abspath(os.path.join(__path__[0], "gen_py"))
|
||||
if not os.path.isdir(__gen_path__):
|
||||
# We used to dynamically create a directory under win32com -
|
||||
# but this sucks. If the dir doesn't already exist, we we
|
||||
# create a version specific directory under the user temp
|
||||
# directory.
|
||||
__gen_path__ = os.path.join(
|
||||
win32api.GetTempPath(), "gen_py",
|
||||
"%d.%d" % (sys.version_info[0], sys.version_info[1]))
|
||||
|
||||
# we must have a __gen_path__, but may not have a gen_py module -
|
||||
# set that up.
|
||||
if "win32com.gen_py" not in sys.modules:
|
||||
# Create a "win32com.gen_py", but with a custom __path__
|
||||
import imp
|
||||
gen_py = imp.new_module("win32com.gen_py")
|
||||
gen_py.__path__ = [ __gen_path__ ]
|
||||
sys.modules[gen_py.__name__]=gen_py
|
||||
del imp
|
||||
gen_py = sys.modules["win32com.gen_py"]
|
||||
|
||||
# get rid of these for module users
|
||||
del os, sys, win32api, pythoncom
|
||||
53
Pywin32/lib/x32/win32com/client/CLSIDToClass.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Manages a dictionary of CLSID strings to Python classes.
|
||||
|
||||
Primary use of this module is to allow modules generated by
|
||||
makepy.py to share classes. @makepy@ automatically generates code
|
||||
which interacts with this module. You should never need to reference
|
||||
this module directly.
|
||||
|
||||
This module only provides support for modules which have been previously
|
||||
been imported. The gencache module provides some support for loading modules
|
||||
on demand - once done, this module supports it...
|
||||
|
||||
As an example, the MSACCESS.TLB type library makes reference to the
|
||||
CLSID of the Database object, as defined in DAO3032.DLL. This
|
||||
allows code using the MSAccess wrapper to natively use Databases.
|
||||
|
||||
This obviously applies to all cooperating objects, not just DAO and
|
||||
Access.
|
||||
"""
|
||||
mapCLSIDToClass = {}
|
||||
|
||||
def RegisterCLSID( clsid, pythonClass ):
|
||||
"""Register a class that wraps a CLSID
|
||||
|
||||
This function allows a CLSID to be globally associated with a class.
|
||||
Certain module will automatically convert an IDispatch object to an
|
||||
instance of the associated class.
|
||||
"""
|
||||
|
||||
mapCLSIDToClass[str(clsid)] = pythonClass
|
||||
|
||||
def RegisterCLSIDsFromDict( dict ):
|
||||
"""Register a dictionary of CLSID's and classes.
|
||||
|
||||
This module performs the same function as @RegisterCLSID@, but for
|
||||
an entire dictionary of associations.
|
||||
|
||||
Typically called by makepy generated modules at import time.
|
||||
"""
|
||||
mapCLSIDToClass.update(dict)
|
||||
|
||||
def GetClass(clsid):
|
||||
"""Given a CLSID, return the globally associated class.
|
||||
|
||||
clsid -- a string CLSID representation to check.
|
||||
"""
|
||||
return mapCLSIDToClass[clsid]
|
||||
|
||||
def HasClass(clsid):
|
||||
"""Determines if the CLSID has an associated class.
|
||||
|
||||
clsid -- the string CLSID to check
|
||||
"""
|
||||
return clsid in mapCLSIDToClass
|
||||
539
Pywin32/lib/x32/win32com/client/__init__.py
Normal file
@@ -0,0 +1,539 @@
|
||||
# This module exists to create the "best" dispatch object for a given
|
||||
# object. If "makepy" support for a given object is detected, it is
|
||||
# used, otherwise a dynamic dispatch object.
|
||||
|
||||
# Note that if the unknown dispatch object then returns a known
|
||||
# dispatch object, the known class will be used. This contrasts
|
||||
# with dynamic.Dispatch behaviour, where dynamic objects are always used.
|
||||
|
||||
import pythoncom
|
||||
from . import dynamic
|
||||
from . import gencache
|
||||
import sys
|
||||
import pywintypes
|
||||
|
||||
_PyIDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
|
||||
|
||||
|
||||
def __WrapDispatch(dispatch, userName = None, resultCLSID = None, typeinfo = None, \
|
||||
UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER,
|
||||
WrapperClass = None):
|
||||
"""
|
||||
Helper function to return a makepy generated class for a CLSID if it exists,
|
||||
otherwise cope by using CDispatch.
|
||||
"""
|
||||
assert UnicodeToString is None, "this is deprecated and will go away"
|
||||
if resultCLSID is None:
|
||||
try:
|
||||
typeinfo = dispatch.GetTypeInfo()
|
||||
if typeinfo is not None: # Some objects return NULL, some raise exceptions...
|
||||
resultCLSID = str(typeinfo.GetTypeAttr()[0])
|
||||
except (pythoncom.com_error, AttributeError):
|
||||
pass
|
||||
if resultCLSID is not None:
|
||||
from . import gencache
|
||||
# Attempt to load generated module support
|
||||
# This may load the module, and make it available
|
||||
klass = gencache.GetClassForCLSID(resultCLSID)
|
||||
if klass is not None:
|
||||
return klass(dispatch)
|
||||
|
||||
# Return a "dynamic" object - best we can do!
|
||||
if WrapperClass is None: WrapperClass = CDispatch
|
||||
return dynamic.Dispatch(dispatch, userName, WrapperClass, typeinfo, clsctx=clsctx)
|
||||
|
||||
|
||||
def GetObject(Pathname = None, Class = None, clsctx = None):
|
||||
"""
|
||||
Mimic VB's GetObject() function.
|
||||
|
||||
ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
|
||||
connect to an already running instance of the COM object.
|
||||
|
||||
ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
|
||||
will return a ready to use Python wrapping of the required COM object.
|
||||
|
||||
Note: You must specifiy one or the other of these arguments. I know
|
||||
this isn't pretty, but it is what VB does. Blech. If you don't
|
||||
I'll throw ValueError at you. :)
|
||||
|
||||
This will most likely throw pythoncom.com_error if anything fails.
|
||||
"""
|
||||
if clsctx is None:
|
||||
clsctx = pythoncom.CLSCTX_ALL
|
||||
|
||||
if (Pathname is None and Class is None) or \
|
||||
(Pathname is not None and Class is not None):
|
||||
raise ValueError("You must specify a value for Pathname or Class, but not both.")
|
||||
|
||||
if Class is not None:
|
||||
return GetActiveObject(Class, clsctx)
|
||||
else:
|
||||
return Moniker(Pathname, clsctx)
|
||||
|
||||
def GetActiveObject(Class, clsctx = pythoncom.CLSCTX_ALL):
|
||||
"""
|
||||
Python friendly version of GetObject's ProgID/CLSID functionality.
|
||||
"""
|
||||
resultCLSID = pywintypes.IID(Class)
|
||||
dispatch = pythoncom.GetActiveObject(resultCLSID)
|
||||
dispatch = dispatch.QueryInterface(pythoncom.IID_IDispatch)
|
||||
return __WrapDispatch(dispatch, Class, resultCLSID = resultCLSID, clsctx = clsctx)
|
||||
|
||||
def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
|
||||
"""
|
||||
Python friendly version of GetObject's moniker functionality.
|
||||
"""
|
||||
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
|
||||
dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
|
||||
return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
|
||||
|
||||
def Dispatch(dispatch, userName = None, resultCLSID = None, typeinfo = None, UnicodeToString=None, clsctx = pythoncom.CLSCTX_SERVER):
|
||||
"""Creates a Dispatch based COM object.
|
||||
"""
|
||||
assert UnicodeToString is None, "this is deprecated and will go away"
|
||||
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
|
||||
return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
|
||||
|
||||
def DispatchEx(clsid, machine=None, userName = None, resultCLSID = None, typeinfo = None, UnicodeToString=None, clsctx = None):
|
||||
"""Creates a Dispatch based COM object on a specific machine.
|
||||
"""
|
||||
assert UnicodeToString is None, "this is deprecated and will go away"
|
||||
# If InProc is registered, DCOM will use it regardless of the machine name
|
||||
# (and regardless of the DCOM config for the object.) So unless the user
|
||||
# specifies otherwise, we exclude inproc apps when a remote machine is used.
|
||||
if clsctx is None:
|
||||
clsctx = pythoncom.CLSCTX_SERVER
|
||||
if machine is not None: clsctx = clsctx & ~pythoncom.CLSCTX_INPROC
|
||||
if machine is None:
|
||||
serverInfo = None
|
||||
else:
|
||||
serverInfo = (machine,)
|
||||
if userName is None: userName = clsid
|
||||
dispatch = pythoncom.CoCreateInstanceEx(clsid, None, clsctx, serverInfo, (pythoncom.IID_IDispatch,))[0]
|
||||
return Dispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx)
|
||||
|
||||
class CDispatch(dynamic.CDispatch):
|
||||
"""
|
||||
The dynamic class used as a last resort.
|
||||
The purpose of this overriding of dynamic.CDispatch is to perpetuate the policy
|
||||
of using the makepy generated wrapper Python class instead of dynamic.CDispatch
|
||||
if/when possible.
|
||||
"""
|
||||
def _wrap_dispatch_(self, ob, userName = None, returnCLSID = None, UnicodeToString=None):
|
||||
assert UnicodeToString is None, "this is deprecated and will go away"
|
||||
return Dispatch(ob, userName, returnCLSID,None)
|
||||
|
||||
def CastTo(ob, target):
|
||||
"""'Cast' a COM object to another interface"""
|
||||
# todo - should support target being an IID
|
||||
if hasattr(target, "index"): # string like
|
||||
# for now, we assume makepy for this to work.
|
||||
if "CLSID" not in ob.__class__.__dict__:
|
||||
# Eeek - no makepy support - try and build it.
|
||||
ob = gencache.EnsureDispatch(ob)
|
||||
if "CLSID" not in ob.__class__.__dict__:
|
||||
raise ValueError("Must be a makepy-able object for this to work")
|
||||
clsid = ob.CLSID
|
||||
# Lots of hoops to support "demand-build" - ie, generating
|
||||
# code for an interface first time it is used. We assume the
|
||||
# interface name exists in the same library as the object.
|
||||
# This is generally the case - only referenced typelibs may be
|
||||
# a problem, and we can handle that later. Maybe <wink>
|
||||
# So get the generated module for the library itself, then
|
||||
# find the interface CLSID there.
|
||||
mod = gencache.GetModuleForCLSID(clsid)
|
||||
# Get the 'root' module.
|
||||
mod = gencache.GetModuleForTypelib(mod.CLSID, mod.LCID,
|
||||
mod.MajorVersion, mod.MinorVersion)
|
||||
# Find the CLSID of the target
|
||||
target_clsid = mod.NamesToIIDMap.get(target)
|
||||
if target_clsid is None:
|
||||
raise ValueError("The interface name '%s' does not appear in the " \
|
||||
"same library as object '%r'" % (target, ob))
|
||||
mod = gencache.GetModuleForCLSID(target_clsid)
|
||||
target_class = getattr(mod, target)
|
||||
# resolve coclass to interface
|
||||
target_class = getattr(target_class, "default_interface", target_class)
|
||||
return target_class(ob) # auto QI magic happens
|
||||
raise ValueError
|
||||
|
||||
class Constants:
|
||||
"""A container for generated COM constants.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.__dicts__ = [] # A list of dictionaries
|
||||
def __getattr__(self, a):
|
||||
for d in self.__dicts__:
|
||||
if a in d:
|
||||
return d[a]
|
||||
raise AttributeError(a)
|
||||
|
||||
# And create an instance.
|
||||
constants = Constants()
|
||||
|
||||
# A helpers for DispatchWithEvents - this becomes __setattr__ for the
|
||||
# temporary class.
|
||||
def _event_setattr_(self, attr, val):
|
||||
try:
|
||||
# Does the COM object have an attribute of this name?
|
||||
self.__class__.__bases__[0].__setattr__(self, attr, val)
|
||||
except AttributeError:
|
||||
# Otherwise just stash it away in the instance.
|
||||
self.__dict__[attr] = val
|
||||
|
||||
# An instance of this "proxy" is created to break the COM circular references
|
||||
# that exist (ie, when we connect to the COM events, COM keeps a reference
|
||||
# to the object. Thus, the Event connection must be manually broken before
|
||||
# our object can die. This solves the problem by manually breaking the connection
|
||||
# to the real object as the proxy dies.
|
||||
class EventsProxy:
|
||||
def __init__(self, ob):
|
||||
self.__dict__['_obj_'] = ob
|
||||
def __del__(self):
|
||||
try:
|
||||
# If there is a COM error on disconnection we should
|
||||
# just ignore it - object probably already shut down...
|
||||
self._obj_.close()
|
||||
except pythoncom.com_error:
|
||||
pass
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self._obj_, attr)
|
||||
def __setattr__(self, attr, val):
|
||||
setattr(self._obj_, attr, val)
|
||||
|
||||
def DispatchWithEvents(clsid, user_event_class):
|
||||
"""Create a COM object that can fire events to a user defined class.
|
||||
clsid -- The ProgID or CLSID of the object to create.
|
||||
user_event_class -- A Python class object that responds to the events.
|
||||
|
||||
This requires makepy support for the COM object being created. If
|
||||
this support does not exist it will be automatically generated by
|
||||
this function. If the object does not support makepy, a TypeError
|
||||
exception will be raised.
|
||||
|
||||
The result is a class instance that both represents the COM object
|
||||
and handles events from the COM object.
|
||||
|
||||
It is important to note that the returned instance is not a direct
|
||||
instance of the user_event_class, but an instance of a temporary
|
||||
class object that derives from three classes:
|
||||
* The makepy generated class for the COM object
|
||||
* The makepy generated class for the COM events
|
||||
* The user_event_class as passed to this function.
|
||||
|
||||
If this is not suitable, see the getevents function for an alternative
|
||||
technique of handling events.
|
||||
|
||||
Object Lifetimes: Whenever the object returned from this function is
|
||||
cleaned-up by Python, the events will be disconnected from
|
||||
the COM object. This is almost always what should happen,
|
||||
but see the documentation for getevents() for more details.
|
||||
|
||||
Example:
|
||||
|
||||
>>> class IEEvents:
|
||||
... def OnVisible(self, visible):
|
||||
... print "Visible changed:", visible
|
||||
...
|
||||
>>> ie = DispatchWithEvents("InternetExplorer.Application", IEEvents)
|
||||
>>> ie.Visible = 1
|
||||
Visible changed: 1
|
||||
>>>
|
||||
"""
|
||||
# Create/Get the object.
|
||||
disp = Dispatch(clsid)
|
||||
if not disp.__class__.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
|
||||
try:
|
||||
ti = disp._oleobj_.GetTypeInfo()
|
||||
disp_clsid = ti.GetTypeAttr()[0]
|
||||
tlb, index = ti.GetContainingTypeLib()
|
||||
tla = tlb.GetLibAttr()
|
||||
gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
|
||||
# Get the class from the module.
|
||||
disp_class = gencache.GetClassForProgID(str(disp_clsid))
|
||||
except pythoncom.com_error:
|
||||
raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
|
||||
else:
|
||||
disp_class = disp.__class__
|
||||
# If the clsid was an object, get the clsid
|
||||
clsid = disp_class.CLSID
|
||||
# Create a new class that derives from 3 classes - the dispatch class, the event sink class and the user class.
|
||||
# XXX - we are still "classic style" classes in py2x, so we need can't yet
|
||||
# use 'type()' everywhere - revisit soon, as py2x will move to new-style too...
|
||||
try:
|
||||
from types import ClassType as new_type
|
||||
except ImportError:
|
||||
new_type = type # py3k
|
||||
events_class = getevents(clsid)
|
||||
if events_class is None:
|
||||
raise ValueError("This COM object does not support events.")
|
||||
result_class = new_type("COMEventClass", (disp_class, events_class, user_event_class), {"__setattr__" : _event_setattr_})
|
||||
instance = result_class(disp._oleobj_) # This only calls the first base class __init__.
|
||||
events_class.__init__(instance, instance)
|
||||
if hasattr(user_event_class, "__init__"):
|
||||
user_event_class.__init__(instance)
|
||||
return EventsProxy(instance)
|
||||
|
||||
def WithEvents(disp, user_event_class):
|
||||
"""Similar to DispatchWithEvents - except that the returned
|
||||
object is *not* also usable as the original Dispatch object - that is
|
||||
the returned object is not dispatchable.
|
||||
|
||||
The difference is best summarised by example.
|
||||
|
||||
>>> class IEEvents:
|
||||
... def OnVisible(self, visible):
|
||||
... print "Visible changed:", visible
|
||||
...
|
||||
>>> ie = Dispatch("InternetExplorer.Application")
|
||||
>>> ie_events = WithEvents(ie, IEEvents)
|
||||
>>> ie.Visible = 1
|
||||
Visible changed: 1
|
||||
|
||||
Compare with the code sample for DispatchWithEvents, where you get a
|
||||
single object that is both the interface and the event handler. Note that
|
||||
the event handler instance will *not* be able to use 'self.' to refer to
|
||||
IE's methods and properties.
|
||||
|
||||
This is mainly useful where using DispatchWithEvents causes
|
||||
circular reference problems that the simple proxy doesn't deal with
|
||||
"""
|
||||
disp = Dispatch(disp)
|
||||
if not disp.__class__.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
|
||||
try:
|
||||
ti = disp._oleobj_.GetTypeInfo()
|
||||
disp_clsid = ti.GetTypeAttr()[0]
|
||||
tlb, index = ti.GetContainingTypeLib()
|
||||
tla = tlb.GetLibAttr()
|
||||
gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
|
||||
# Get the class from the module.
|
||||
disp_class = gencache.GetClassForProgID(str(disp_clsid))
|
||||
except pythoncom.com_error:
|
||||
raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
|
||||
else:
|
||||
disp_class = disp.__class__
|
||||
# Get the clsid
|
||||
clsid = disp_class.CLSID
|
||||
# Create a new class that derives from 2 classes - the event sink
|
||||
# class and the user class.
|
||||
try:
|
||||
from types import ClassType as new_type
|
||||
except ImportError:
|
||||
new_type = type # py3k
|
||||
events_class = getevents(clsid)
|
||||
if events_class is None:
|
||||
raise ValueError("This COM object does not support events.")
|
||||
result_class = new_type("COMEventClass", (events_class, user_event_class), {})
|
||||
instance = result_class(disp) # This only calls the first base class __init__.
|
||||
if hasattr(user_event_class, "__init__"):
|
||||
user_event_class.__init__(instance)
|
||||
return instance
|
||||
|
||||
def getevents(clsid):
|
||||
"""Determine the default outgoing interface for a class, given
|
||||
either a clsid or progid. It returns a class - you can
|
||||
conveniently derive your own handler from this class and implement
|
||||
the appropriate methods.
|
||||
|
||||
This method relies on the classes produced by makepy. You must use
|
||||
either makepy or the gencache module to ensure that the
|
||||
appropriate support classes have been generated for the com server
|
||||
that you will be handling events from.
|
||||
|
||||
Beware of COM circular references. When the Events class is connected
|
||||
to the COM object, the COM object itself keeps a reference to the Python
|
||||
events class. Thus, neither the Events instance or the COM object will
|
||||
ever die by themselves. The 'close' method on the events instance
|
||||
must be called to break this chain and allow standard Python collection
|
||||
rules to manage object lifetimes. Note that DispatchWithEvents() does
|
||||
work around this problem by the use of a proxy object, but if you use
|
||||
the getevents() function yourself, you must make your own arrangements
|
||||
to manage this circular reference issue.
|
||||
|
||||
Beware of creating Python circular references: this will happen if your
|
||||
handler has a reference to an object that has a reference back to
|
||||
the event source. Call the 'close' method to break the chain.
|
||||
|
||||
Example:
|
||||
|
||||
>>>win32com.client.gencache.EnsureModule('{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}',0,1,1)
|
||||
<module 'win32com.gen_py.....
|
||||
>>>
|
||||
>>> class InternetExplorerEvents(win32com.client.getevents("InternetExplorer.Application.1")):
|
||||
... def OnVisible(self, Visible):
|
||||
... print "Visibility changed: ", Visible
|
||||
...
|
||||
>>>
|
||||
>>> ie=win32com.client.Dispatch("InternetExplorer.Application.1")
|
||||
>>> events=InternetExplorerEvents(ie)
|
||||
>>> ie.Visible=1
|
||||
Visibility changed: 1
|
||||
>>>
|
||||
"""
|
||||
|
||||
# find clsid given progid or clsid
|
||||
clsid=str(pywintypes.IID(clsid))
|
||||
# return default outgoing interface for that class
|
||||
klass = gencache.GetClassForCLSID(clsid)
|
||||
try:
|
||||
return klass.default_source
|
||||
except AttributeError:
|
||||
# See if we have a coclass for the interfaces.
|
||||
try:
|
||||
return gencache.GetClassForCLSID(klass.coclass_clsid).default_source
|
||||
except AttributeError:
|
||||
return None
|
||||
|
||||
# A Record object, as used by the COM struct support
|
||||
def Record(name, object):
|
||||
"""Creates a new record object, given the name of the record,
|
||||
and an object from the same type library.
|
||||
|
||||
Example usage would be:
|
||||
app = win32com.client.Dispatch("Some.Application")
|
||||
point = win32com.client.Record("SomeAppPoint", app)
|
||||
point.x = 0
|
||||
point.y = 0
|
||||
app.MoveTo(point)
|
||||
"""
|
||||
# XXX - to do - probably should allow "object" to already be a module object.
|
||||
from . import gencache
|
||||
object = gencache.EnsureDispatch(object)
|
||||
module = sys.modules[object.__class__.__module__]
|
||||
# to allow us to work correctly with "demand generated" code,
|
||||
# we must use the typelib CLSID to obtain the module
|
||||
# (otherwise we get the sub-module for the object, which
|
||||
# does not hold the records)
|
||||
# thus, package may be module, or may be module's parent if demand generated.
|
||||
package = gencache.GetModuleForTypelib(module.CLSID, module.LCID, module.MajorVersion, module.MinorVersion)
|
||||
try:
|
||||
struct_guid = package.RecordMap[name]
|
||||
except KeyError:
|
||||
raise ValueError("The structure '%s' is not defined in module '%s'" % (name, package))
|
||||
return pythoncom.GetRecordFromGuids(module.CLSID, module.MajorVersion, module.MinorVersion, module.LCID, struct_guid)
|
||||
|
||||
|
||||
############################################
|
||||
# The base of all makepy generated classes
|
||||
############################################
|
||||
class DispatchBaseClass:
|
||||
def __init__(self, oobj=None):
|
||||
if oobj is None:
|
||||
oobj = pythoncom.new(self.CLSID)
|
||||
elif isinstance(oobj, DispatchBaseClass):
|
||||
try:
|
||||
oobj = oobj._oleobj_.QueryInterface(self.CLSID, pythoncom.IID_IDispatch) # Must be a valid COM instance
|
||||
except pythoncom.com_error as details:
|
||||
import winerror
|
||||
# Some stupid objects fail here, even tho it is _already_ IDispatch!!??
|
||||
# Eg, Lotus notes.
|
||||
# So just let it use the existing object if E_NOINTERFACE
|
||||
if details.hresult != winerror.E_NOINTERFACE:
|
||||
raise
|
||||
oobj = oobj._oleobj_
|
||||
self.__dict__["_oleobj_"] = oobj # so we dont call __setattr__
|
||||
# Provide a prettier name than the CLSID
|
||||
def __repr__(self):
|
||||
# Need to get the docstring for the module for this class.
|
||||
try:
|
||||
mod_doc = sys.modules[self.__class__.__module__].__doc__
|
||||
if mod_doc:
|
||||
mod_name = "win32com.gen_py." + mod_doc
|
||||
else:
|
||||
mod_name = sys.modules[self.__class__.__module__].__name__
|
||||
except KeyError:
|
||||
mod_name = "win32com.gen_py.unknown"
|
||||
return "<%s.%s instance at 0x%s>" % (mod_name, self.__class__.__name__, id(self))
|
||||
# Delegate comparison to the oleobjs, as they know how to do identity.
|
||||
def __eq__(self, other):
|
||||
other = getattr(other, "_oleobj_", other)
|
||||
return self._oleobj_ == other
|
||||
|
||||
def __ne__(self, other):
|
||||
other = getattr(other, "_oleobj_", other)
|
||||
return self._oleobj_ != other
|
||||
|
||||
def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
|
||||
return self._get_good_object_(
|
||||
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
|
||||
user, resultCLSID)
|
||||
|
||||
def __getattr__(self, attr):
|
||||
args=self._prop_map_get_.get(attr)
|
||||
if args is None:
|
||||
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
|
||||
return self._ApplyTypes_(*args)
|
||||
|
||||
def __setattr__(self, attr, value):
|
||||
if attr in self.__dict__: self.__dict__[attr] = value; return
|
||||
try:
|
||||
args, defArgs=self._prop_map_put_[attr]
|
||||
except KeyError:
|
||||
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
|
||||
self._oleobj_.Invoke(*(args + (value,) + defArgs))
|
||||
def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None):
|
||||
return _get_good_single_object_(obj, obUserName, resultCLSID)
|
||||
def _get_good_object_(self, obj, obUserName=None, resultCLSID=None):
|
||||
return _get_good_object_(obj, obUserName, resultCLSID)
|
||||
|
||||
# XXX - These should be consolidated with dynamic.py versions.
|
||||
def _get_good_single_object_(obj, obUserName=None, resultCLSID=None):
|
||||
if _PyIDispatchType==type(obj):
|
||||
return Dispatch(obj, obUserName, resultCLSID)
|
||||
return obj
|
||||
|
||||
def _get_good_object_(obj, obUserName=None, resultCLSID=None):
|
||||
if obj is None:
|
||||
return None
|
||||
elif isinstance(obj, tuple):
|
||||
obUserNameTuple = (obUserName,) * len(obj)
|
||||
resultCLSIDTuple = (resultCLSID,) * len(obj)
|
||||
return tuple(map(_get_good_object_, obj, obUserNameTuple, resultCLSIDTuple))
|
||||
else:
|
||||
return _get_good_single_object_(obj, obUserName, resultCLSID)
|
||||
|
||||
class CoClassBaseClass:
|
||||
def __init__(self, oobj=None):
|
||||
if oobj is None: oobj = pythoncom.new(self.CLSID)
|
||||
self.__dict__["_dispobj_"] = self.default_interface(oobj)
|
||||
def __repr__(self):
|
||||
return "<win32com.gen_py.%s.%s>" % (__doc__, self.__class__.__name__)
|
||||
|
||||
def __getattr__(self, attr):
|
||||
d=self.__dict__["_dispobj_"]
|
||||
if d is not None: return getattr(d, attr)
|
||||
raise AttributeError(attr)
|
||||
def __setattr__(self, attr, value):
|
||||
if attr in self.__dict__: self.__dict__[attr] = value; return
|
||||
try:
|
||||
d=self.__dict__["_dispobj_"]
|
||||
if d is not None:
|
||||
d.__setattr__(attr, value)
|
||||
return
|
||||
except AttributeError:
|
||||
pass
|
||||
self.__dict__[attr] = value
|
||||
|
||||
# A very simple VARIANT class. Only to be used with poorly-implemented COM
|
||||
# objects. If an object accepts an arg which is a simple "VARIANT", but still
|
||||
# is very pickly about the actual variant type (eg, isn't happy with a VT_I4,
|
||||
# which it would get from a Python integer), you can use this to force a
|
||||
# particular VT.
|
||||
class VARIANT(object):
|
||||
def __init__(self, vt, value):
|
||||
self.varianttype = vt
|
||||
self._value = value
|
||||
|
||||
# 'value' is a property so when set by pythoncom it gets any magic wrapping
|
||||
# which normally happens for result objects
|
||||
def _get_value(self):
|
||||
return self._value
|
||||
def _set_value(self, newval):
|
||||
self._value = _get_good_object_(newval)
|
||||
def _del_value(self):
|
||||
del self._value
|
||||
value = property(_get_value, _set_value, _del_value)
|
||||
|
||||
def __repr__(self):
|
||||
return "win32com.client.VARIANT(%r, %r)" % (self.varianttype, self._value)
|
||||
636
Pywin32/lib/x32/win32com/client/build.py
Normal file
@@ -0,0 +1,636 @@
|
||||
"""Contains knowledge to build a COM object definition.
|
||||
|
||||
This module is used by both the @dynamic@ and @makepy@ modules to build
|
||||
all knowledge of a COM object.
|
||||
|
||||
This module contains classes which contain the actual knowledge of the object.
|
||||
This include parameter and return type information, the COM dispid and CLSID, etc.
|
||||
|
||||
Other modules may use this information to generate .py files, use the information
|
||||
dynamically, or possibly even generate .html documentation for objects.
|
||||
"""
|
||||
|
||||
#
|
||||
# NOTES: DispatchItem and MapEntry used by dynamic.py.
|
||||
# the rest is used by makepy.py
|
||||
#
|
||||
# OleItem, DispatchItem, MapEntry, BuildCallList() is used by makepy
|
||||
|
||||
import sys
|
||||
import string
|
||||
from keyword import iskeyword
|
||||
|
||||
import pythoncom
|
||||
from pywintypes import TimeType
|
||||
import winerror
|
||||
import datetime
|
||||
|
||||
# It isn't really clear what the quoting rules are in a C/IDL string and
|
||||
# literals like a quote char and backslashes makes life a little painful to
|
||||
# always render the string perfectly - so just punt and fall-back to a repr()
|
||||
def _makeDocString(s):
|
||||
if sys.version_info < (3,):
|
||||
s = s.encode("mbcs")
|
||||
return repr(s)
|
||||
|
||||
error = "PythonCOM.Client.Build error"
|
||||
class NotSupportedException(Exception): pass # Raised when we cant support a param type.
|
||||
DropIndirection="DropIndirection"
|
||||
|
||||
NoTranslateTypes = [
|
||||
pythoncom.VT_BOOL, pythoncom.VT_CLSID, pythoncom.VT_CY,
|
||||
pythoncom.VT_DATE, pythoncom.VT_DECIMAL, pythoncom.VT_EMPTY,
|
||||
pythoncom.VT_ERROR, pythoncom.VT_FILETIME, pythoncom.VT_HRESULT,
|
||||
pythoncom.VT_I1, pythoncom.VT_I2, pythoncom.VT_I4,
|
||||
pythoncom.VT_I8, pythoncom.VT_INT, pythoncom.VT_NULL,
|
||||
pythoncom.VT_R4, pythoncom.VT_R8, pythoncom.VT_NULL,
|
||||
pythoncom.VT_STREAM,
|
||||
pythoncom.VT_UI1, pythoncom.VT_UI2, pythoncom.VT_UI4,
|
||||
pythoncom.VT_UI8, pythoncom.VT_UINT, pythoncom.VT_VOID,
|
||||
]
|
||||
|
||||
NoTranslateMap = {}
|
||||
for v in NoTranslateTypes:
|
||||
NoTranslateMap[v] = None
|
||||
|
||||
class MapEntry:
|
||||
"Simple holder for named attibutes - items in a map."
|
||||
def __init__(self, desc_or_id, names=None, doc=None, resultCLSID=pythoncom.IID_NULL, resultDoc = None, hidden=0):
|
||||
if type(desc_or_id)==type(0):
|
||||
self.dispid = desc_or_id
|
||||
self.desc = None
|
||||
else:
|
||||
self.dispid = desc_or_id[0]
|
||||
self.desc = desc_or_id
|
||||
|
||||
self.names = names
|
||||
self.doc = doc
|
||||
self.resultCLSID = resultCLSID
|
||||
self.resultDocumentation = resultDoc
|
||||
self.wasProperty = 0 # Have I been transformed into a function so I can pass args?
|
||||
self.hidden = hidden
|
||||
def GetResultCLSID(self):
|
||||
rc = self.resultCLSID
|
||||
if rc == pythoncom.IID_NULL: return None
|
||||
return rc
|
||||
# Return a string, suitable for output - either "'{...}'" or "None"
|
||||
def GetResultCLSIDStr(self):
|
||||
rc = self.GetResultCLSID()
|
||||
if rc is None: return "None"
|
||||
return repr(str(rc)) # Convert the IID object to a string, then to a string in a string.
|
||||
|
||||
def GetResultName(self):
|
||||
if self.resultDocumentation is None:
|
||||
return None
|
||||
return self.resultDocumentation[0]
|
||||
|
||||
class OleItem:
|
||||
typename = "OleItem"
|
||||
|
||||
def __init__(self, doc=None):
|
||||
self.doc = doc
|
||||
if self.doc:
|
||||
self.python_name = MakePublicAttributeName(self.doc[0])
|
||||
else:
|
||||
self.python_name = None
|
||||
self.bWritten = 0
|
||||
self.bIsDispatch = 0
|
||||
self.bIsSink = 0
|
||||
self.clsid = None
|
||||
self.co_class = None
|
||||
|
||||
class DispatchItem(OleItem):
|
||||
typename = "DispatchItem"
|
||||
|
||||
def __init__(self, typeinfo=None, attr=None, doc=None, bForUser=1):
|
||||
OleItem.__init__(self,doc)
|
||||
self.propMap = {}
|
||||
self.propMapGet = {}
|
||||
self.propMapPut = {}
|
||||
self.mapFuncs = {}
|
||||
self.defaultDispatchName = None
|
||||
self.hidden = 0
|
||||
|
||||
if typeinfo:
|
||||
self.Build(typeinfo, attr, bForUser)
|
||||
|
||||
def _propMapPutCheck_(self,key,item):
|
||||
ins, outs, opts = self.CountInOutOptArgs(item.desc[2])
|
||||
if ins>1: # if a Put property takes more than 1 arg:
|
||||
if opts+1==ins or ins==item.desc[6]+1:
|
||||
newKey = "Set" + key
|
||||
deleteExisting = 0 # This one is still OK
|
||||
else:
|
||||
deleteExisting = 1 # No good to us
|
||||
if key in self.mapFuncs or key in self.propMapGet:
|
||||
newKey = "Set" + key
|
||||
else:
|
||||
newKey = key
|
||||
item.wasProperty = 1
|
||||
self.mapFuncs[newKey] = item
|
||||
if deleteExisting:
|
||||
del self.propMapPut[key]
|
||||
|
||||
def _propMapGetCheck_(self,key,item):
|
||||
ins, outs, opts = self.CountInOutOptArgs(item.desc[2])
|
||||
if ins > 0: # if a Get property takes _any_ in args:
|
||||
if item.desc[6]==ins or ins==opts:
|
||||
newKey = "Get" + key
|
||||
deleteExisting = 0 # This one is still OK
|
||||
else:
|
||||
deleteExisting = 1 # No good to us
|
||||
if key in self.mapFuncs:
|
||||
newKey = "Get" + key
|
||||
else:
|
||||
newKey = key
|
||||
item.wasProperty = 1
|
||||
self.mapFuncs[newKey] = item
|
||||
if deleteExisting:
|
||||
del self.propMapGet[key]
|
||||
|
||||
def _AddFunc_(self,typeinfo,fdesc,bForUser):
|
||||
id = fdesc.memid
|
||||
funcflags = fdesc.wFuncFlags
|
||||
try:
|
||||
names = typeinfo.GetNames(id)
|
||||
name=names[0]
|
||||
except pythoncom.ole_error:
|
||||
name = ""
|
||||
names = None
|
||||
|
||||
doc = None
|
||||
try:
|
||||
if bForUser:
|
||||
doc = typeinfo.GetDocumentation(id)
|
||||
except pythoncom.ole_error:
|
||||
pass
|
||||
|
||||
if id==0 and name:
|
||||
self.defaultDispatchName = name
|
||||
|
||||
invkind = fdesc.invkind
|
||||
|
||||
# We need to translate any Alias', Enums, structs etc in result and args
|
||||
typerepr, flag, defval = fdesc.rettype
|
||||
# sys.stderr.write("%s result - %s -> " % (name, typerepr))
|
||||
typerepr, resultCLSID, resultDoc = _ResolveType(typerepr, typeinfo)
|
||||
# sys.stderr.write("%s\n" % (typerepr,))
|
||||
fdesc.rettype = typerepr, flag, defval, resultCLSID
|
||||
# Translate any Alias or Enums in argument list.
|
||||
argList = []
|
||||
for argDesc in fdesc.args:
|
||||
typerepr, flag, defval = argDesc
|
||||
# sys.stderr.write("%s arg - %s -> " % (name, typerepr))
|
||||
arg_type, arg_clsid, arg_doc = _ResolveType(typerepr, typeinfo)
|
||||
argDesc = arg_type, flag, defval, arg_clsid
|
||||
# sys.stderr.write("%s\n" % (argDesc[0],))
|
||||
argList.append(argDesc)
|
||||
fdesc.args = tuple(argList)
|
||||
|
||||
hidden = (funcflags & pythoncom.FUNCFLAG_FHIDDEN) != 0
|
||||
if invkind == pythoncom.INVOKE_PROPERTYGET:
|
||||
map = self.propMapGet
|
||||
# This is not the best solution, but I dont think there is
|
||||
# one without specific "set" syntax.
|
||||
# If there is a single PUT or PUTREF, it will function as a property.
|
||||
# If there are both, then the PUT remains a property, and the PUTREF
|
||||
# gets transformed into a function.
|
||||
# (in vb, PUT=="obj=other_obj", PUTREF="set obj=other_obj
|
||||
elif invkind in (pythoncom.INVOKE_PROPERTYPUT, pythoncom.INVOKE_PROPERTYPUTREF):
|
||||
# Special case
|
||||
existing = self.propMapPut.get(name, None)
|
||||
if existing is not None:
|
||||
if existing.desc[4]==pythoncom.INVOKE_PROPERTYPUT: # Keep this one
|
||||
map = self.mapFuncs
|
||||
name = "Set"+name
|
||||
else: # Existing becomes a func.
|
||||
existing.wasProperty = 1
|
||||
self.mapFuncs["Set"+name]=existing
|
||||
map = self.propMapPut # existing gets overwritten below.
|
||||
else:
|
||||
map = self.propMapPut # first time weve seen it.
|
||||
|
||||
elif invkind == pythoncom.INVOKE_FUNC:
|
||||
map = self.mapFuncs
|
||||
else:
|
||||
map = None
|
||||
if not map is None:
|
||||
# if map.has_key(name):
|
||||
# sys.stderr.write("Warning - overwriting existing method/attribute %s\n" % name)
|
||||
map[name] = MapEntry(tuple(fdesc), names, doc, resultCLSID, resultDoc, hidden)
|
||||
# any methods that can't be reached via DISPATCH we return None
|
||||
# for, so dynamic dispatch doesnt see it.
|
||||
if fdesc.funckind != pythoncom.FUNC_DISPATCH:
|
||||
return None
|
||||
return (name,map)
|
||||
return None
|
||||
|
||||
def _AddVar_(self,typeinfo,fdesc,bForUser):
|
||||
### need pythoncom.VARFLAG_FRESTRICTED ...
|
||||
### then check it
|
||||
|
||||
if fdesc.varkind == pythoncom.VAR_DISPATCH:
|
||||
id = fdesc.memid
|
||||
names = typeinfo.GetNames(id)
|
||||
# Translate any Alias or Enums in result.
|
||||
typerepr, flags, defval = fdesc.elemdescVar
|
||||
typerepr, resultCLSID, resultDoc = _ResolveType(typerepr, typeinfo)
|
||||
fdesc.elemdescVar = typerepr, flags, defval
|
||||
doc = None
|
||||
try:
|
||||
if bForUser: doc = typeinfo.GetDocumentation(id)
|
||||
except pythoncom.ole_error:
|
||||
pass
|
||||
|
||||
# handle the enumerator specially
|
||||
map = self.propMap
|
||||
# Check if the element is hidden.
|
||||
hidden = 0
|
||||
if hasattr(fdesc,"wVarFlags"):
|
||||
hidden = (fdesc.wVarFlags & 0x40) != 0 # VARFLAG_FHIDDEN
|
||||
map[names[0]] = MapEntry(tuple(fdesc), names, doc, resultCLSID, resultDoc, hidden)
|
||||
return (names[0],map)
|
||||
else:
|
||||
return None
|
||||
|
||||
def Build(self, typeinfo, attr, bForUser = 1):
|
||||
self.clsid = attr[0]
|
||||
self.bIsDispatch = (attr.wTypeFlags & pythoncom.TYPEFLAG_FDISPATCHABLE) != 0
|
||||
if typeinfo is None: return
|
||||
# Loop over all methods
|
||||
for j in range(attr[6]):
|
||||
fdesc = typeinfo.GetFuncDesc(j)
|
||||
self._AddFunc_(typeinfo,fdesc,bForUser)
|
||||
|
||||
# Loop over all variables (ie, properties)
|
||||
for j in range(attr[7]):
|
||||
fdesc = typeinfo.GetVarDesc(j)
|
||||
self._AddVar_(typeinfo,fdesc,bForUser)
|
||||
|
||||
# Now post-process the maps. For any "Get" or "Set" properties
|
||||
# that have arguments, we must turn them into methods. If a method
|
||||
# of the same name already exists, change the name.
|
||||
for key, item in list(self.propMapGet.items()):
|
||||
self._propMapGetCheck_(key,item)
|
||||
|
||||
for key, item in list(self.propMapPut.items()):
|
||||
self._propMapPutCheck_(key,item)
|
||||
|
||||
def CountInOutOptArgs(self, argTuple):
|
||||
"Return tuple counting in/outs/OPTS. Sum of result may not be len(argTuple), as some args may be in/out."
|
||||
ins = out = opts = 0
|
||||
for argCheck in argTuple:
|
||||
inOut = argCheck[1]
|
||||
if inOut==0:
|
||||
ins = ins + 1
|
||||
out = out + 1
|
||||
else:
|
||||
if inOut & pythoncom.PARAMFLAG_FIN:
|
||||
ins = ins + 1
|
||||
if inOut & pythoncom.PARAMFLAG_FOPT:
|
||||
opts = opts + 1
|
||||
if inOut & pythoncom.PARAMFLAG_FOUT:
|
||||
out = out + 1
|
||||
return ins, out, opts
|
||||
|
||||
def MakeFuncMethod(self, entry, name, bMakeClass = 1):
|
||||
# If we have a type description, and not varargs...
|
||||
if entry.desc is not None and (len(entry.desc) < 6 or entry.desc[6]!=-1):
|
||||
return self.MakeDispatchFuncMethod(entry, name, bMakeClass)
|
||||
else:
|
||||
return self.MakeVarArgsFuncMethod(entry, name, bMakeClass)
|
||||
|
||||
def MakeDispatchFuncMethod(self, entry, name, bMakeClass = 1):
|
||||
fdesc = entry.desc
|
||||
doc = entry.doc
|
||||
names = entry.names
|
||||
ret = []
|
||||
if bMakeClass:
|
||||
linePrefix = "\t"
|
||||
defNamedOptArg = "defaultNamedOptArg"
|
||||
defNamedNotOptArg = "defaultNamedNotOptArg"
|
||||
defUnnamedArg = "defaultUnnamedArg"
|
||||
else:
|
||||
linePrefix = ""
|
||||
defNamedOptArg = "pythoncom.Missing"
|
||||
defNamedNotOptArg = "pythoncom.Missing"
|
||||
defUnnamedArg = "pythoncom.Missing"
|
||||
defOutArg = "pythoncom.Missing"
|
||||
id = fdesc[0]
|
||||
|
||||
s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):'
|
||||
ret.append(s)
|
||||
if doc and doc[1]:
|
||||
ret.append(linePrefix + '\t' + _makeDocString(doc[1]))
|
||||
|
||||
# print "fdesc is ", fdesc
|
||||
|
||||
resclsid = entry.GetResultCLSID()
|
||||
if resclsid:
|
||||
resclsid = "'%s'" % resclsid
|
||||
else:
|
||||
resclsid = 'None'
|
||||
# Strip the default values from the arg desc
|
||||
retDesc = fdesc[8][:2]
|
||||
argsDesc = tuple([what[:2] for what in fdesc[2]])
|
||||
# The runtime translation of the return types is expensive, so when we know the
|
||||
# return type of the function, there is no need to check the type at runtime.
|
||||
# To qualify, this function must return a "simple" type, and have no byref args.
|
||||
# Check if we have byrefs or anything in the args which mean we still need a translate.
|
||||
param_flags = [what[1] for what in fdesc[2]]
|
||||
bad_params = [flag for flag in param_flags if flag & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FRETVAL)!=0]
|
||||
s = None
|
||||
if len(bad_params)==0 and len(retDesc)==2 and retDesc[1]==0:
|
||||
rd = retDesc[0]
|
||||
if rd in NoTranslateMap:
|
||||
s = '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, _BuildArgList(fdesc, names))
|
||||
elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]:
|
||||
s = '%s\tret = self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)\n' % (linePrefix, id, fdesc[4], retDesc, repr(argsDesc), _BuildArgList(fdesc, names))
|
||||
s = s + '%s\tif ret is not None:\n' % (linePrefix,)
|
||||
if rd == pythoncom.VT_UNKNOWN:
|
||||
s = s + "%s\t\t# See if this IUnknown is really an IDispatch\n" % (linePrefix,)
|
||||
s = s + "%s\t\ttry:\n" % (linePrefix,)
|
||||
s = s + "%s\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" % (linePrefix,)
|
||||
s = s + "%s\t\texcept pythoncom.error:\n" % (linePrefix,)
|
||||
s = s + "%s\t\t\treturn ret\n" % (linePrefix,)
|
||||
s = s + '%s\t\tret = Dispatch(ret, %s, %s)\n' % (linePrefix,repr(name), resclsid)
|
||||
s = s + '%s\treturn ret' % (linePrefix)
|
||||
elif rd == pythoncom.VT_BSTR:
|
||||
s = "%s\t# Result is a Unicode object\n" % (linePrefix,)
|
||||
s = s + '%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, repr(argsDesc), _BuildArgList(fdesc, names))
|
||||
# else s remains None
|
||||
if s is None:
|
||||
s = '%s\treturn self._ApplyTypes_(%d, %s, %s, %s, %s, %s%s)' % (linePrefix, id, fdesc[4], retDesc, argsDesc, repr(name), resclsid, _BuildArgList(fdesc, names))
|
||||
|
||||
ret.append(s)
|
||||
ret.append("")
|
||||
return ret
|
||||
|
||||
def MakeVarArgsFuncMethod(self, entry, name, bMakeClass = 1):
|
||||
fdesc = entry.desc
|
||||
names = entry.names
|
||||
doc = entry.doc
|
||||
ret = []
|
||||
argPrefix = "self"
|
||||
if bMakeClass:
|
||||
linePrefix = "\t"
|
||||
else:
|
||||
linePrefix = ""
|
||||
ret.append(linePrefix + 'def ' + name + '(' + argPrefix + ', *args):')
|
||||
if doc and doc[1]: ret.append(linePrefix + '\t' + _makeDocString(doc[1]))
|
||||
if fdesc:
|
||||
invoketype = fdesc[4]
|
||||
else:
|
||||
invoketype = pythoncom.DISPATCH_METHOD
|
||||
s = linePrefix + '\treturn self._get_good_object_(self._oleobj_.Invoke(*(('
|
||||
ret.append(s + str(entry.dispid) + ",0,%d,1)+args)),'%s')" % (invoketype, names[0]))
|
||||
ret.append("")
|
||||
return ret
|
||||
|
||||
# Note - "DispatchItem" poorly named - need a new intermediate class.
|
||||
class VTableItem(DispatchItem):
|
||||
def Build(self, typeinfo, attr, bForUser = 1):
|
||||
DispatchItem.Build(self, typeinfo, attr, bForUser)
|
||||
assert typeinfo is not None, "Cant build vtables without type info!"
|
||||
|
||||
meth_list = list(self.mapFuncs.values()) + list(self.propMapGet.values()) + list(self.propMapPut.values())
|
||||
|
||||
if sys.version_info < (2,4):
|
||||
def cmp_vtable_off(m1, m2):
|
||||
return cmp(m1.desc[7], m2.desc[7])
|
||||
meth_list.sort(cmp_vtable_off)
|
||||
else:
|
||||
meth_list.sort(key=lambda m: m.desc[7])
|
||||
|
||||
# Now turn this list into the run-time representation
|
||||
# (ready for immediate use or writing to gencache)
|
||||
self.vtableFuncs = []
|
||||
for entry in meth_list:
|
||||
self.vtableFuncs.append( (entry.names, entry.dispid, entry.desc) )
|
||||
|
||||
# A Lazy dispatch item - builds an item on request using info from
|
||||
# an ITypeComp. The dynamic module makes the called to build each item,
|
||||
# and also holds the references to the typeinfo and typecomp.
|
||||
class LazyDispatchItem(DispatchItem):
|
||||
typename = "LazyDispatchItem"
|
||||
def __init__(self, attr, doc):
|
||||
self.clsid = attr[0]
|
||||
DispatchItem.__init__(self, None, attr, doc, 0)
|
||||
|
||||
typeSubstMap = {
|
||||
pythoncom.VT_INT: pythoncom.VT_I4,
|
||||
pythoncom.VT_UINT: pythoncom.VT_UI4,
|
||||
pythoncom.VT_HRESULT: pythoncom.VT_I4,
|
||||
}
|
||||
|
||||
def _ResolveType(typerepr, itypeinfo):
|
||||
# Resolve VT_USERDEFINED (often aliases or typed IDispatches)
|
||||
|
||||
if type(typerepr)==tuple:
|
||||
indir_vt, subrepr = typerepr
|
||||
if indir_vt == pythoncom.VT_PTR:
|
||||
# If it is a VT_PTR to a VT_USERDEFINED that is an IDispatch/IUnknown,
|
||||
# then it resolves to simply the object.
|
||||
# Otherwise, it becomes a ByRef of the resolved type
|
||||
# We need to drop an indirection level on pointer to user defined interfaces.
|
||||
# eg, (VT_PTR, (VT_USERDEFINED, somehandle)) needs to become VT_DISPATCH
|
||||
# only when "somehandle" is an object.
|
||||
# but (VT_PTR, (VT_USERDEFINED, otherhandle)) doesnt get the indirection dropped.
|
||||
was_user = type(subrepr)==tuple and subrepr[0]==pythoncom.VT_USERDEFINED
|
||||
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
|
||||
if was_user and subrepr in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN, pythoncom.VT_RECORD]:
|
||||
# Drop the VT_PTR indirection
|
||||
return subrepr, sub_clsid, sub_doc
|
||||
# Change PTR indirection to byref
|
||||
return subrepr | pythoncom.VT_BYREF, sub_clsid, sub_doc
|
||||
if indir_vt == pythoncom.VT_SAFEARRAY:
|
||||
# resolve the array element, and convert to VT_ARRAY
|
||||
subrepr, sub_clsid, sub_doc = _ResolveType(subrepr, itypeinfo)
|
||||
return pythoncom.VT_ARRAY | subrepr, sub_clsid, sub_doc
|
||||
if indir_vt == pythoncom.VT_CARRAY: # runtime has no support for this yet.
|
||||
# resolve the array element, and convert to VT_CARRAY
|
||||
# sheesh - return _something_
|
||||
return pythoncom.VT_CARRAY, None, None
|
||||
if indir_vt == pythoncom.VT_USERDEFINED:
|
||||
try:
|
||||
resultTypeInfo = itypeinfo.GetRefTypeInfo(subrepr)
|
||||
except pythoncom.com_error as details:
|
||||
if details.hresult in [winerror.TYPE_E_CANTLOADLIBRARY, winerror.TYPE_E_LIBNOTREGISTERED]:
|
||||
# an unregistered interface
|
||||
return pythoncom.VT_UNKNOWN, None, None
|
||||
raise
|
||||
|
||||
resultAttr = resultTypeInfo.GetTypeAttr()
|
||||
typeKind = resultAttr.typekind
|
||||
if typeKind == pythoncom.TKIND_ALIAS:
|
||||
tdesc = resultAttr.tdescAlias
|
||||
return _ResolveType(tdesc, resultTypeInfo)
|
||||
elif typeKind in [pythoncom.TKIND_ENUM, pythoncom.TKIND_MODULE]:
|
||||
# For now, assume Long
|
||||
return pythoncom.VT_I4, None, None
|
||||
|
||||
elif typeKind == pythoncom.TKIND_DISPATCH:
|
||||
clsid = resultTypeInfo.GetTypeAttr()[0]
|
||||
retdoc = resultTypeInfo.GetDocumentation(-1)
|
||||
return pythoncom.VT_DISPATCH, clsid, retdoc
|
||||
|
||||
elif typeKind in [pythoncom.TKIND_INTERFACE,
|
||||
pythoncom.TKIND_COCLASS]:
|
||||
# XXX - should probably get default interface for CO_CLASS???
|
||||
clsid = resultTypeInfo.GetTypeAttr()[0]
|
||||
retdoc = resultTypeInfo.GetDocumentation(-1)
|
||||
return pythoncom.VT_UNKNOWN, clsid, retdoc
|
||||
|
||||
elif typeKind == pythoncom.TKIND_RECORD:
|
||||
return pythoncom.VT_RECORD, None, None
|
||||
raise NotSupportedException("Can not resolve alias or user-defined type")
|
||||
return typeSubstMap.get(typerepr,typerepr), None, None
|
||||
|
||||
def _BuildArgList(fdesc, names):
|
||||
"Builds list of args to the underlying Invoke method."
|
||||
# Word has TypeInfo for Insert() method, but says "no args"
|
||||
numArgs = max(fdesc[6], len(fdesc[2]))
|
||||
names = list(names)
|
||||
while None in names:
|
||||
i = names.index(None)
|
||||
names[i] = "arg%d" % (i,)
|
||||
# We've seen 'source safe' libraries offer the name of 'ret' params in
|
||||
# 'names' - although we can't reproduce this, it would be insane to offer
|
||||
# more args than we have arg infos for - hence the upper limit on names...
|
||||
names = list(map(MakePublicAttributeName, names[1:(numArgs + 1)]))
|
||||
name_num = 0
|
||||
while len(names) < numArgs:
|
||||
names.append("arg%d" % (len(names),))
|
||||
# As per BuildCallList(), avoid huge lines.
|
||||
# Hack a "\n" at the end of every 5th name - "strides" would be handy
|
||||
# here but don't exist in 2.2
|
||||
for i in range(0, len(names), 5):
|
||||
names[i] = names[i] + "\n\t\t\t"
|
||||
return "," + ", ".join(names)
|
||||
|
||||
valid_identifier_chars = string.ascii_letters + string.digits + "_"
|
||||
|
||||
def demunge_leading_underscores(className):
|
||||
i = 0
|
||||
while className[i] == "_":
|
||||
i += 1
|
||||
assert i >= 2, "Should only be here with names starting with '__'"
|
||||
return className[i-1:] + className[:i-1]
|
||||
|
||||
# Given a "public name" (eg, the name of a class, function, etc)
|
||||
# make sure it is a legal (and reasonable!) Python name.
|
||||
def MakePublicAttributeName(className, is_global = False):
|
||||
# Given a class attribute that needs to be public, convert it to a
|
||||
# reasonable name.
|
||||
# Also need to be careful that the munging doesnt
|
||||
# create duplicates - eg, just removing a leading "_" is likely to cause
|
||||
# a clash.
|
||||
# if is_global is True, then the name is a global variable that may
|
||||
# overwrite a builtin - eg, "None"
|
||||
if className[:2]=='__':
|
||||
return demunge_leading_underscores(className)
|
||||
elif className == 'None':
|
||||
# assign to None is evil (and SyntaxError in 2.4, even though
|
||||
# iskeyword says False there) - note that if it was a global
|
||||
# it would get picked up below
|
||||
className = 'NONE'
|
||||
elif iskeyword(className):
|
||||
# most keywords are lower case (except True, False etc in py3k)
|
||||
ret = className.capitalize()
|
||||
# but those which aren't get forced upper.
|
||||
if ret == className:
|
||||
ret = ret.upper()
|
||||
return ret
|
||||
elif is_global and hasattr(__builtins__, className):
|
||||
# builtins may be mixed case. If capitalizing it doesn't change it,
|
||||
# force to all uppercase (eg, "None", "True" become "NONE", "TRUE"
|
||||
ret = className.capitalize()
|
||||
if ret==className: # didn't change - force all uppercase.
|
||||
ret = ret.upper()
|
||||
return ret
|
||||
# Strip non printable chars
|
||||
return ''.join([char for char in className if char in valid_identifier_chars])
|
||||
|
||||
# Given a default value passed by a type library, return a string with
|
||||
# an appropriate repr() for the type.
|
||||
# Takes a raw ELEMDESC and returns a repr string, or None
|
||||
# (NOTE: The string itself may be '"None"', which is valid, and different to None.
|
||||
# XXX - To do: Dates are probably screwed, but can they come in?
|
||||
def MakeDefaultArgRepr(defArgVal):
|
||||
try:
|
||||
inOut = defArgVal[1]
|
||||
except IndexError:
|
||||
# something strange - assume is in param.
|
||||
inOut = pythoncom.PARAMFLAG_FIN
|
||||
|
||||
if inOut & pythoncom.PARAMFLAG_FHASDEFAULT:
|
||||
# times need special handling...
|
||||
val = defArgVal[2]
|
||||
if isinstance(val, datetime.datetime):
|
||||
# VARIANT <-> SYSTEMTIME conversions always lose any sub-second
|
||||
# resolution, so just use a 'timetuple' here.
|
||||
return repr(tuple(val.utctimetuple()))
|
||||
if type(val) is TimeType:
|
||||
# must be the 'old' pywintypes time object...
|
||||
year=val.year; month=val.month; day=val.day; hour=val.hour; minute=val.minute; second=val.second; msec=val.msec
|
||||
return "pywintypes.Time((%(year)d, %(month)d, %(day)d, %(hour)d, %(minute)d, %(second)d,0,0,0,%(msec)d))" % locals()
|
||||
return repr(val)
|
||||
return None
|
||||
|
||||
def BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg, is_comment = False):
|
||||
"Builds a Python declaration for a method."
|
||||
# Names[0] is the func name - param names are from 1.
|
||||
numArgs = len(fdesc[2])
|
||||
numOptArgs = fdesc[6]
|
||||
strval = ''
|
||||
if numOptArgs==-1: # Special value that says "var args after here"
|
||||
firstOptArg = numArgs
|
||||
numArgs = numArgs - 1
|
||||
else:
|
||||
firstOptArg = numArgs - numOptArgs
|
||||
for arg in range(numArgs):
|
||||
try:
|
||||
argName = names[arg+1]
|
||||
namedArg = argName is not None
|
||||
except IndexError:
|
||||
namedArg = 0
|
||||
if not namedArg: argName = "arg%d" % (arg)
|
||||
thisdesc = fdesc[2][arg]
|
||||
# See if the IDL specified a default value
|
||||
defArgVal = MakeDefaultArgRepr(thisdesc)
|
||||
if defArgVal is None:
|
||||
# Out params always get their special default
|
||||
if thisdesc[1] & (pythoncom.PARAMFLAG_FOUT | pythoncom.PARAMFLAG_FIN) == pythoncom.PARAMFLAG_FOUT:
|
||||
defArgVal = defOutArg
|
||||
else:
|
||||
# Unnamed arg - always allow default values.
|
||||
if namedArg:
|
||||
# Is a named argument
|
||||
if arg >= firstOptArg:
|
||||
defArgVal = defNamedOptArg
|
||||
else:
|
||||
defArgVal = defNamedNotOptArg
|
||||
else:
|
||||
defArgVal = defUnnamedArg
|
||||
|
||||
argName = MakePublicAttributeName(argName)
|
||||
# insanely long lines with an 'encoding' flag crashes python 2.4.0
|
||||
# keep 5 args per line
|
||||
# This may still fail if the arg names are insane, but that seems
|
||||
# unlikely. See also _BuildArgList()
|
||||
if (arg+1) % 5 == 0:
|
||||
strval = strval + "\n"
|
||||
if is_comment:
|
||||
strval = strval + "#"
|
||||
strval = strval + "\t\t\t"
|
||||
strval = strval + ", " + argName
|
||||
if defArgVal:
|
||||
strval = strval + "=" + defArgVal
|
||||
if numOptArgs==-1:
|
||||
strval = strval + ", *" + names[-1]
|
||||
|
||||
return strval
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
print("Use 'makepy.py' to generate Python code - this module is just a helper")
|
||||