Пример #1
0
static PyObject *
cups_modelSort (PyObject *self, PyObject *args)
{
  PyObject *Oa, *Ob, *a, *b;
  int len_a, len_b;
  size_t size_a, size_b;
  wchar_t *wca, *wcb;

  if (!PyArg_ParseTuple (args, "OO", &Oa, &Ob))
    return NULL;

  a = PyUnicode_FromObject (Oa);
  b = PyUnicode_FromObject (Ob);
  if (a == NULL || b == NULL || !PyUnicode_Check (a) || !PyUnicode_Check (b)) {
    if (a) {
      Py_DECREF (a);
    }
    if (b) {
      Py_DECREF (b);
    }

    PyErr_SetString (PyExc_TypeError, "Unable to convert to Unicode");
    return NULL;
  }

  len_a = 1 + PyUnicode_GetSize (a);
  size_a = len_a * sizeof (wchar_t);
  if ((size_a / sizeof (wchar_t)) != len_a) {
    Py_DECREF (a);
    Py_DECREF (b);
    PyErr_SetString (PyExc_RuntimeError, "String too long");
    return NULL;
  }

  len_b = 1 + PyUnicode_GetSize (b);
  size_b = len_b * sizeof (wchar_t);
  if ((size_b / sizeof (wchar_t)) != len_b) {
    Py_DECREF (a);
    Py_DECREF (b);
    PyErr_SetString (PyExc_RuntimeError, "String too long");
    return NULL;
  }

  wca = malloc (size_a);
  wcb = malloc (size_b);
  if (wca == NULL || wcb == NULL) {
    Py_DECREF (a);
    Py_DECREF (b);
    free (wca);
    free (wcb);
    PyErr_SetString (PyExc_RuntimeError, "Insufficient memory");
    return NULL;
  }

  PyUnicode_AsWideChar ((PyUnicodeObject *) a, wca, size_a);
  PyUnicode_AsWideChar ((PyUnicodeObject *) b, wcb, size_b);
  Py_DECREF (a);
  Py_DECREF (b);
  return Py_BuildValue ("i", do_model_compare (wca, wcb));
}
Пример #2
0
// Collator.startswith {{{
static PyObject *
icu_Collator_collation_order(icu_Collator *self, PyObject *args, PyObject *kwargs) {
    PyObject *a_;
    int32_t asz;
    int32_t actual_a;
    UChar *a;
    wchar_t *aw;
    UErrorCode status = U_ZERO_ERROR;
    UCollationElements *iter = NULL;
    int order = 0, len = -1;
  
    if (!PyArg_ParseTuple(args, "U", &a_)) return NULL;
    asz = (int32_t)PyUnicode_GetSize(a_); 
    
    a = (UChar*)calloc(asz*4 + 2, sizeof(UChar));
    aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t));

    if (a == NULL || aw == NULL ) return PyErr_NoMemory();

    actual_a = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1);
    if (actual_a > -1) {
        u_strFromWCS(a, asz*4 + 1, &actual_a, aw, -1, &status);
        iter = ucol_openElements(self->collator, a, actual_a, &status);
        if (iter != NULL && U_SUCCESS(status)) {
            order = ucol_next(iter, &status);
            len = ucol_getOffset(iter);
            ucol_closeElements(iter); iter = NULL;
        }
    }

    free(a); free(aw); 
    return Py_BuildValue("ii", order, len);
} // }}}
Пример #3
0
PYTHON_METHOD_DEFINITION(ptVaultImageNode, setTitleW, args)
{
    PyObject* textObj;
    if (!PyArg_ParseTuple(args, "O", &textObj))
    {
        PyErr_SetString(PyExc_TypeError, "setTitleW expects a unicode string");
        PYTHON_RETURN_ERROR;
    }
    if (PyUnicode_Check(textObj))
    {
        int strLen = PyUnicode_GetSize(textObj);
        wchar_t* title = new wchar_t[strLen + 1];
        PyUnicode_AsWideChar((PyUnicodeObject*)textObj, title, strLen);
        title[strLen] = L'\0';
        self->fThis->Image_SetTitleW(title);
        delete [] title;
        PYTHON_RETURN_NONE;
    }
    else if (PyString_Check(textObj))
    {
        // we'll allow this, just in case something goes weird
        char* title = PyString_AsString(textObj);
        self->fThis->Image_SetTitle(title);
        PYTHON_RETURN_NONE;
    }
    PyErr_SetString(PyExc_TypeError, "setTitleW expects a unicode string");
    PYTHON_RETURN_ERROR;
}
PYTHON_METHOD_DEFINITION(ptGUIControlMultiLineEdit, insertStringW, args)
{
    PyObject* textObj;
    if (!PyArg_ParseTuple(args, "O", &textObj))
    {
        PyErr_SetString(PyExc_TypeError, "insertStringW expects a unicode string");
        PYTHON_RETURN_ERROR;
    }
    if (PyUnicode_Check(textObj))
    {
        int strLen = PyUnicode_GetSize(textObj);
        wchar_t* temp = new wchar_t[strLen + 1];
        PyUnicode_AsWideChar((PyUnicodeObject*)textObj, temp, strLen);
        temp[strLen] = L'\0';
        self->fThis->InsertStringW(temp);
        delete [] temp;
        PYTHON_RETURN_NONE;
    }
    else if (PyString_Check(textObj))
    {
        // we'll allow this, just in case something goes weird
        char* temp = PyString_AsString(textObj);
        self->fThis->InsertString(temp);
        PYTHON_RETURN_NONE;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError, "insertStringW expects a unicode string");
        PYTHON_RETURN_ERROR;
    }
}
Пример #5
0
PYTHON_METHOD_DEFINITION(ptImage, saveAsPNG, args)
{
    PyObject* filenameObj;
    if (!PyArg_ParseTuple(args, "O", &filenameObj))
    {
        PyErr_SetString(PyExc_TypeError, "saveAsPNG expects a string");
        PYTHON_RETURN_ERROR;
    }

    if (PyUnicode_Check(filenameObj))
    {
        int strLen = PyUnicode_GetSize(filenameObj);
        wchar_t* text = new wchar_t[strLen + 1];
        PyUnicode_AsWideChar((PyUnicodeObject*)filenameObj, text, strLen);
        text[strLen] = L'\0';
        self->fThis->SaveAsPNG(text);
        delete [] text;
        PYTHON_RETURN_NONE;
    }
    else if (PyString_Check(filenameObj))
    {
        // we'll allow this, just in case something goes weird
        char* text = PyString_AsString(filenameObj);
        wchar_t* wText = hsStringToWString(text);
        self->fThis->SaveAsPNG(wText);
        delete [] wText;
        PYTHON_RETURN_NONE;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError, "saveAsPNG expects a string");
        PYTHON_RETURN_ERROR;
    }
}
Пример #6
0
PYTHON_METHOD_DEFINITION(ptGUIControlListBox, addBranchW, args)
{
    PyObject* textObj;
    char initiallyOpen;
    if (!PyArg_ParseTuple(args, "Ob", &textObj, &initiallyOpen))
    {
        PyErr_SetString(PyExc_TypeError, "addBranchW expects a unicode string and a boolean");
        PYTHON_RETURN_ERROR;
    }
    if (PyUnicode_Check(textObj))
    {
        int strLen = PyUnicode_GetSize(textObj);
        wchar_t* name = new wchar_t[strLen + 1];
        PyUnicode_AsWideChar((PyUnicodeObject*)textObj, name, strLen);
        name[strLen] = L'\0';
        self->fThis->AddBranch(ST::string::from_wchar(name), initiallyOpen != 0);
        delete [] name;
        PYTHON_RETURN_NONE;
    }
    else if (PyString_Check(textObj))
    {
        // we'll allow this, just in case something goes weird
        char* name = PyString_AsString(textObj);
        self->fThis->AddBranch(name, initiallyOpen != 0);
        PYTHON_RETURN_NONE;
    }
    else
    {
        PyErr_SetString(PyExc_TypeError, "addBranchW expects a unicode string and a boolean");
        PYTHON_RETURN_ERROR;
    }
}
Пример #7
0
/* u - a single wchar_t character */
static PyObject *
u_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    Py_ssize_t len;
    wchar_t chars[2];
    if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);

    len = PyUnicode_AsWideChar(value, chars, 2);
    if (len != 1) {
        Py_DECREF(value);
        PyErr_SetString(PyExc_TypeError,
                        "one character unicode string expected");
        return NULL;
    }

    *(wchar_t *)ptr = chars[0];
    Py_DECREF(value);

    _RET(value);
}
Пример #8
0
static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length)
{
    Py_ssize_t size;

    /* It's easier to calculate in characters than in bytes */
    length /= sizeof(wchar_t);

    if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
    size = PyUnicode_GET_SIZE(value);
    if (size > length) {
        PyErr_Format(PyExc_ValueError,
                     "string too long (%zd, maximum length %zd)",
                     size, length);
        Py_DECREF(value);
        return NULL;
    } else if (size < length-1)
        /* copy terminating NUL character if there is space */
        size += 1;
    PyUnicode_AsWideChar(value, (wchar_t *)ptr, size);
    return value;
}
Пример #9
0
// Collator.find {{{
static PyObject *
icu_Collator_find(icu_Collator *self, PyObject *args, PyObject *kwargs) {
    PyObject *a_, *b_;
    int32_t asz, bsz;
    UChar *a, *b;
    wchar_t *aw, *bw;
    UErrorCode status = U_ZERO_ERROR;
    UStringSearch *search = NULL;
    int32_t pos = -1, length = -1;
  
    if (!PyArg_ParseTuple(args, "UU", &a_, &b_)) return NULL;
    asz = (int32_t)PyUnicode_GetSize(a_); bsz = (int32_t)PyUnicode_GetSize(b_);
    
    a = (UChar*)calloc(asz*4 + 2, sizeof(UChar));
    b = (UChar*)calloc(bsz*4 + 2, sizeof(UChar));
    aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t));
    bw = (wchar_t*)calloc(bsz*4 + 2, sizeof(wchar_t));

    if (a == NULL || b == NULL || aw == NULL || bw == NULL) return PyErr_NoMemory();

    PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1);
    PyUnicode_AsWideChar((PyUnicodeObject*)b_, bw, bsz*4+1);
    u_strFromWCS(a, asz*4 + 1, NULL, aw, -1, &status);
    u_strFromWCS(b, bsz*4 + 1, NULL, bw, -1, &status);

    if (U_SUCCESS(status)) {
        search = usearch_openFromCollator(a, -1, b, -1, self->collator, NULL, &status);
        if (U_SUCCESS(status)) {
            pos = usearch_first(search, &status);
            if (pos != USEARCH_DONE) 
                length = usearch_getMatchedLength(search);
            else
                pos = -1;
        }
        if (search != NULL) usearch_close(search);
    }

    free(a); free(b); free(aw); free(bw);

    return Py_BuildValue("ii", pos, length);
} // }}}
Пример #10
0
static PyObject *
get_proper_case_filename(PyObject *self, PyObject *args)
{
    PyObject *arg_1;
    wchar_t filename_in[4096];
    wchar_t filename_out[4096];
    DWORD nchars;
    LPITEMIDLIST pidl;
    LPSHELLFOLDER pDesktopFolder;
    ULONG chEaten;
    HRESULT hr;
    DWORD dwAttributes;
    
    if (PyTuple_Size(args) < 1) {
        Py_RETURN_NONE;
    }
    arg_1 = PyTuple_GetItem(args, 0);
    if (! PyUnicode_Check(arg_1)) {
        Py_RETURN_NONE;
    }
    nchars = PyUnicode_AsWideChar((PyUnicodeObject *)arg_1, filename_in, 4095);
    if (nchars == 0) {
        Py_RETURN_NONE;
    }
    filename_in[nchars] = 0;
    /*
     * The following is taken from http://support.microsoft.com/kb/132750
     */
    if (FAILED(SHGetDesktopFolder(&pDesktopFolder))) {
        Py_RETURN_NONE;
    }
    dwAttributes = SFGAO_VALIDATE;
    hr = pDesktopFolder->lpVtbl->ParseDisplayName(pDesktopFolder,
                                                  NULL,
                                                  NULL,
                                                  filename_in,
                                                  &chEaten,
                                                  &pidl,
                                                  &dwAttributes);
    pDesktopFolder->lpVtbl->Release(pDesktopFolder);
    if (FAILED(hr)) {
        Py_RETURN_NONE;
    }
    if (! SHGetPathFromIDList(pidl, filename_out)) {
        CoTaskMemFree(pidl);
        Py_RETURN_NONE;
    }
    CoTaskMemFree(pidl);
    nchars = wcslen(filename_out);
    return PyUnicode_FromWideChar(filename_out,nchars);
}
Пример #11
0
std::wstring Py2WString(PyObject* pyValue)
{
    auto len = PyUnicode_GetSize(pyValue) + 1;
    wchar_t* w = new wchar_t[len];

    if (PyUnicode_AsWideChar((PYUNICODEASVARCHARARG1TYPE*)pyValue, w, len) < 0)
    {
        delete[] w;
        throw MI::Exception(L"PyUnicode_AsWideChar failed");
    }

    auto& value = std::wstring(w, len);
    delete[] w;
    return value;
}
static PyObject*
PyLocale_strcoll(PyObject* self, PyObject* args)
{
    PyObject *os1, *os2, *result = NULL;
    wchar_t *ws1 = NULL, *ws2 = NULL;
    Py_ssize_t len1, len2;
    
    if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2))
        return NULL;
    /* Convert the unicode strings to wchar[]. */
    len1 = PyUnicode_GET_SIZE(os1) + 1;
    ws1 = PyMem_MALLOC(len1 * sizeof(wchar_t));
    if (!ws1) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os1, ws1, len1) == -1)
        goto done;
    ws1[len1 - 1] = 0;
    len2 = PyUnicode_GET_SIZE(os2) + 1;
    ws2 = PyMem_MALLOC(len2 * sizeof(wchar_t));
    if (!ws2) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os2, ws2, len2) == -1)
        goto done;
    ws2[len2 - 1] = 0;
    /* Collate the strings. */
    result = PyLong_FromLong(wcscoll(ws1, ws2));
  done:
    /* Deallocate everything. */
    if (ws1) PyMem_FREE(ws1);
    if (ws2) PyMem_FREE(ws2);
    return result;
}
Пример #13
0
// Collator.startswith {{{
static PyObject *
icu_Collator_startswith(icu_Collator *self, PyObject *args, PyObject *kwargs) {
    PyObject *a_, *b_;
    int32_t asz, bsz;
    int32_t actual_a, actual_b;
    UChar *a, *b;
    wchar_t *aw, *bw;
    UErrorCode status = U_ZERO_ERROR;
    int ans = 0;
  
    if (!PyArg_ParseTuple(args, "UU", &a_, &b_)) return NULL;
    asz = (int32_t)PyUnicode_GetSize(a_); bsz = (int32_t)PyUnicode_GetSize(b_);
    if (asz < bsz) Py_RETURN_FALSE;
    if (bsz == 0) Py_RETURN_TRUE;
    
    a = (UChar*)calloc(asz*4 + 2, sizeof(UChar));
    b = (UChar*)calloc(bsz*4 + 2, sizeof(UChar));
    aw = (wchar_t*)calloc(asz*4 + 2, sizeof(wchar_t));
    bw = (wchar_t*)calloc(bsz*4 + 2, sizeof(wchar_t));

    if (a == NULL || b == NULL || aw == NULL || bw == NULL) return PyErr_NoMemory();

    actual_a = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)a_, aw, asz*4+1);
    actual_b = (int32_t)PyUnicode_AsWideChar((PyUnicodeObject*)b_, bw, bsz*4+1);
    if (actual_a > -1 && actual_b > -1) {
        u_strFromWCS(a, asz*4 + 1, &actual_a, aw, -1, &status);
        u_strFromWCS(b, bsz*4 + 1, &actual_b, bw, -1, &status);

        if (U_SUCCESS(status) && ucol_equal(self->collator, a, actual_b, b, actual_b))
            ans = 1;
    }

    free(a); free(b); free(aw); free(bw);
    if (ans) Py_RETURN_TRUE;
    Py_RETURN_FALSE;
} // }}}
Пример #14
0
static wstring
PyUnicode_AsWString(PyObject* obj)
{
    TWCHAR* wide_str_buf = new TWCHAR[TWCharBufferSize];
    wstring res;
    memset(wide_str_buf, 0, sizeof(TWCHAR) * TWCharBufferSize);

    Py_ssize_t size = PyUnicode_AsWideChar((PyUnicodeObject*) obj,
                                           (wchar_t*) wide_str_buf,
                                           TWCharBufferSize);
    if (size > 0) {
        res = wstring(wide_str_buf);
    }
    delete [] wide_str_buf;
    return res;
}
Пример #15
0
static int
find_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
{
    int result = 0; /* meaning not found */
    char buffer[MAXPATHLEN*2+1];  /* allow extra for key, '=', etc. */

    fseek(env_file, 0, SEEK_SET);
    while (!feof(env_file)) {
        char * p = fgets(buffer, MAXPATHLEN*2, env_file);
        wchar_t tmpbuffer[MAXPATHLEN*2+1];
        PyObject * decoded;
        size_t n;

        if (p == NULL)
            break;
        n = strlen(p);
        if (p[n - 1] != '\n') {
            /* line has overflowed - bail */
            break;
        }
        if (p[0] == '#')    /* Comment - skip */
            continue;
        decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape");
        if (decoded != NULL) {
            Py_ssize_t k;
            k = PyUnicode_AsWideChar(decoded,
                                     tmpbuffer, MAXPATHLEN * 2);
            Py_DECREF(decoded);
            if (k >= 0) {
                wchar_t * context = NULL;
                wchar_t * tok = wcstok_s(tmpbuffer, L" \t\r\n", &context);
                if ((tok != NULL) && !wcscmp(tok, key)) {
                    tok = wcstok_s(NULL, L" \t", &context);
                    if ((tok != NULL) && !wcscmp(tok, L"=")) {
                        tok = wcstok_s(NULL, L"\r\n", &context);
                        if (tok != NULL) {
                            wcsncpy(value, tok, MAXPATHLEN);
                            result = 1;
                            break;
                        }
                    }
                }
            }
        }
    }
    return result;
}
Пример #16
0
// Convert a Python object to a BSTR - allow embedded NULLs, None, etc.
BOOL PyWinObject_AsBstr(PyObject *stringObject, BSTR *pResult, BOOL bNoneOK /*= FALSE*/,DWORD *pResultLen /*= NULL*/)
{
	BOOL rc = TRUE;
	if (PyString_Check(stringObject))
		rc = PyString_AsBstr(stringObject, pResult);
	else if (PyUnicode_Check(stringObject))
	{
		// copy the value, including embedded NULLs
		int nchars = PyUnicode_GET_SIZE(stringObject);
		*pResult = SysAllocStringLen(NULL, nchars);
		if (*pResult) {
#if (PY_VERSION_HEX < 0x03020000)
#define PUAWC_TYPE PyUnicodeObject *
#else
#define PUAWC_TYPE PyObject *
#endif
			if (PyUnicode_AsWideChar((PUAWC_TYPE)stringObject, *pResult, nchars)==-1) {
				rc = FALSE;
			} else {
				// The SysAllocStringLen docs indicate that nchars+1 bytes are allocated,
				// and that normally a \0 is appened by the function.  It also states 
				// the \0 is not necessary!  While it seems to work fine without it,
				// we do copy it, as the previous code, which used SysAllocStringLen
				// with a non-NULL arg is documented clearly as appending the \0.
				(*pResult)[nchars] = 0;
			}
		}
	}
	else if (stringObject == Py_None) {
		if (bNoneOK) {
			*pResult = NULL;
		} else {
			PyErr_SetString(PyExc_TypeError, "None is not a valid string in this context");
			rc = FALSE;
		}
	} else {
		const char *tp_name = stringObject && stringObject->ob_type ? stringObject->ob_type->tp_name : "<NULL!!>";
		PyErr_Format(PyExc_TypeError, "Objects of type '%s' can not be converted to Unicode.", tp_name);
		rc = FALSE;
	}
	if (rc && !pResult) {
		PyErr_SetString(PyExc_MemoryError, "Allocating BSTR");
		return FALSE;
	}
	if (rc && pResultLen) *pResultLen = SysStringLen(*pResult);
	return rc;
}
Пример #17
0
void GetIndexOrName(PyObject *item, std::wstring& name, Py_ssize_t& i)
{
    name.clear();
    i = -1;

#ifndef IS_PY3K
    if (PyString_Check(item))
    {
        char* s = PyString_AsString(item);
        DWORD len = lstrlenA(s) + 1;
        wchar_t* w = new wchar_t[len];

        if (::MultiByteToWideChar(CP_ACP, 0, s, len, w, len) != len)
        {
            delete [] w;
            throw MI::Exception(L"MultiByteToWideChar failed");
        }
        name.assign(w, len);
        delete[] w;
    }
    else
#endif
    if (PyUnicode_Check(item))
    {
        Py_ssize_t len = PyUnicode_GetSize(item) + 1;
        wchar_t* w = new wchar_t[len];

        if (PyUnicode_AsWideChar((PYUNICODEASVARCHARARG1TYPE*)item, w, len) < 0)
        {
            delete[] w;
            throw MI::Exception(L"PyUnicode_AsWideChar failed");
        }
        name.assign(w, len);
        delete[] w;
    }
    else if (PyIndex_Check(item))
    {
        i = PyNumber_AsSsize_t(item, PyExc_IndexError);
        if (i == -1 && PyErr_Occurred())
            throw MI::Exception(L"Index error");
    }
    else
        throw MI::Exception(L"Invalid name or index");
}
Пример #18
0
static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length)
{
    Py_ssize_t size;

    /* It's easier to calculate in characters than in bytes */
    length /= sizeof(wchar_t);

    if (PyString_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                        "unicode string expected instead of %s instance",
                        value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
    size = PyUnicode_GET_SIZE(value);
    if (size > length) {
        PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
                     "string too long (%d, maximum length %d)",
#else
                     "string too long (%zd, maximum length %zd)",
#endif
                     size, length);
        Py_DECREF(value);
        return NULL;
    } else if (size < length-1)
        /* copy terminating NUL character if there is space */
        size += 1;
    PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
    return value;
}
Пример #19
0
static PyObject* PySendInput(PyObject *self, PyObject *args)
{
    INPUT *pInputs;
    int i;

    pInputs = (INPUT*)malloc(sizeof(INPUT) * PyTuple_Size(args));

    ZeroMemory(pInputs, sizeof(INPUT) * PyTuple_Size(args));

    for (i = 0; i < PyTuple_Size(args); ++i)
    {
        PyObject *type;
        PyObject *tpl = PyTuple_GetItem(args, i);

        if (!PyTuple_Check(tpl))
        {
            PyErr_SetString(PyExc_TypeError, "Arguments must be tuples.");
            goto err;
        }

        if (PyTuple_Size(tpl) != 2)
        {
            PyErr_SetString(PyExc_TypeError, "Arguments must be 2-tuples.");
            goto err;
        }

        type = PyTuple_GetItem(tpl, 0);
        if (!PyInt_Check(type))
        {
            PyErr_SetString(PyExc_TypeError, "Struct type must be int.");
            goto err;
        }

        switch (PyInt_AsLong(type))
        {
        case INPUT_MOUSE:
        {
            int dx, dy, mouseData, flags, time;
            PyObject *minput;

            minput = PyTuple_GetItem(tpl, 1);

            if (!PyTuple_Check(minput))
            {
                PyErr_SetString(PyExc_TypeError, "Structure must be a tuple");
                goto err;
            }

            if (!PyArg_ParseTuple(minput, "iiiii", &dx, &dy, &mouseData, &flags, &time))
                goto err;

            pInputs[i].type = INPUT_MOUSE;
            pInputs[i].mi.dx = dx;
            pInputs[i].mi.dy = dy;
            pInputs[i].mi.mouseData = mouseData;
            pInputs[i].mi.dwFlags = flags;
            pInputs[i].mi.time = time;

            break;
        }

        case INPUT_KEYBOARD:
        {
            HKL layout = GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), NULL));

            PyObject *kinput = PyTuple_GetItem(tpl, 1);

            if (!PyTuple_Check(kinput))
            {
                PyErr_SetString(PyExc_TypeError, "Structure must be a tuple");
                goto err;
            }

            PyObject *theChar;
            int type;
            if (!PyArg_ParseTuple(kinput, "Oi", &theChar, &type))
                goto err;

            if (!PyUnicode_Check(theChar))
            {
                PyErr_SetString(PyExc_TypeError, "Text must be a Unicode character");
                goto err;
            }

            WCHAR szChar;
            PyUnicode_AsWideChar((PyUnicodeObject *)theChar, &szChar, 1);

            pInputs[i].type = INPUT_KEYBOARD;
            pInputs[i].ki.wVk = 0;
            pInputs[i].ki.wScan = MapVirtualKeyEx(VkKeyScan(szChar), 0, layout);
            pInputs[i].ki.dwFlags = KEYEVENTF_SCANCODE | type;
            pInputs[i].ki.time = 0;
            pInputs[i].ki.dwExtraInfo = 0;

            break;
        }

        default:
            PyErr_SetString(PyExc_ValueError, "Unknown input type.");
            goto err;
        }
    }

    if (SendInput(PyTuple_Size(args), pInputs, sizeof(INPUT)) != PyTuple_Size(args))
    {
        PyErr_SetString(PyExc_RuntimeError, "SendInput failed.");
        goto err;
    }

    free(pInputs);

    Py_INCREF(Py_None);
    return Py_None;

err:
    free(pInputs);

    return NULL;
}
wxString* newWxStringFromPy( PyObject* src )
{
    bool        must_unref_str = false;

    wxString*   result  = NULL;
    PyObject*   obj     = src;

#if wxUSE_UNICODE
    bool        must_unref_obj = false;
    // Unicode string to python unicode string
    PyObject*   uni_str = src;

    // if not an str or unicode, try to str(src)
#if PY_MAJOR_VERSION >= 3
    if( !PyBytes_Check( src ) && !PyUnicode_Check( src ) )
#else
    if( !PyString_Check( src ) && !PyUnicode_Check( src ) )
#endif
    {
        obj = PyObject_Str( src );

#if PY_MAJOR_VERSION >= 3
        uni_str = obj; // in case of Python 3 our string is already correctly encoded
#endif

        must_unref_obj = true;

        if( PyErr_Occurred() )
            return NULL;
    }

#if PY_MAJOR_VERSION >= 3
    if( PyBytes_Check( obj ) )
#else
    if( PyString_Check( obj ) )
#endif
    {
        uni_str = PyUnicode_FromEncodedObject( obj, wxPythonEncoding, "strict" );
        must_unref_str = true;

        if( PyErr_Occurred() )
            return NULL;
    }

    result = new wxString();
#if PY_MAJOR_VERSION >= 3
    size_t len = PyUnicode_GET_LENGTH( uni_str );
#else
    size_t len = PyUnicode_GET_SIZE( uni_str );
#endif

    if( len )
    {
#if PY_MAJOR_VERSION >= 3
        PyUnicode_AsWideChar( uni_str,
                              wxStringBuffer( *result, len ), len );
#else
        PyUnicode_AsWideChar( (PyUnicodeObject*) uni_str,
                              wxStringBuffer( *result, len ), len );
#endif
    }

    if( must_unref_str )
    {
        Py_DECREF( uni_str );
    }

    if( must_unref_obj )
    {
        Py_DECREF( obj );
    }

#else
    // normal string (or object) to normal python string
    PyObject* str = src;

    if( PyUnicode_Check( src ) )    // if it's unicode convert to normal string
    {
        str = PyUnicode_AsEncodedString( src, wxPythonEncoding, "strict" );

        if( PyErr_Occurred() )
            return NULL;
    }
#if PY_MAJOR_VERSION >= 3
    else if( !PyUnicode_Check( src ) )
#else
    else if( !PyString_Check( src ) )    // if it's not a string, str(obj)
#endif
    {
        str = PyObject_Str( src );
        must_unref_str = true;

        if( PyErr_Occurred() )
            return NULL;
    }

    // get the string pointer and size
    char*       str_ptr;
    Py_ssize_t  str_size;
    PyString_AsStringAndSize( str, &str_ptr, &str_size );

    // build the wxString from our pointer / size
    result = new wxString( str_ptr, str_size );

    if( must_unref_str )
    {
        Py_DECREF( str );
    }

#endif

    return result;
}
Пример #21
0
/* search_for_exec_prefix requires that argv0_path be no more than
   MAXPATHLEN bytes long.
*/
static int
search_for_exec_prefix(wchar_t *argv0_path, wchar_t *home, wchar_t *_exec_prefix)
{
    size_t n;

    /* If PYTHONHOME is set, we believe it unconditionally */
    if (home) {
        wchar_t *delim;
        delim = wcschr(home, DELIM);
        if (delim)
            wcsncpy(exec_prefix, delim+1, MAXPATHLEN);
        else
            wcsncpy(exec_prefix, home, MAXPATHLEN);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        return 1;
    }

    /* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
       is written by setup.py and contains the relative path to the location
       of shared library modules. */
    wcscpy(exec_prefix, argv0_path);
    joinpath(exec_prefix, L"pybuilddir.txt");
    if (isfile(exec_prefix)) {
        FILE *f = _Py_wfopen(exec_prefix, L"rb");
        if (f == NULL)
            errno = 0;
        else {
            char buf[MAXPATHLEN+1];
            PyObject *decoded;
            wchar_t rel_builddir_path[MAXPATHLEN+1];
            n = fread(buf, 1, MAXPATHLEN, f);
            buf[n] = '\0';
            fclose(f);
            decoded = PyUnicode_DecodeUTF8(buf, n, "surrogateescape");
            if (decoded != NULL) {
                Py_ssize_t k;
                k = PyUnicode_AsWideChar(decoded,
                                         rel_builddir_path, MAXPATHLEN);
                Py_DECREF(decoded);
                if (k >= 0) {
                    rel_builddir_path[k] = L'\0';
                    wcscpy(exec_prefix, argv0_path);
                    joinpath(exec_prefix, rel_builddir_path);
                    return -1;
                }
            }
        }
    }

    /* Search from argv0_path, until root is found */
    copy_absolute(exec_prefix, argv0_path, MAXPATHLEN+1);
    do {
        n = wcslen(exec_prefix);
        joinpath(exec_prefix, lib_python);
        joinpath(exec_prefix, L"lib-dynload");
        if (isdir(exec_prefix))
            return 1;
        exec_prefix[n] = L'\0';
        reduce(exec_prefix);
    } while (exec_prefix[0]);

    /* Look at configure's EXEC_PREFIX */
    wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN);
    joinpath(exec_prefix, lib_python);
    joinpath(exec_prefix, L"lib-dynload");
    if (isdir(exec_prefix))
        return 1;

    /* Fail */
    return 0;
}
Пример #22
0
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
    if (value == Py_None) {
        *(wchar_t **)ptr = NULL;
        Py_INCREF(value);
        return value;
    }
    if (PyString_Check(value)) {
        value = PyUnicode_FromEncodedObject(value,
                                            _ctypes_conversion_encoding,
                                            _ctypes_conversion_errors);
        if (!value)
            return NULL;
    } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
        *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
        *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
        Py_INCREF(Py_None);
        return Py_None;
    } else if (!PyUnicode_Check(value)) {
        PyErr_Format(PyExc_TypeError,
                     "unicode string or integer address expected instead of %s instance",
                     value->ob_type->tp_name);
        return NULL;
    } else
        Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
    /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
       type.  So we can copy directly.  Hm, are unicode objects always NUL
       terminated in Python, internally?
     */
    *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
    return value;
#else
    {
        /* We must create a wchar_t* buffer from the unicode object,
           and keep it alive */
        PyObject *keep;
        wchar_t *buffer;

        int size = PyUnicode_GET_SIZE(value);
        size += 1; /* terminating NUL */
        size *= sizeof(wchar_t);
        buffer = (wchar_t *)PyMem_Malloc(size);
        if (!buffer) {
            Py_DECREF(value);
            return PyErr_NoMemory();
        }
        memset(buffer, 0, size);
        keep = CAPSULE_NEW(buffer, CTYPES_CAPSULE_WCHAR_T);
        if (!keep) {
            Py_DECREF(value);
            PyMem_Free(buffer);
            return NULL;
        }
        *(wchar_t **)ptr = (wchar_t *)buffer;
        if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
                                       buffer, PyUnicode_GET_SIZE(value))) {
            Py_DECREF(value);
            Py_DECREF(keep);
            return NULL;
        }
        Py_DECREF(value);
        return keep;
    }
#endif
}
Пример #23
0
static PyObject*
PyLocale_strcoll(PyObject* self, PyObject* args)
{
#if !defined(HAVE_WCSCOLL) || !defined(Py_USING_UNICODE)
    char *s1,*s2;
    
    if (!PyArg_ParseTuple(args, "ss:strcoll", &s1, &s2))
        return NULL;
    return PyInt_FromLong(strcoll(s1, s2));
#else
    PyObject *os1, *os2, *result = NULL;
    wchar_t *ws1 = NULL, *ws2 = NULL;
    int rel1 = 0, rel2 = 0, len1, len2;
    
    if (!PyArg_ParseTuple(args, "OO:strcoll", &os1, &os2))
        return NULL;
    /* If both arguments are byte strings, use strcoll.  */
    if (PyString_Check(os1) && PyString_Check(os2))
        return PyInt_FromLong(strcoll(PyString_AS_STRING(os1),
                                      PyString_AS_STRING(os2)));
    /* If neither argument is unicode, it's an error.  */
    if (!PyUnicode_Check(os1) && !PyUnicode_Check(os2)) {
        PyErr_SetString(PyExc_ValueError, "strcoll arguments must be strings");
    }
    /* Convert the non-unicode argument to unicode. */
    if (!PyUnicode_Check(os1)) {
        os1 = PyUnicode_FromObject(os1);
        if (!os1)
            return NULL;
        rel1 = 1;
    }
    if (!PyUnicode_Check(os2)) {
        os2 = PyUnicode_FromObject(os2);
        if (!os2) {
            Py_DECREF(os1);
            return NULL;
        } 
        rel2 = 1;
    }
    /* Convert the unicode strings to wchar[]. */
    len1 = PyUnicode_GET_SIZE(os1) + 1;
    ws1 = PyMem_MALLOC(len1 * sizeof(wchar_t));
    if (!ws1) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os1, ws1, len1) == -1)
        goto done;
    ws1[len1 - 1] = 0;
    len2 = PyUnicode_GET_SIZE(os2) + 1;
    ws2 = PyMem_MALLOC(len2 * sizeof(wchar_t));
    if (!ws2) {
        PyErr_NoMemory();
        goto done;
    }
    if (PyUnicode_AsWideChar((PyUnicodeObject*)os2, ws2, len2) == -1)
        goto done;
    ws2[len2 - 1] = 0;
    /* Collate the strings. */
    result = PyInt_FromLong(wcscoll(ws1, ws2));
  done:
    /* Deallocate everything. */
    if (ws1) PyMem_FREE(ws1);
    if (ws2) PyMem_FREE(ws2);
    if (rel1) {
        Py_DECREF(os1);
    }
    if (rel2) {
        Py_DECREF(os2);
    }
    return result;
#endif
}
Пример #24
0
static int
Context_setWorkgroup (Context *self, PyObject *value, void *closure)
{
  wchar_t *w_workgroup;
  size_t chars;
  char *workgroup;
  size_t bytes;
  ssize_t written;

#if PY_MAJOR_VERSION < 3
  if (PyString_Check (value))
    value = PyUnicode_FromString (PyString_AsString (value));
#endif

  if (!PyUnicode_Check (value))
    {
      PyErr_SetString (PyExc_TypeError, "must be string");
      return -1;
    }

  chars = PyUnicode_GetSize (value); /* not including NUL */
  w_workgroup = malloc ((chars + 1) * sizeof (wchar_t));
  if (!w_workgroup)
    {
      PyErr_NoMemory ();
      return -1;
    }

#if PY_MAJOR_VERSION < 3
  if (PyUnicode_AsWideChar ((PyUnicodeObject *) value,
			    w_workgroup, chars) == -1)
#else
  if (PyUnicode_AsWideChar (value, w_workgroup, chars) == -1)
#endif
    {
      free (w_workgroup);
      return -1;
    }

  w_workgroup[chars] = L'\0';
  bytes = MB_CUR_MAX * chars + 1; /* extra byte for NUL */
  workgroup = malloc (bytes);
  if (!workgroup)
    {
      free (w_workgroup);
      PyErr_NoMemory ();
      return -1;
    }

  written = wcstombs (workgroup, w_workgroup, bytes);
  free (w_workgroup);

  if (written == -1)
    workgroup[0] = '\0';
  else
    /* NUL-terminate it (this is why we allocated the extra byte) */
    workgroup[written] = '\0';

  smbc_setWorkgroup (self->context, workgroup);
  // Don't free workgroup: the API function just takes a reference(!)
  return 0;
}
Пример #25
0
Файл: type.c Проект: zillow/ctds
static PyObject* translate_to_ucs2(PyObject* o)
{
    PyObject* translated = NULL;
    Py_ssize_t len;
    wchar_t* unicode;

    assert(PyUnicode_Check(o));
#if PY_MAJOR_VERSION < 3
    len = PyUnicode_GetSize(o);
    do
    {
        unicode = tds_mem_malloc((size_t)len * sizeof(wchar_t));
        if (!unicode)
        {
            PyErr_NoMemory();
            break;
        }
        if (-1 == PyUnicode_AsWideChar((PyUnicodeObject*)o, unicode, len))
        {
            break;
        }
    }
    while (0);
#else /* if PY_MAJOR_VERSION < 3 */
    unicode = PyUnicode_AsWideCharString(o, &len);
#endif /* else if PY_MAJOR_VERSION < 3 */

    if (!PyErr_Occurred())
    {
        Py_ssize_t ixsrc, ixdst = 0;
        for (ixsrc = 0; ixsrc < len; ++ixsrc, ++ixdst)
        {
#if defined(WCHAR_T_UCS4)
            if (0xFFFF < unicode[ixsrc])
#else /* if defined(WCHAR_T_UCS4) */
            if (Py_UNICODE_IS_SURROGATE(unicode[ixsrc]))
#endif /* else if defined(WCHAR_T_UCS4) */
            {
                static const char s_fmt[] =
                    "Unicode codepoint U+%08X is not representable in UCS-2; replaced with U+FFFD";
                char buffer[ARRAYSIZE(s_fmt) + 8 /* for codepoint chars */];
#if defined(WCHAR_T_UCS4)
                uint32_t codepoint = (uint32_t)unicode[ixsrc];
#else /* if defined(WCHAR_T_UCS4) */
                uint32_t codepoint;
                assert(((ixsrc + 1) < len) && Py_UNICODE_IS_SURROGATE(unicode[ixsrc + 1]));
                codepoint = Py_UNICODE_JOIN_SURROGATES(unicode[ixsrc], unicode[ixsrc + 1]);
                ++ixsrc;
#endif /* else if defined(WCHAR_T_UCS4) */
                (void)sprintf(buffer, s_fmt, codepoint);
                if (0 != PyErr_WarnEx(PyExc_UnicodeWarning, buffer, 1))
                {
                    break;
                }

                unicode[ixdst] = 0xFFFD; /* unicode replacement character */
            }
#if !defined(WCHAR_T_UCS4)
            else
            {
                unicode[ixdst] = unicode[ixsrc];
            }
#endif /* if !defined(WCHAR_T_UCS4) */
        }

        if (!PyErr_Occurred())
        {
            translated = PyUnicode_FromWideChar(unicode, ixdst);
        }
    }
#if PY_MAJOR_VERSION < 3
    tds_mem_free(unicode);
#else /* if PY_MAJOR_VERSION < 3 */
    PyMem_Free(unicode);
#endif /* else if PY_MAJOR_VERSION < 3 */

    return translated;
}