/* atexit() handler that'll call unload_add_on() for every item in the
 * dictionary.
 */
static void beos_cleanup_dyn( void )
{
	if( beos_dyn_images ) {
		int idx;
		int list_size;
		PyObject *id_list;

#ifdef WITH_THREAD
		PyThread_acquire_lock( beos_dyn_lock, 1 );
#endif

		id_list = PyDict_Values( beos_dyn_images );

		list_size = PyList_Size( id_list );
		for( idx = 0; idx < list_size; idx++ ) {
			PyObject *the_item;
			
			the_item = PyList_GetItem( id_list, idx );
			beos_nuke_dyn( the_item );
		}

		PyDict_Clear( beos_dyn_images );

#ifdef WITH_THREAD
		PyThread_free_lock( beos_dyn_lock );
#endif
	}
}
Beispiel #2
0
static PyObject*
init (PyObject* self)
{
    PyObject *allmodules, *moduleslist, *dict, *func, *result, *mod;
    int loop, num;
    int success=0, fail=0;

    if (!CheckSDLVersions ())
        return NULL;


    /*nice to initialize timer, so startup time will reflec init() time*/
    sdl_was_init = SDL_Init (
#if defined(WITH_THREAD) && !defined(MS_WIN32) && defined(SDL_INIT_EVENTTHREAD)
                       SDL_INIT_EVENTTHREAD |
#endif
                       SDL_INIT_TIMER |
                       SDL_INIT_NOPARACHUTE) == 0;


    /* initialize all pygame modules */
    allmodules = PyImport_GetModuleDict ();
    moduleslist = PyDict_Values (allmodules);
    if (!allmodules || !moduleslist)
        return Py_BuildValue ("(ii)", 0, 0);

    if (PyGame_Video_AutoInit ())
        ++success;
    else
        ++fail;

    num = PyList_Size (moduleslist);
    for (loop = 0; loop < num; ++loop)
    {
        mod = PyList_GET_ITEM (moduleslist, loop);
        if (!mod || !PyModule_Check (mod))
            continue;
        dict = PyModule_GetDict (mod);
        func = PyDict_GetItemString (dict, "__PYGAMEinit__");
        if(func && PyCallable_Check (func))
        {
            result = PyObject_CallObject (func, NULL);
            if (result && PyObject_IsTrue (result))
                ++success;
            else
            {
                PyErr_Clear ();
                ++fail;
            }
            Py_XDECREF (result);
        }
    }
    Py_DECREF (moduleslist);

    return Py_BuildValue ("(ii)", success, fail);
}
Beispiel #3
0
 static std::map<K,V> py2c(PyObject * ob) {
   pyref keys = PyDict_Keys(ob);
   pyref values = PyDict_Values(ob);
   std::map<K,V> res;
   int len = PyDict_Size(ob);
   for (int i = 0; i < len; i++)
     res.emplace(py_converter<K>::py2c(PyList_GET_ITEM((PyObject*)keys, i)),  //borrowed ref
                 py_converter<V>::py2c(PyList_GET_ITEM((PyObject*)values, i))); //borrowed ref
   return res;
 }
Beispiel #4
0
list dict_base::values() const
{
    if (check_exact(this))
    {
        return list(detail::new_reference(
                        PyDict_Values(this->ptr())));
    }
    else
    {
        return assume_list(this->attr("values")());
    }
}
Beispiel #5
0
static PyObject* py_set_colormap(PyObject *self, PyObject *args,
                                 PyObject *kwargs) {

  const char *kwnames[] = {"name", "pairs", NULL};
  PyObject *newdict, *keys, *vals;
  PyObject *result = NULL;
  VMDApp *app;
  char *name;

  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO!:color.set_colormap",
                                   (char**) kwnames, &name, &PyDict_Type,
                                   &newdict))
    return NULL;

  if (!(app = get_vmdapp()))
    return NULL;

  keys = PyDict_Keys(newdict);
  vals = PyDict_Values(newdict);

  for (int i=0; i<PyList_Size(keys); i++) {
    char *keyname = as_charptr(PyList_GetItem(keys, i));
    char *valname = as_charptr(PyList_GetItem(vals, i));

    if (!keyname || !valname || PyErr_Occurred()) {
      PyErr_SetString(PyExc_ValueError, "set_colormap dictionary invalid");
      goto cleanup;
    }

    if (!app->color_change_name(name, keyname, valname)) {
      PyErr_SetString(PyExc_ValueError,
                      "Invalid color category or item specified");
      goto cleanup;
    }
  }
  result = Py_None;

  // Getting the keys and values from the dictionary makes a new reference.
  // We tell Python we're done with it so as to not leak memory.
  // This needs to happen even if there was a problem setting color, which is
  // why we don't return NULL from the error checking statements above.
cleanup:
  Py_DECREF(keys);
  Py_DECREF(vals);

  Py_XINCREF(result);
  return result;
}
Beispiel #6
0
 /*static PyObject * c2py(std::map<K,V> &m) {
  PyObject * d = PyDict_New();
  for (auto & x : m) {
   pyref k = py_converter<K>::c2py(x.first);
   pyref v = py_converter<V>::c2py(x.second);   
   if (PyDict_SetItem(d,k,v) == -1) { Py_DECREF(d); return NULL;} // error
  }
  return d;
 }*/
 static bool is_convertible(PyObject *ob, bool raise_exception) {
  if (!PyDict_Check(ob)) goto _false;
  {
   pyref keys = PyDict_Keys(ob);
   pyref values = PyDict_Values(ob);
   int len = PyDict_Size(ob);
   for (int i = 0; i < len; i++) {
     if (!py_converter<K>::is_convertible(PyList_GET_ITEM((PyObject*)keys, i),raise_exception)) goto _false; //borrowed ref
     if (!py_converter<V>::is_convertible(PyList_GET_ITEM((PyObject*)values, i),raise_exception)) goto _false; //borrowed ref
   }
   return true;
  }
  _false:
  if (raise_exception) { PyErr_SetString(PyExc_TypeError, "Cannot convert to std::map");}
  return false;
 }
Beispiel #7
0
static PyObject *set_colors(PyObject *self, PyObject *args) {
  PyObject *newdict;
  if (!PyArg_ParseTuple(args, (char *)"O!", &PyDict_Type, &newdict))
    return NULL;

  VMDApp *app = get_vmdapp();
  PyObject *keys = PyDict_Keys(newdict);
  PyObject *vals = PyDict_Values(newdict);
  int error = 0;
  for (int i=0; i<PyList_Size(keys); i++) {
    char *keyname = PyString_AsString(PyList_GET_ITEM(keys, i));
    if (PyErr_Occurred()) {
      error = 1;
      break;
    }
    if (app->color_index(keyname) < 0) {
      PyErr_SetString(PyExc_ValueError, (char *)"Unknown color");
      error = 1;
      break;
    }
    PyObject *newtuple = PyList_GET_ITEM(vals, i);
    if (!PyTuple_Check(newtuple) || PyTuple_Size(newtuple) != 3) {
      PyErr_SetString(PyExc_ValueError, (char *)"color definition must be 3-tuple of floats");
      error = 1;
      break;
    }
    float rgb[3];
    for (int j=0; j<3; j++) 
      rgb[j] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(newtuple, j));
    if (PyErr_Occurred()) {
      error = 1;
      break;
    }
    app->color_changevalue(keyname, rgb[0], rgb[1], rgb[2]);
  }
  Py_DECREF(keys);
  Py_DECREF(vals);
  if (error)
    return NULL;

  Py_INCREF(Py_None);
  return Py_None;
}
Beispiel #8
0
static int PyBobSpIDCT1D_Init(PyBobSpIDCT1DObject* self,
    PyObject* args, PyObject* kwds) {

  Py_ssize_t nargs = (args?PyTuple_Size(args):0) + (kwds?PyDict_Size(kwds):0);

  switch (nargs) {

    case 1:

      {

        PyObject* arg = 0; ///< borrowed (don't delete)
        if (PyTuple_Size(args)) arg = PyTuple_GET_ITEM(args, 0);
        else {
          PyObject* tmp = PyDict_Values(kwds);
          auto tmp_ = make_safe(tmp);
          arg = PyList_GET_ITEM(tmp, 0);
        }

        if (PyBob_NumberCheck(arg)) {
          return PyBobSpIDCT1D_InitShape(self, args, kwds);
        }

        if (PyBobSpIDCT1D_Check(arg)) {
          return PyBobSpIDCT1D_InitCopy(self, args, kwds);
        }

        PyErr_Format(PyExc_TypeError, "cannot initialize `%s' with `%s' (see help)", Py_TYPE(self)->tp_name, Py_TYPE(arg)->tp_name);

      }

      break;

    default:

      PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 1 argument, but you provided %" PY_FORMAT_SIZE_T "d (see help)", Py_TYPE(self)->tp_name, nargs);

  }

  return -1;

}
Beispiel #9
0
static int PyBobLearnEMGMMMachine_init(PyBobLearnEMGMMMachineObject* self, PyObject* args, PyObject* kwargs) {
  BOB_TRY

  // get the number of command line arguments
  int nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  switch (nargs) {

    case 0: //default initializer ()
      self->cxx.reset(new bob::learn::em::GMMMachine());
      return 0;

    case 1:{
      //Reading the input argument
      PyObject* arg = 0;
      if (PyTuple_Size(args))
        arg = PyTuple_GET_ITEM(args, 0);
      else {
        PyObject* tmp = PyDict_Values(kwargs);
        auto tmp_ = make_safe(tmp);
        arg = PyList_GET_ITEM(tmp, 0);
      }

      // If the constructor input is Gaussian object
     if (PyBobLearnEMGMMMachine_Check(arg))
       return PyBobLearnEMGMMMachine_init_copy(self, args, kwargs);
      // If the constructor input is a HDF5
     else if (PyBobIoHDF5File_Check(arg))
       return PyBobLearnEMGMMMachine_init_hdf5(self, args, kwargs);
    }
    case 2:
      return PyBobLearnEMGMMMachine_init_number(self, args, kwargs);
    default:
      PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires 0, 1 or 2 arguments, but you provided %d (see help)", Py_TYPE(self)->tp_name, nargs);
      GMMMachine_doc.print_usage();
      return -1;
  }
  BOB_CATCH_MEMBER("cannot create GMMMachine", -1)
  return 0;
}
Beispiel #10
0
CString EnumerateDictionary(PyObject* pDict)
{
	CString strRet;
	if( pDict == 0 )
		return strRet;

	PyObject* pItems = PyDict_Values(pDict);
	Py_ssize_t nNumItems = PyList_GET_SIZE(pItems);
	for(int i = 0; i < nNumItems; i++)
	{
		PyObject* pItem = PyList_GET_ITEM( pItems, i );
		if( MyPyTuple_Check(pItem) )
			strRet += EnumerateTuple(pItem);
		else
		{
			CString strType = GetType(pItem);
			strRet += CA2T(PyString_AsString(pItem));
		}
	}

	return strRet;
}
Beispiel #11
0
static int PyBobLearnEMISVMachine_init(PyBobLearnEMISVMachineObject* self, PyObject* args, PyObject* kwargs) {
  BOB_TRY

  // get the number of command line arguments
  int nargs = (args?PyTuple_Size(args):0) + (kwargs?PyDict_Size(kwargs):0);

  if(nargs == 1){
    //Reading the input argument
    PyObject* arg = 0;
    if (PyTuple_Size(args))
      arg = PyTuple_GET_ITEM(args, 0);
    else {
      PyObject* tmp = PyDict_Values(kwargs);
      auto tmp_ = make_safe(tmp);
      arg = PyList_GET_ITEM(tmp, 0);
    }

    // If the constructor input is Gaussian object
    if (PyBobLearnEMISVMachine_Check(arg))
      return PyBobLearnEMISVMachine_init_copy(self, args, kwargs);
    // If the constructor input is a HDF5
    else if (PyBobIoHDF5File_Check(arg))
      return PyBobLearnEMISVMachine_init_hdf5(self, args, kwargs);
    // If the constructor input is a JFABase Object
    else
      return PyBobLearnEMISVMachine_init_isvbase(self, args, kwargs);
  }
  else{
    PyErr_Format(PyExc_RuntimeError, "number of arguments mismatch - %s requires only 1 argument, but you provided %d (see help)", Py_TYPE(self)->tp_name, nargs);
    ISVMachine_doc.print_usage();
    return -1;
  }
  
  BOB_CATCH_MEMBER("cannot create ISVMachine", -1)
  return 0;
}
Beispiel #12
0
static PyObject *set_colormap(PyObject *self, PyObject *args) {
  char *name;
  PyObject *newdict;

  if (!PyArg_ParseTuple(args, (char *)"sO!", &name, &PyDict_Type, &newdict))
    return NULL;

  VMDApp *app = get_vmdapp();
  PyObject *keys = PyDict_Keys(newdict);
  PyObject *vals = PyDict_Values(newdict);
  int error = 0;
  for (int i=0; i<PyList_Size(keys); i++) {
    char *keyname = PyString_AsString(PyList_GET_ITEM(keys, i));
    if (PyErr_Occurred()) {
      error = 1;
      break;
    }
    char *valname = PyString_AsString(PyList_GET_ITEM(vals, i));
    if (PyErr_Occurred()) {
      error = 1;
      break;
    }
    if (!app->color_changename(name, keyname, valname)) {
      PyErr_SetString(PyExc_ValueError, 
        (char *)"Invalid color category or item specified");
      return NULL;
    }
  }
  Py_DECREF(keys);
  Py_DECREF(vals);
  if (error)
    return NULL;
  
  Py_INCREF(Py_None);
  return Py_None;
}
Beispiel #13
0
static PyObject* py_set_colors(PyObject *self, PyObject *args, PyObject *kwargs)
{
  PyObject *newdict, *newtuple, *keys, *vals;
  const char *kwnames[] = {"colors", NULL};
  PyObject *retval = NULL;
  char *keyname;
  float rgb[3];
  VMDApp *app;

  if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O!:color.set_colors",
                                   (char**) kwnames, &PyDict_Type, &newdict))
    return NULL;

  if (!(app = get_vmdapp()))
    return NULL;

  keys = PyDict_Keys(newdict);
  vals = PyDict_Values(newdict);

  for (int i=0; i<PyList_Size(keys); i++) {
    // Get color name from input dictionary
    keyname = as_charptr(PyList_GetItem(keys, i));
    if (PyErr_Occurred())
        goto cleanup;

    // Check this color name actually exists
    if (app->color_index(keyname) < 0) {
      PyErr_Format(PyExc_ValueError, "Unknown color '%s'", keyname);
      goto cleanup;
    }

    // Unpack value tuples into 3 floats
    newtuple = PyList_GetItem(vals, i);
    if (!PyTuple_Check(newtuple) || PyTuple_Size(newtuple) != 3) {
      PyErr_SetString(PyExc_ValueError,
                      "color definition must be 3-tuple of floats");
      goto cleanup;
    }

    for (int j=0; j<3; j++) {
      rgb[j] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(newtuple, j));

      if (PyErr_Occurred()) {
        PyErr_SetString(PyExc_ValueError, "color definition must be floats");
        goto cleanup;
      }
    }

    // Finally actually change the color
    app->color_change_rgb(keyname, rgb[0], rgb[1], rgb[2]);
  }
  retval = Py_None;

  // Getting the keys and values from the dictionary makes a new reference.
  // We tell Python we're done with it so as to not leak memory.
  // This needs to happen even if there was a problem setting color, which is
  // why we don't return NULL from the error checking statements above.
cleanup:
  Py_DECREF(keys);
  Py_DECREF(vals);

  Py_XINCREF(retval);
  return retval;
}
Beispiel #14
0
static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) {
    if (PY_MAJOR_VERSION >= 3)
        return __Pyx_PyObject_CallMethod1((PyObject*)&PyDict_Type, PYIDENT("values"), d);
    else
        return PyDict_Values(d);
}
Beispiel #15
0
PyObject*
PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
{
    ImagingEncoderObject* encoder;

    char* mode;
    char* rawmode;
    char* compname;
    char* filename;
    int compression;
    int fp;

    PyObject *dir;
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    int status;

    Py_ssize_t d_size;
    PyObject *keys, *values;


    if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) {
        return NULL;
    }

    if (!PyDict_Check(dir)) {
        PyErr_SetString(PyExc_ValueError, "Invalid Dictionary");
        return NULL;
    } else {
        d_size = PyDict_Size(dir);
        TRACE(("dict size: %d\n", (int)d_size));
        keys = PyDict_Keys(dir);
        values = PyDict_Values(dir);
        for (pos=0;pos<d_size;pos++){
            TRACE(("  key: %d\n", (int)PyInt_AsLong(PyList_GetItem(keys,pos))));
        }
        pos = 0;
    }


    TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));

    /* UNDONE -- we can probably do almost any arbitrary compression here,
     *  so long as we're doing row/stripe based actions and not tiles.
     */

    if (strcasecmp(compname, "tiff_ccitt") == 0) {
        compression = COMPRESSION_CCITTRLE;

    } else if (strcasecmp(compname, "group3") == 0) {
        compression = COMPRESSION_CCITTFAX3;

    } else if (strcasecmp(compname, "group4") == 0) {
        compression = COMPRESSION_CCITTFAX4;

    } else if (strcasecmp(compname, "tiff_jpeg") == 0) {
        compression = COMPRESSION_OJPEG;

    } else if (strcasecmp(compname, "tiff_adobe_deflate") == 0) {
        compression = COMPRESSION_ADOBE_DEFLATE;

    } else if (strcasecmp(compname, "tiff_thunderscan") == 0) {
        compression = COMPRESSION_THUNDERSCAN;

    } else if (strcasecmp(compname, "tiff_deflate") == 0) {
        compression = COMPRESSION_DEFLATE;

    } else if (strcasecmp(compname, "tiff_sgilog") == 0) {
        compression = COMPRESSION_SGILOG;

    } else if (strcasecmp(compname, "tiff_sgilog24") == 0) {
        compression = COMPRESSION_SGILOG24;

    } else if (strcasecmp(compname, "tiff_raw_16") == 0) {
        compression = COMPRESSION_CCITTRLEW;

    } else {
        PyErr_SetString(PyExc_ValueError, "unknown compession");
        return NULL;
    }

    TRACE(("Found compression: %d\n", compression));

    encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
    if (encoder == NULL)
        return NULL;

    if (get_packer(encoder, mode, rawmode) < 0)
        return NULL;

    if (! ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
        Py_DECREF(encoder);
        PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed");
        return NULL;
    }

	// While failes on 64 bit machines, complains that pos is an int instead of a Py_ssize_t
	//    while (PyDict_Next(dir, &pos, &key, &value)) {
	for (pos=0;pos<d_size;pos++){
		key = PyList_GetItem(keys,pos);
		value = PyList_GetItem(values,pos);
        status = 0;
        TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key)));
        if (PyInt_Check(value)) {
            TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyInt_AsLong(value));
        } else if(PyBytes_Check(value)) {
            TRACE(("Setting from Bytes: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyBytes_AsString(value));
        } else if(PyList_Check(value)) {
            int len,i;
            float *floatav;
            TRACE(("Setting from List: %d \n", (int)PyInt_AsLong(key)));
            len = (int)PyList_Size(value);
            TRACE((" %d elements, setting as floats \n", len));
            floatav = malloc(sizeof(float)*len);
            if (floatav) {
                for (i=0;i<len;i++) {
                    floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i));
                }
                status = ImagingLibTiffSetField(&encoder->state,
                                                (ttag_t) PyInt_AsLong(key),
                                                floatav);
                free(floatav);
            }
        } else if (PyFloat_Check(value)) {
            TRACE(("Setting from Float: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            (float)PyFloat_AsDouble(value));
        } else {
            TRACE(("Unhandled type for key %d : %s \n",
                   (int)PyInt_AsLong(key),
                   PyBytes_AsString(PyObject_Str(value))));
        }
        if (!status) {
            TRACE(("Error setting Field\n"));
            Py_DECREF(encoder);
            PyErr_SetString(PyExc_RuntimeError, "Error setting from dictionary");
            return NULL;
        }
    }

    encoder->encode  = ImagingLibTiffEncode;

    return (PyObject*) encoder;
}
Beispiel #16
0
//-------------------------------------------------------------------------------------
PyObject* Map::__py_values(PyObject* self, PyObject* args)
{
	return PyDict_Values(static_cast<Map*>(self)->pyDict_);
}
Beispiel #17
0
/*
 * HTML starttag builder
 */
PyObject *
tdi_soup_encode_starttag(tdi_node_t *node)
{
    PyObject *result, *attr;
    tdi_attr_t *item;
    char *cresult;
    Py_ssize_t j, length, size;

    /* 1st pass: count result bytes */
    size = PyString_GET_SIZE(node->tagname) + 2;  /* <> */
    if (node->flags & NODE_CLOSED)
        size += 2;  /* ' /' */

    if (!(attr = PyDict_Values(node->attr)))
        return NULL;
    length = PyList_GET_SIZE(attr);
    for (j = 0; j < length; ++j) {
        if (!(item = (tdi_attr_t *)PyList_GetItem(attr, j))) {
            Py_DECREF(attr);
            return NULL;
        }
        if (item->value == Py_None)
            size += PyString_GET_SIZE(item->key) + 1;  /* ' ' */
        else
            size += PyString_GET_SIZE(item->key)
                + PyString_GET_SIZE(item->value) + 2;  /* ' =' */
    }

    /* 2nd pass: assemble result */
    if (!(result = PyString_FromStringAndSize(NULL, size))) {
        Py_DECREF(attr);
        return NULL;
    }
    cresult = PyString_AS_STRING(result);
    *cresult++ = '<';

    size = PyString_GET_SIZE(node->tagname);
    (void)memcpy(cresult, PyString_AS_STRING(node->tagname), (size_t)size);
    cresult += size;

    for (j = 0; j < length; ++j) {
        if (!(item = (tdi_attr_t *)PyList_GetItem(attr, j))) {
            Py_DECREF(result);
            Py_DECREF(attr);
            return NULL;
        }

        *cresult++ = ' ';

        size = PyString_GET_SIZE(item->key);
        (void)memcpy(cresult, PyString_AS_STRING(item->key), (size_t)size);
        cresult += size;

        if (item->value != Py_None) {
            *cresult++ = '=';
            size = PyString_GET_SIZE(item->value);
            (void)memcpy(cresult, PyString_AS_STRING(item->value),
                         (size_t)size);
            cresult += size;
        }
    }
    Py_DECREF(attr);

    if (node->flags & NODE_CLOSED) {
        *cresult++ = ' ';
        *cresult++ = '/';
    }
    *cresult = '>';

    return result;
}
Beispiel #18
0
static CYTHON_INLINE PyObject* __Pyx_PyDict_Values(PyObject* d) {
    if (PY_MAJOR_VERSION >= 3)
        return CALL_UNBOUND_METHOD(PyDict_Type, "values", d);
    else
        return PyDict_Values(d);
}
Beispiel #19
0
PyObject*
PyImaging_LibTiffEncoderNew(PyObject* self, PyObject* args)
{
    ImagingEncoderObject* encoder;

    char* mode;
    char* rawmode;
    char* compname;
    char* filename;
    int fp;

    PyObject *dir;
    PyObject *key, *value;
    Py_ssize_t pos = 0;
    int status;

    Py_ssize_t d_size;
    PyObject *keys, *values;


    if (! PyArg_ParseTuple(args, "sssisO", &mode, &rawmode, &compname, &fp, &filename, &dir)) {
        return NULL;
    }

    if (!PyDict_Check(dir)) {
        PyErr_SetString(PyExc_ValueError, "Invalid Dictionary");
        return NULL;
    } else {
        d_size = PyDict_Size(dir);
        TRACE(("dict size: %d\n", (int)d_size));
        keys = PyDict_Keys(dir);
        values = PyDict_Values(dir);
        for (pos=0;pos<d_size;pos++){
            TRACE(("  key: %d\n", (int)PyInt_AsLong(PyList_GetItem(keys,pos))));
        }
        pos = 0;
    }


    TRACE(("new tiff encoder %s fp: %d, filename: %s \n", compname, fp, filename));

    encoder = PyImaging_EncoderNew(sizeof(TIFFSTATE));
    if (encoder == NULL)
        return NULL;

    if (get_packer(encoder, mode, rawmode) < 0)
        return NULL;

    if (! ImagingLibTiffEncodeInit(&encoder->state, filename, fp)) {
        Py_DECREF(encoder);
        PyErr_SetString(PyExc_RuntimeError, "tiff codec initialization failed");
        return NULL;
    }

        // While failes on 64 bit machines, complains that pos is an int instead of a Py_ssize_t
        //    while (PyDict_Next(dir, &pos, &key, &value)) {
        for (pos=0;pos<d_size;pos++){
                key = PyList_GetItem(keys,pos);
                value = PyList_GetItem(values,pos);
        status = 0;
        TRACE(("Attempting to set key: %d\n", (int)PyInt_AsLong(key)));
        if (PyInt_Check(value)) {
            TRACE(("Setting from Int: %d %ld \n", (int)PyInt_AsLong(key),PyInt_AsLong(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyInt_AsLong(value));
        } else if(PyBytes_Check(value)) {
            TRACE(("Setting from Bytes: %d, %s \n", (int)PyInt_AsLong(key),PyBytes_AsString(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            PyBytes_AsString(value));
        } else if(PyList_Check(value)) {
            int len,i;
            float *floatav;
            int *intav;
            TRACE(("Setting from List: %d \n", (int)PyInt_AsLong(key)));
            len = (int)PyList_Size(value);
            if (len) {
                if (PyInt_Check(PyList_GetItem(value,0))) {
                    TRACE((" %d elements, setting as ints \n", len));
                    intav = malloc(sizeof(int)*len);
                    if (intav) {
                        for (i=0;i<len;i++) {
                            intav[i] = (int)PyInt_AsLong(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        intav);
                        free(intav);
                    }
                } else {
                    TRACE((" %d elements, setting as floats \n", len));
                    floatav = malloc(sizeof(float)*len);
                    if (floatav) {
                        for (i=0;i<len;i++) {
                            floatav[i] = (float)PyFloat_AsDouble(PyList_GetItem(value,i));
                        }
                        status = ImagingLibTiffSetField(&encoder->state,
                                                        (ttag_t) PyInt_AsLong(key),
                                                        floatav);
                        free(floatav);
                    }
                }
            }
        } else if (PyFloat_Check(value)) {
            TRACE(("Setting from Float: %d, %f \n", (int)PyInt_AsLong(key),PyFloat_AsDouble(value)));
            status = ImagingLibTiffSetField(&encoder->state,
                                            (ttag_t) PyInt_AsLong(key),
                                            (float)PyFloat_AsDouble(value));
        } else {
            TRACE(("Unhandled type for key %d : %s \n",
                   (int)PyInt_AsLong(key),
                   PyBytes_AsString(PyObject_Str(value))));
        }
        if (!status) {
            TRACE(("Error setting Field\n"));
            Py_DECREF(encoder);
            PyErr_SetString(PyExc_RuntimeError, "Error setting from dictionary");
            return NULL;
        }
    }

    encoder->encode  = ImagingLibTiffEncode;

    return (PyObject*) encoder;
}
Beispiel #20
0
void CPyScriptAutoConfigDlg::InitFuncNameComboBox()
{
	// initialize Python for the following
	if( !InitPython() )
		return;

	PyObject* pItems = PyDict_Values(m_pDictionary);
	Py_ssize_t nNumItems = PyList_GET_SIZE(pItems);
	for(int i = 0; i < nNumItems; i++)
	{
		PyObject* pItem = PyList_GET_ITEM( pItems, i );
		CString strType = GetType(pItem);
		if( MyPyFunction_Check(pItem) )
		{
			PyFunctionObject* pFunc = (PyFunctionObject *)pItem;
			PyObject* pName = PyFunction_GET_NAME(pFunc);
			CStringA str(PyString_AsString(pName));
			m_cbFunctionNames.AddString(CA2T(str));
		}

#define rdeTesting
#if defined(DEBUG) && !defined(rdeTesting)
		else if( MyPyClass_Check(pItem) )
		{
			PyClassObject* pClass = (PyClassObject*)pItem;
			PyObject* pDict = pClass->cl_dict;
			if( MyPyDict_Check(pDict) )
			{
				CString str = EnumerateDictionary(pDict);
			}
			else if( MyPyString_Check(((PyClassObject*)pItem)->cl_name) )
			{
				CString str = CA2T(PyString_AsString(((PyClassObject*)pItem)->cl_name));
				TRACE(str);
			}
		}
		else if( MyPyType_Check(pItem) )
		{
			PyTypeObject* pType = (PyTypeObject*)pItem;
			TRACE(_T("type: name: (%s)\n"), CA2T(pType->tp_name) );
			CString str = EnumerateDictionary(pType->tp_dict);
			PyMethodDef* pMD = pType->tp_methods;
			if( (pMD != 0) && (pMD->ml_name != 0) )
				TRACE(_T("method name: (%s)\n"), CA2T(pMD->ml_name));
			PyMemberDef* pMbD = pType->tp_members;
			if( (pMbD != 0) && (pMbD->name != 0) )
				TRACE(_T("member name: (%s)\n"), CA2T(pMbD->name));
			_typeobject* pBase = pType->tp_base;
			if( (pBase != 0) && (pBase->tp_name != 0) )
				TRACE(_T("base name: (%s)\n"), CA2T(pBase->tp_name) );

			str = EnumerateTuple(pType->tp_bases);
			str = EnumerateTuple(pType->tp_mro);
			if( pType->tp_repr != 0 )
			{
				PyObject* pRepr = (pType->tp_repr)(pItem);
				CString str(CA2T(PyString_AsString(pRepr)));
				TRACE(str);
			}

			i = 0;
			while(pType->tp_getset[i].get != 0)
			{
				PyObject* pGet = (pType->tp_getset[i++].get)(pItem,0);
				if( MyPyDict_Check(pGet) )
				{
					CString str = EnumerateDictionary(pGet);
					TRACE(str);
				}
				else
				{
					CString str(CA2T(PyString_AsString(pGet)));
					TRACE(str);
				}
			}
		}
		else if( MyPyDict_Check(pItem) )
		{
			CString str = EnumerateDictionary(pItem);
			TRACE(str);
		}
		else if( MyPyList_Check(pItem) )
		{
			CString str = EnumerateList(pItem);
			TRACE(str);
		}
		else if( MyPyString_Check(pItem) )
		{
			CString str(CA2T(PyString_AsString(pItem)));
			TRACE(str);
		}
/*
			// what else can we figure out
			// RESULT: we could get the argument-list, but not the types (i.e. legacy vs. unicode)
			PyCodeObject* pCode = (PyCodeObject*)PyFunction_GET_CODE(pFunc);
			strType = GetType((PyObject*)pCode);
			// IterateList(pCode->co_names);
			IterateTuple(pCode->co_varnames);

			PyObject* pGlobals = PyFunction_GET_GLOBALS(pFunc); // a dictionary
			strType = GetType(pGlobals);
			IterateDictionary(pGlobals);
			// CStringA strGlobals(PyString_AsString(pGlobals));

			PyObject* pModule = PyFunction_GET_MODULE(pFunc);   // module name (we already know)
			strType = GetType(pModule);
			CStringA strModule(PyString_AsString(pModule));

			// PyObject* pDefaults = PyFunction_GET_DEFAULTS(pFunc);
			// strType = GetType(pDefaults);
			// CStringA strDefaults(PyString_AsString(pDefaults));

			PyObject* pClosure = PyFunction_GET_CLOSURE(pFunc);
			strType = GetType(pClosure);
			CStringA strClosure(PyString_AsString(pClosure));

			PyObject* pDoc = PyFunction_GET_DOC(pFunc);
			strType = GetType(pDoc);
			CStringA strDoc(PyString_AsString(pDoc));

			PyObject* pDict = PyFunction_GET_DICT(pFunc);
			strType = GetType(pDict);
			CStringA strDict(PyString_AsString(pDict));

			PyObject* pWRF = PyFunction_GET_WEAKREFLIST(pFunc);
			strType = GetType(pWRF);
			CStringA strWRF(PyString_AsString(pWRF));

			m_cbFunctionNames.SetCurSel(0);
*/
#endif
	}

	if( m_cbFunctionNames.GetCount() != 0 )
	{
		if( m_strFuncName.IsEmpty() )
			m_cbFunctionNames.SetCurSel(0);
		else
			m_cbFunctionNames.SelectString(0, m_strFuncName);

		OnCbnSelchangeCbFuncName();
	}
}