示例#1
0
文件: entity.c 项目: abed-hawa/amara
static PyObject *entity_setstate(PyObject *self, PyObject *state)
{
  PyObject *dict, *public_id, *system_id, *unparsed_entities, *children, *temp;
  Py_ssize_t i, n;

  if (!PyArg_UnpackTuple(state, NULL, 5, 5,
                         &dict, &public_id, &system_id, &unparsed_entities,
                         &children))
    return NULL;

  if (!convert_arg(0, &PyDict_Type, &dict))
    return NULL;
  if (!convert_arg(3, &PyDict_Type, &unparsed_entities))
    return NULL;
  if (!convert_arg(4, &PyTuple_Type, &children))
    return NULL;

  if (dict) {
    if (PyType_HasFeature(self->ob_type, Py_TPFLAGS_HEAPTYPE)) {
      temp = PyObject_GetAttrString(self, "__dict__");
      if (temp == NULL)
        return NULL;
      if (PyDict_Update(temp, dict) < 0) {
        Py_DECREF(temp);
        return NULL;
      }
      Py_DECREF(temp);
    }
  }
  temp = Entity_GET_PUBLIC_ID(self);
  Entity_SET_PUBLIC_ID(self, public_id);
  Py_INCREF(public_id);
  Py_DECREF(temp);

  temp = Entity_GET_SYSTEM_ID(self);
  Entity_SET_SYSTEM_ID(self, system_id);
  Py_INCREF(system_id);
  Py_DECREF(temp);

  if (unparsed_entities) {
    temp = Entity_GET_UNPARSED_ENTITIES(self);
    PyDict_Clear(temp);
    if (PyDict_Update(temp, unparsed_entities) < 0)
      return NULL;
  }
  if (children) {
    for (i = 0, n = PyTuple_GET_SIZE(children); i < n; i++) {
      NodeObject *node = (NodeObject *)PyTuple_GET_ITEM(children, i);
      if (Container_Append((NodeObject *)self, node) < 0)
        return NULL;
    }
  }
  Py_RETURN_NONE;
}
示例#2
0
__inline static int
set_state(PyObject *obj, PyObject *state)
{
	PyObject *__setstate__, *__dict__;

	if((__setstate__ = PyObject_GetAttr(obj, py__setstate__)))
	{
		// container has a __setstate__, invoke it!
		if(!PyObject_CallFunctionObjArgs(__setstate__, state, 0))
		{
			Py_DECREF(__setstate__);
			return 0;
		}
		Py_DECREF(__setstate__);
	}
	else
	{
		// container does not have __setstate__, see if it
		// has a __dict__ to update instead.
		PyErr_Clear();
		if(!(__dict__ = PyObject_GetAttr(obj, py__dict__)))
		{
			return 0;
		}

		if(PyDict_Update(__dict__, state))
		{
			Py_DECREF(__dict__);
			return 0;
		}
		Py_DECREF(__dict__);
	}

	return 1;
}
示例#3
0
static int
_event_init (PyObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *dict = NULL;
    int eventid;
    PyEvent *event = (PyEvent *) self;

    if (!PyArg_ParseTuple (args, "i|O", &eventid, &dict))
        return -1;

    if (eventid < 0 || eventid > 255)
    {
        PyErr_SetString (PyExc_ValueError,
                         "type must be an integer in the range 0-255");
        return -1;
    }

    if (dict && !PyDict_Check (dict))
    {
        PyErr_SetString (PyExc_TypeError, "dict must be a dict");
        return -1;
    }

    event->type = eventid;

    if (dict)
    {
        if (PyDict_Update (event->dict, dict) == -1)
            return -1;
    }

    return 0;
}
示例#4
0
static int
on_message_complete(http_parser* parser)
{
    switch(parser->method) {
        case HTTP_GET:
            _set_header(_REQUEST_METHOD, _GET);
            break;
        case HTTP_POST:
            _set_header(_REQUEST_METHOD, _POST);
            break;
        default:
            _set_header_free_value(
                _REQUEST_METHOD,
                PyString_FromString(http_method_str(parser->method))
            );
    }

    _set_header_free_value(
        _wsgi_input,
        PycStringIO->NewInput(
            REQUEST->body ? PycStringIO->cgetvalue(REQUEST->body)
                          : _empty_string
        )
    );

    _set_header(
        _SERVER_PROTOCOL,
        parser->http_minor == 1 ? _HTTP_1_1 : _HTTP_1_0
    );

    PyDict_Update(REQUEST->headers, wsgi_base_dict);

    REQUEST->state.parse_finished = true;
    return 0;
}
示例#5
0
//
// makes a dictionary with all of the neccessary stuff in it, but without
// a __builtin__ module set
PyObject *mud_script_dict(void) {
  PyObject* dict = PyDict_New();

  // add the exit() function so people can terminate scripts
  PyObject *sys = PyImport_ImportModule("sys");
  if(sys != NULL) {
    PyObject *exit = PyDict_GetItemString(PyModule_GetDict(sys), "exit");
    if(exit != NULL) PyDict_SetItemString(dict, "exit", exit);
    if(exit != NULL) PyDict_SetItemString(dict, "end_script", exit);
    Py_DECREF(sys);
  } 
  
  // merge all of the mud module contents with our current dict
  PyObject *mudmod = PyImport_ImportModule("mud");
  if (mudmod != NULL) {
    PyDict_Update(dict, PyModule_GetDict(mudmod));
	Py_DECREF(mudmod);
  } 
  
  mudmod = PyImport_ImportModule("char");
  if (mudmod != NULL) {
    PyDict_Update(dict, PyModule_GetDict(mudmod));
    Py_DECREF(mudmod);
  }
  mudmod = PyImport_ImportModule("room");
  if (mudmod) {
    PyDict_Update(dict, PyModule_GetDict(mudmod));
    Py_DECREF(mudmod);
  }
  mudmod = PyImport_ImportModule("obj");
  if (mudmod) {
    PyDict_Update(dict, PyModule_GetDict(mudmod));
    Py_DECREF(mudmod);
  }
  mudmod = PyImport_ImportModule("event");
  if (mudmod) {
    PyDict_Update(dict, PyModule_GetDict(mudmod));
    Py_DECREF(mudmod);
  }
  mudmod = PyImport_ImportModule("random");
  if (mudmod) {
    PyDict_SetItemString(dict, "random", mudmod);
    Py_DECREF(mudmod);
  }
  return dict;
}
示例#6
0
static int
analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
                    PyObject *global, PyObject* child_free)
{
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;

    /* Copy the bound and global dictionaries.

       These dictionaries are used by all blocks enclosed by the
       current block.  The analyze_block() call modifies these
       dictionaries.

    */
    temp_bound = PyDict_New();
    if (!temp_bound)
        goto error;
    if (PyDict_Update(temp_bound, bound) < 0)
        goto error;
    temp_free = PyDict_New();
    if (!temp_free)
        goto error;
    if (PyDict_Update(temp_free, free) < 0)
        goto error;
    temp_global = PyDict_New();
    if (!temp_global)
        goto error;
    if (PyDict_Update(temp_global, global) < 0)
        goto error;

    if (!analyze_block(entry, temp_bound, temp_free, temp_global))
        goto error;
    if (PyDict_Update(child_free, temp_free) < 0)
        goto error;
    Py_DECREF(temp_bound);
    Py_DECREF(temp_free);
    Py_DECREF(temp_global);
    return 1;
 error:
    Py_XDECREF(temp_bound);
    Py_XDECREF(temp_free);
    Py_XDECREF(temp_global);
    return 0;
}
示例#7
0
static PyObject *PythonQtClassWrapper_getattro(PyObject *obj, PyObject *name)
{
  const char *attributeName;
  PythonQtClassWrapper *wrapper = (PythonQtClassWrapper *)obj;

#ifdef PY3K
  if ((attributeName = PyUnicode_AsUTF8(name)) == NULL) {
#else
  if ((attributeName = PyString_AsString(name)) == NULL) {
#endif
    return NULL;
  }
  if (obj == (PyObject*)&PythonQtInstanceWrapper_Type) {
    return NULL;
  }

  if (qstrcmp(attributeName, "__dict__")==0) {
    PyObject* objectDict  = ((PyTypeObject *)wrapper)->tp_dict;
    if (!wrapper->classInfo()) {
      Py_INCREF(objectDict);
      return objectDict;
    }
    PyObject* dict = PyDict_New();
      
    QStringList l = wrapper->classInfo()->memberList();
    Q_FOREACH (QString name, l) {
      PyObject* o = PyObject_GetAttrString(obj, name.toLatin1().data());
      if (o) {
        PyDict_SetItemString(dict, name.toLatin1().data(), o);
        Py_DECREF(o);
      } else {
        // it must have been a property or child, which we do not know as a class object...
        PyErr_Clear();
      }
    }
    if (wrapper->classInfo()->constructors()) {
#ifdef PY3K
      PyObject* initName = PyUnicode_FromString("__init__");
#else
      PyObject* initName = PyString_FromString("__init__");
#endif
      PyObject* func = PyType_Type.tp_getattro(obj, initName);
      Py_DECREF(initName);
      PyDict_SetItemString(dict, "__init__", func);
      Py_DECREF(func);
    }
    for (int i = 0; PythonQtClassWrapper_methods[i].ml_name != NULL; i++) {
      PyObject* func = PyCFunction_New(&PythonQtClassWrapper_methods[i], obj);
      PyDict_SetItemString(dict, PythonQtClassWrapper_methods[i].ml_name, func);
      Py_DECREF(func);
    }

    PyDict_Update(dict, objectDict);
    return dict;
  }
示例#8
0
文件: pysocket.c 项目: KaSt/nereamud
//
// Send a message with Python statements potentially embedded in it. For 
//evaluating 
PyObject *PySocket_send(PyObject *self, PyObject *args, PyObject *kwds) {
  static char *kwlist[ ] = { "mssg", "dict", "newline", NULL };
  SOCKET_DATA *me = NULL;
  char      *text = NULL;
  PyObject  *dict = NULL;
  bool    newline = TRUE;

  if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|Ob", kwlist, 
				  &text, &dict, &newline)) {
    PyErr_Format(PyExc_TypeError, "Invalid arguments supplied to Mudsock.send");
    return NULL;
  }

  // is dict None? set it to NULL for expand_to_char
  if(dict == Py_None)
    dict = NULL;

  // make sure the dictionary is a dictionary
  if(!(dict == NULL || PyDict_Check(dict))) {
    PyErr_Format(PyExc_TypeError, "Mudsock.send expects second argument to be a dict object.");
    return NULL;
  }
  
  // make sure we exist
  if( (me = PySocket_AsSocket(self)) == NULL) {
    PyErr_Format(PyExc_TypeError, "Tried to send nonexistent socket.");
    return NULL;
  }

  if(dict != NULL)
    PyDict_SetItemString(dict, "me", self);

  // build our script environment
  BUFFER   *buf = newBuffer(1);
  bufferCat(buf, text);

  // expand out our dynamic descriptions if we have a dictionary supplied
  if(dict != NULL) {
    PyObject *env = restricted_script_dict();
    PyDict_Update(env, dict);

    // do the expansion
    expand_dynamic_descs_dict(buf, env, get_script_locale());
    Py_XDECREF(env);
  }

  if(newline == TRUE)
    bufferCat(buf, "\r\n");
  text_to_buffer(me, bufferString(buf));

  // garbage collection
  deleteBuffer(buf);
  return Py_BuildValue("");
}
示例#9
0
文件: dict.cpp 项目: NeoAnomaly/xray
void dict_base::update(object_cref other)
{
    if (check_exact(this))
    {
        if (PyDict_Update(this->ptr(),other.ptr()) == -1)
            throw_error_already_set();
    }
    else
    {
        this->attr("update")(other);
    }
}
示例#10
0
static int
merge_class_dict(PyObject* dict, PyObject* aclass)
{
	PyObject *classdict;
	PyObject *bases;

	assert(PyDict_Check(dict));
	assert(aclass);

	/* Merge in the type's dict (if any). */
	classdict = PyObject_GetAttrString(aclass, "__dict__");
	if (classdict == NULL)
		PyErr_Clear();
	else {
		int status = PyDict_Update(dict, classdict);
		Py_DECREF(classdict);
		if (status < 0)
			return -1;
	}

	/* Recursively merge in the base types' (if any) dicts. */
	bases = PyObject_GetAttrString(aclass, "__bases__");
	if (bases == NULL)
		PyErr_Clear();
	else {
		/* We have no guarantee that bases is a real tuple */
		Py_ssize_t i, n;
		n = PySequence_Size(bases); /* This better be right */
		if (n < 0)
			PyErr_Clear();
		else {
			for (i = 0; i < n; i++) {
				int status;
				PyObject *base = PySequence_GetItem(bases, i);
				if (base == NULL) {
					Py_DECREF(bases);
					return -1;
				}
				status = merge_class_dict(dict, base);
				Py_DECREF(base);
				if (status < 0) {
					Py_DECREF(bases);
					return -1;
				}
			}
		}
		Py_DECREF(bases);
	}
	return 0;
}
示例#11
0
PyObject *
_PyNamespace_New(PyObject *kwds)
{
    PyObject *ns = namespace_new(&_PyNamespace_Type, NULL, NULL);
    if (ns == NULL)
        return NULL;

    if (kwds == NULL)
        return ns;
    if (PyDict_Update(((_PyNamespaceObject *)ns)->ns_dict, kwds) != 0) {
        Py_DECREF(ns);
        return NULL;
    }

    return (PyObject *)ns;
}
示例#12
0
static int
namespace_init(_PyNamespaceObject *ns, PyObject *args, PyObject *kwds)
{
    /* ignore args if it's NULL or empty */
    if (args != NULL) {
        Py_ssize_t argcount = PyObject_Size(args);
        if (argcount < 0)
            return -1;
        else if (argcount > 0) {
            PyErr_Format(PyExc_TypeError, "no positional arguments expected");
            return -1;
        }
    }
    if (kwds == NULL)
        return 0;
    return PyDict_Update(ns->ns_dict, kwds);
}
示例#13
0
文件: node.c 项目: abed-hawa/amara
static PyObject *node_setstate(PyObject *self, PyObject *state)
{
  PyObject *dict;

  if (PyType_HasFeature(self->ob_type, Py_TPFLAGS_HEAPTYPE)) {
    dict = PyObject_GetAttrString(self, "__dict__");
    if (dict == NULL)
      return NULL;
    if (PyDict_Update(dict, state) < 0) {
      Py_DECREF(dict);
      return NULL;
    }
    Py_DECREF(dict);
  } else if (state != Py_None)
    return PyErr_Format(PyExc_NotImplementedError,
                        "subclass '%s' must override __setstate__()",
                        self->ob_type->tp_name);
  Py_RETURN_NONE;
}
示例#14
0
static PyObject *
pickle___setstate__(PyObject *self, PyObject *state)
{
  PyObject *slots=NULL;

  if (PyTuple_Check(state))
    {
      if (! PyArg_ParseTuple(state, "OO", &state, &slots))
        return NULL;
    }

  if (state != Py_None)
    {
      PyObject **dict;

      dict = _PyObject_GetDictPtr(self);
      if (dict)
        {
          if (*dict == NULL)
            {
              *dict = PyDict_New();
              if (*dict == NULL)
                return NULL;
            }
        }

      if (*dict != NULL)
        {
          PyDict_Clear(*dict);
          if (PyDict_Update(*dict, state) < 0)
            return NULL;
        }
      else if (pickle_setattrs_from_dict(self, state) < 0)
        return NULL;
    }

  if (slots != NULL && pickle_setattrs_from_dict(self, slots) < 0)
    return NULL;

  Py_INCREF(Py_None);
  return Py_None;
}
static PyObject *
pickle___setstate__(PyObject *self, PyObject *state)
{
    PyObject *slots=NULL;

    if (PyTuple_Check(state))
    {
        if (!PyArg_ParseTuple(state, "OO:__setstate__", &state, &slots))
            return NULL;
    }

    if (state != Py_None)
    {
        PyObject **dict;

        dict = _PyObject_GetDictPtr(self);
        
        if (!dict)
        {
            PyErr_SetString(PyExc_TypeError,
                            "this object has no instance dictionary");
            return NULL;
        }

        if (!*dict)
        {
            *dict = PyDict_New();
            if (!*dict)
                return NULL;
        }

        PyDict_Clear(*dict);
        if (PyDict_Update(*dict, state) < 0)
            return NULL;
    }

    if (slots && pickle_setattrs_from_dict(self, slots) < 0)
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}
示例#16
0
void expand_to_char(CHAR_DATA *ch, const char *mssg, PyObject *dict, 
		    const char *locale, bool newline) {
  BUFFER *buf = newBuffer(1);
  bufferCat(buf, mssg);
  if(dict != NULL) {
    // build the script dictionary
    PyObject *script_dict = restricted_script_dict();
    PyDict_Update(script_dict, dict);

    // do the expansion
    expand_dynamic_descs_dict(buf, script_dict, locale);

    // garbage collection and end
    Py_XDECREF(script_dict);
  }

  if(newline == TRUE)
    bufferCat(buf, "\r\n");
  text_to_char(ch, bufferString(buf));

  // garbage collection
  deleteBuffer(buf);
}
示例#17
0
文件: request.c 项目: RaNaN/bjoern
static int
on_message_complete(http_parser* parser)
{
  /* HTTP_CONTENT_{LENGTH,TYPE} -> CONTENT_{LENGTH,TYPE} */
  PyDict_ReplaceKey(REQUEST->headers, _HTTP_CONTENT_LENGTH, _CONTENT_LENGTH);
  PyDict_ReplaceKey(REQUEST->headers, _HTTP_CONTENT_TYPE, _CONTENT_TYPE);

  /* SERVER_PROTOCOL (REQUEST_PROTOCOL) */
  _set_header(_SERVER_PROTOCOL, parser->http_minor == 1 ? _HTTP_1_1 : _HTTP_1_0);

  /* REQUEST_METHOD */
  if(parser->method == HTTP_GET) {
    /* I love useless micro-optimizations. */
    _set_header(_REQUEST_METHOD, _GET);
  } else {
    _set_header_free_value(_REQUEST_METHOD,
      PyString_FromString(http_method_str(parser->method)));
  }

  /* REMOTE_ADDR */
  _set_header(_REMOTE_ADDR, REQUEST->client_addr);

  PyObject* body = PyDict_GetItem(REQUEST->headers, _wsgi_input);
  if(body) {
    /* We abused the `pos` member for tracking the amount of data copied from
     * the buffer in on_body, so reset it to zero here. */
    ((Iobject*)body)->pos = 0;
  } else {
    /* Request has no body */
    _set_header_free_value(_wsgi_input, PycStringIO->NewInput(_empty_string));
  }

  PyDict_Update(REQUEST->headers, wsgi_base_dict);

  REQUEST->state.parse_finished = true;
  return 0;
}
示例#18
0
/* call once __file__ is set */
void bpy_module_delay_init(PyObject *bpy_proxy)
{
	const int argc = 1;
	const char *argv[2];

	/* updating the module dict below will loose the reference to __file__ */
	PyObject *filename_obj = PyModule_GetFilenameObject(bpy_proxy);

	const char *filename_rel = _PyUnicode_AsString(filename_obj); /* can be relative */
	char filename_abs[1024];

	BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
	BLI_path_cwd(filename_abs);

	argv[0] = filename_abs;
	argv[1] = NULL;
	
	// printf("module found %s\n", argv[0]);

	main_python_enter(argc, argv);

	/* initialized in BPy_init_modules() */
	PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
}
示例#19
0
static PyObject*
_create_dict_from_event (SDL_Event *event, int release)
{
    PyObject *val = NULL;
    PyObject *dict = PyDict_New ();
    if (!dict)
        return NULL;

    if (event->type >= SDL_USEREVENT && event->type < SDL_NUMEVENTS)
    {
        if (event->user.code == PYGAME_USEREVENT_CODE &&
                event->user.data1 == (void*)PYGAME_USEREVENT)
        {
            /* It comes from pygame, it goes to pygame. */
            PyObject *vdict = (PyObject*) event->user.data2;
            if (PyDict_Update (dict, vdict) == -1)
                goto failed;
            if (release)
            {
                Py_DECREF (vdict);
            }
            return dict;
        }
        else
        {
            /* It comes from some SDL stuff, it goes to pygame. */
            if (!_set_item (dict, "code", PyInt_FromLong (event->user.code)))
                goto failed;
#if PY_VERSION_HEX >= 0x03010000
            if (!_set_item (dict, "data1",
                            PyCapsule_New (event->user.data1, "data1", NULL)))
                goto failed;
            if (!_set_item (dict, "data2",
                            PyCapsule_New (event->user.data2, "data2", NULL)))
                goto failed;
#else
            if (!_set_item (dict, "data1",
                            PyCObject_FromVoidPtr (event->user.data1, NULL)))
                goto failed;
            if (!_set_item (dict, "data2",
                            PyCObject_FromVoidPtr (event->user.data2, NULL)))
                goto failed;
#endif
        }
        return dict;
    }

    switch (event->type)
    {
    case SDL_ACTIVEEVENT:
        if (!_set_item (dict, "gain", PyInt_FromLong (event->active.gain)))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->active.state)))
            goto failed;
        break;

    case SDL_KEYDOWN:
    case SDL_KEYUP:
        if (!_set_item (dict, "state", PyInt_FromLong (event->key.state)))
            goto failed;
        if (!_set_item (dict, "scancode",
                        PyInt_FromLong (event->key.keysym.scancode)))
            goto failed;
        if (!_set_item (dict, "key",
                        PyLong_FromUnsignedLong (event->key.keysym.sym)))
            goto failed;
        if (!_set_item (dict, "sym",
                        PyLong_FromUnsignedLong (event->key.keysym.sym)))
            goto failed;
        if (!_set_item (dict, "mod",
                        PyLong_FromUnsignedLong (event->key.keysym.mod)))
            goto failed;
        /* if SDL_EnableUNICODE() == 0, unicode will be a 0 character */
        if (!_set_item (dict, "unicode",
                        PyUnicode_FromOrdinal (event->key.keysym.unicode)))
            goto failed;
        break;

    case SDL_MOUSEMOTION:
        if (!_set_item (dict, "state", PyInt_FromLong (event->motion.state)))
            goto failed;
        if (!_set_item (dict, "x", PyInt_FromLong (event->motion.x)))
            goto failed;
        if (!_set_item (dict, "y", PyInt_FromLong (event->motion.y)))
            goto failed;
        if (!_set_item (dict, "xrel", PyInt_FromLong (event->motion.xrel)))
            goto failed;
        if (!_set_item (dict, "yrel", PyInt_FromLong (event->motion.yrel)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->motion.x, event->motion.y);
        if (!val)
            goto failed;
        if (!_set_item (dict, "pos", val))
            goto failed;
        val = Py_BuildValue ("(ii)", event->motion.xrel, event->motion.yrel);
        if (!val)
            goto failed;
        if (!_set_item (dict, "rel", val))
            goto failed;
        val = PyTuple_New (3);
        if (!val)
            return NULL;
        PyTuple_SET_ITEM (val, 0,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(1)));
        PyTuple_SET_ITEM (val, 1,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(2)));
        PyTuple_SET_ITEM (val, 2,
                          PyBool_FromLong (event->motion.state & SDL_BUTTON(3)));
        if (!_set_item (dict, "buttons", val))
            goto failed;
        break;

    case SDL_MOUSEBUTTONDOWN:
    case SDL_MOUSEBUTTONUP:
        if (!_set_item (dict, "button", PyInt_FromLong (event->button.button)))
            goto failed;
        if (!_set_item (dict, "x", PyInt_FromLong (event->button.x)))
            goto failed;
        if (!_set_item (dict, "y", PyInt_FromLong (event->button.y)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->button.x, event->button.y);
        if (!val)
            goto failed;
        if (!_set_item (dict, "pos", val))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->button.state)))
            goto failed;
        break;

    case SDL_JOYAXISMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jaxis.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jaxis.which)))
            goto failed;
        if (!_set_item (dict, "axis", PyInt_FromLong (event->jaxis.axis)))
            goto failed;
        if (!_set_item (dict, "value", PyInt_FromLong (event->jaxis.value)))
            goto failed;
        break;

    case SDL_JOYBALLMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jball.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jball.which)))
            goto failed;
        if (!_set_item (dict, "ball", PyInt_FromLong (event->jball.ball)))
            goto failed;
        if (!_set_item (dict, "xrel", PyInt_FromLong (event->jball.xrel)))
            goto failed;
        if (!_set_item (dict, "yrel", PyInt_FromLong (event->jball.yrel)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->jball.xrel, event->jball.yrel);
        if (!val)
            goto failed;
        if (!_set_item (dict, "rel", val))
            goto failed;
        break;

    case SDL_JOYHATMOTION:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jhat.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jhat.which)))
            goto failed;
        if (!_set_item (dict, "hat", PyInt_FromLong (event->jhat.hat)))
            goto failed;
        if (!_set_item (dict, "value", PyInt_FromLong (event->jhat.value)))
            goto failed;
        break;

    case SDL_JOYBUTTONDOWN:
    case SDL_JOYBUTTONUP:
        if (!_set_item (dict, "which", PyInt_FromLong (event->jbutton.which)))
            goto failed;
        if (!_set_item (dict, "joy", PyInt_FromLong (event->jbutton.which)))
            goto failed;
        if (!_set_item (dict, "button", PyInt_FromLong (event->jbutton.button)))
            goto failed;
        if (!_set_item (dict, "state", PyInt_FromLong (event->jbutton.state)))
            goto failed;
        break;

    case SDL_VIDEORESIZE:
        if (!_set_item (dict, "w", PyInt_FromLong (event->resize.w)))
            goto failed;
        if (!_set_item (dict, "h", PyInt_FromLong (event->resize.h)))
            goto failed;
        val = Py_BuildValue ("(ii)", event->resize.w, event->resize.h);
        if (!val)
            goto failed;
        if (!_set_item (dict, "size", val))
            goto failed;
        break;

    case SDL_SYSWMEVENT:
#if defined(SDL_VIDEO_DRIVER_WINDIB) || defined(SDL_VIDEO_DRIVER_DDRAW) || defined(SDL_VIDEO_DRIVER_GAPI)
        if (!_set_item (dict, "hwnd",
                        PyInt_FromLong ((long) event->syswm.msg->hwnd)))
            goto failed;
        if (!_set_item (dict, "msg", PyInt_FromLong (event->syswm.msg->msg)))
            goto failed;
        if (!_set_item (dict, "wparam",
                        PyInt_FromLong (event->syswm.msg->wParam)))
            goto failed;
        if (!_set_item (dict, "lparam",
                        PyInt_FromLong (event-> syswm.msg->lParam)))
            goto failed;
#elif defined(SDL_VIDEO_DRIVER_X11)
        if (!_set_item (dict,  "event", Text_FromUTF8AndSize
                        ((char*) &(event->syswm.msg->event.xevent), sizeof (XEvent))))
            goto failed;
#endif
        break;
    case SDL_QUIT:
        break;
    case SDL_VIDEOEXPOSE:
        break;
    default:
        break;
    }

    return dict;

failed:
    Py_XDECREF (val);
    Py_XDECREF (dict);
    return NULL;
}
示例#20
0
void wsgi_publish_event(const char *name, PyObject *event)
{
    int i;

    PyObject *module = NULL;
    PyObject *list = NULL;

    module = PyImport_ImportModule("mod_wsgi");

    if (module) {
        PyObject *dict = NULL;

        dict = PyModule_GetDict(module);
        list = PyDict_GetItemString(dict, "event_callbacks");

        Py_INCREF(list);
    }
    else {
        Py_BEGIN_ALLOW_THREADS
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
                     "mod_wsgi (pid=%d): Unable to import mod_wsgi when "
                     "publishing events.", getpid());
        Py_END_ALLOW_THREADS

        PyErr_Clear();

        return;
    }

    Py_XDECREF(module);

    if (!list) {
        Py_BEGIN_ALLOW_THREADS
        ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
                     "mod_wsgi (pid=%d): Unable to find event subscribers.",
                     getpid());
        Py_END_ALLOW_THREADS

        PyErr_Clear();

        return;
    }

    for (i=0; i<PyList_Size(list); i++) {
        PyObject *callback = NULL;

        PyObject *res = NULL;
        PyObject *args = NULL;

        callback = PyList_GetItem(list, i);

        Py_INCREF(callback);

        args = Py_BuildValue("(s)", name);

        res = PyObject_Call(callback, args, event);

        if (!res) {
            PyObject *m = NULL;
            PyObject *result = NULL;

            PyObject *type = NULL;
            PyObject *value = NULL;
            PyObject *traceback = NULL;

            Py_BEGIN_ALLOW_THREADS
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
                         "mod_wsgi (pid=%d): Exception occurred within "
                         "event callback.", getpid());
            Py_END_ALLOW_THREADS

            PyErr_Fetch(&type, &value, &traceback);
            PyErr_NormalizeException(&type, &value, &traceback);

            if (!value) {
                value = Py_None;
                Py_INCREF(value);
            }

            if (!traceback) {
                traceback = Py_None;
                Py_INCREF(traceback);
            }

            m = PyImport_ImportModule("traceback");

            if (m) {
                PyObject *d = NULL;
                PyObject *o = NULL;
                d = PyModule_GetDict(m);
                o = PyDict_GetItemString(d, "print_exception");
                if (o) {
                    PyObject *log = NULL;
                    PyObject *args = NULL;
                    Py_INCREF(o);
                    log = newLogObject(NULL, APLOG_ERR, NULL, 0);
                    args = Py_BuildValue("(OOOOO)", type, value,
                                         traceback, Py_None, log);
                    result = PyEval_CallObject(o, args);
                    Py_DECREF(args);
                    Py_DECREF(log);
                    Py_DECREF(o);
                }
            }

            if (!result) {
                /*
                 * If can't output exception and traceback then
                 * use PyErr_Print to dump out details of the
                 * exception. For SystemExit though if we do
                 * that the process will actually be terminated
                 * so can only clear the exception information
                 * and keep going.
                 */

                PyErr_Restore(type, value, traceback);

                if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
                    PyErr_Print();
                    PyErr_Clear();
                }
                else {
                    PyErr_Clear();
                }
            }
            else {
                Py_XDECREF(type);
                Py_XDECREF(value);
                Py_XDECREF(traceback);
            }

            Py_XDECREF(result);

            Py_XDECREF(m);
        }
        else if (PyDict_Check(res)) {
            PyDict_Update(event, res);
        }

        Py_XDECREF(res);

        Py_DECREF(callback);
        Py_DECREF(args);
    }

    Py_DECREF(list);
}
示例#21
0
文件: map.cpp 项目: lweijin/kbengine
//-------------------------------------------------------------------------------------
PyObject* Map::__py_update(PyObject* self, PyObject* args)
{
	PyDict_Update(static_cast<Map*>(self)->pyDict_, args);
	S_Return; 
}
示例#22
0
static int
analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, 
	      PyObject *global)
{
	PyObject *name, *v, *local = NULL, *scope = NULL, *newbound = NULL;
	PyObject *newglobal = NULL, *newfree = NULL;
	int i, success = 0;
	Py_ssize_t pos = 0;

	local = PyDict_New();
	if (!local)
		goto error;
	scope = PyDict_New();
	if (!scope)
		goto error;
	newglobal = PyDict_New();
	if (!newglobal)
		goto error;
	newfree = PyDict_New();
	if (!newfree)
		goto error;
	newbound = PyDict_New();
	if (!newbound)
		goto error;

	if (ste->ste_type == ClassBlock) {
		/* make a copy of globals before calling analyze_name(),
		   because global statements in the class have no effect
		   on nested functions.
		*/
		if (PyDict_Update(newglobal, global) < 0)
			goto error;
		if (bound)
			if (PyDict_Update(newbound, bound) < 0)
				goto error;
	}

	assert(PySTEntry_Check(ste));
	assert(PyDict_Check(ste->ste_symbols));
	while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
		long flags = PyInt_AS_LONG(v);
		if (!analyze_name(ste, scope, name, flags, bound, local, free,
				  global))
			goto error;
	}

	if (ste->ste_type != ClassBlock) {
		if (ste->ste_type == FunctionBlock) {
			if (PyDict_Update(newbound, local) < 0)
				goto error;
		}
		if (bound) {
			if (PyDict_Update(newbound, bound) < 0)
				goto error;
		}
		if (PyDict_Update(newglobal, global) < 0)
			goto error;
	}

	/* Recursively call analyze_block() on each child block */
	for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
		PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
		PySTEntryObject* entry;
		assert(c && PySTEntry_Check(c));
		entry = (PySTEntryObject*)c;
		if (!analyze_block(entry, newbound, newfree, newglobal))
			goto error;
		if (entry->ste_free || entry->ste_child_free)
			ste->ste_child_free = 1;
	}

	if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
		goto error;
	if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
			    ste->ste_type == ClassBlock))
		goto error;
	if (!check_unoptimized(ste))
		goto error;

	if (PyDict_Update(free, newfree) < 0)
		goto error;
	success = 1;
 error:
	Py_XDECREF(local);
	Py_XDECREF(scope);
	Py_XDECREF(newbound);
	Py_XDECREF(newglobal);
	Py_XDECREF(newfree);
	if (!success)
		assert(PyErr_Occurred());
	return success;
}
示例#23
0
static int
analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
              PyObject *global)
{
    PyObject *name, *v, *local = NULL, *scope = NULL;
    PyObject *newbound = NULL, *newglobal = NULL;
    PyObject *newfree = NULL, *allfree = NULL;
    int i, success = 0;
    Py_ssize_t pos = 0;

    local = PyDict_New();  /* collect new names bound in block */
    if (!local)
        goto error;
    scope = PyDict_New(); /* collect scopes defined for each name */
    if (!scope)
        goto error;

    /* Allocate new global and bound variable dictionaries.  These
       dictionaries hold the names visible in nested blocks.  For
       ClassBlocks, the bound and global names are initialized
       before analyzing names, because class bindings aren't
       visible in methods.  For other blocks, they are initialized
       after names are analyzed.
     */

    /* TODO(jhylton): Package these dicts in a struct so that we
       can write reasonable helper functions?
    */
    newglobal = PyDict_New();
    if (!newglobal)
        goto error;
    newbound = PyDict_New();
    if (!newbound)
        goto error;
    newfree = PyDict_New();
    if (!newfree)
        goto error;

    if (ste->ste_type == ClassBlock) {
        if (PyDict_Update(newglobal, global) < 0)
            goto error;
        if (bound)
            if (PyDict_Update(newbound, bound) < 0)
                goto error;
    }

    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
        long flags = PyInt_AS_LONG(v);
        if (!analyze_name(ste, scope, name, flags,
                          bound, local, free, global))
            goto error;
    }

    if (ste->ste_type != ClassBlock) {
        if (ste->ste_type == FunctionBlock) {
            if (PyDict_Update(newbound, local) < 0)
                goto error;
        }
        if (bound) {
            if (PyDict_Update(newbound, bound) < 0)
                goto error;
        }
        if (PyDict_Update(newglobal, global) < 0)
            goto error;
    }

    /* Recursively call analyze_block() on each child block.

       newbound, newglobal now contain the names visible in
       nested blocks.  The free variables in the children will
       be collected in allfree.
    */
    allfree = PyDict_New();
    if (!allfree)
        goto error;
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
        PySTEntryObject* entry;
        assert(c && PySTEntry_Check(c));
        entry = (PySTEntryObject*)c;
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
                                 allfree))
            goto error;
        if (entry->ste_free || entry->ste_child_free)
            ste->ste_child_free = 1;
    }

    if (PyDict_Update(newfree, allfree) < 0)
        goto error;
    if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
        goto error;
    if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
                        ste->ste_type == ClassBlock))
        goto error;
    if (!check_unoptimized(ste))
        goto error;

    if (PyDict_Update(free, newfree) < 0)
        goto error;
    success = 1;
 error:
    Py_XDECREF(local);
    Py_XDECREF(scope);
    Py_XDECREF(newbound);
    Py_XDECREF(newglobal);
    Py_XDECREF(newfree);
    Py_XDECREF(allfree);
    if (!success)
        assert(PyErr_Occurred());
    return success;
}
示例#24
0
	k3d::bool_t execute(const k3d::string_t& ScriptName, const k3d::string_t& Script, context& Context, output_t* Stdout, output_t* Stderr)
	{
		k3d::bool_t succeeded = true;

		try
		{
			boost::scoped_ptr<k3d::python::file_signal> stdout_signal;
			boost::scoped_ptr<k3d::python::file_signal> stderr_signal;

			if(Stdout)
			{
				stdout_signal.reset(new k3d::python::file_signal());
				stdout_signal->connect_output_signal(*Stdout);
				PySys_SetObject(const_cast<char*>("stdout"), boost::python::object(*stdout_signal).ptr());
			}

			if(Stderr)
			{
				stderr_signal.reset(new k3d::python::file_signal());
				stderr_signal->connect_output_signal(*Stderr);
				PySys_SetObject(const_cast<char*>("stderr"), boost::python::object(*stderr_signal).ptr());
			}

			m_local_dict["context"] = Context;

			// The embedded python interpreter cannot handle DOS line-endings, see http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1167922
			k3d::string_t script = Script;
			script.erase(std::remove(script.begin(), script.end(), '\r'), script.end());

			PyDict_Update(m_local_dict.ptr(), PyObject_GetAttrString(PyImport_AddModule("__main__"), "__dict__"));
			
			PyObject* const result = PyRun_String(const_cast<char*>(script.c_str()), Py_file_input, m_local_dict.ptr(), m_local_dict.ptr());
			if(result)
			{
				Py_DECREF(result);
				if(Py_FlushLine())
					PyErr_Clear();
			}
			else
			{
				PyErr_Print();
			}

			Context = boost::python::extract<k3d::iscript_engine::context>(m_local_dict["context"])();

			succeeded = result ? true : false;
		}
		catch(std::exception& e)
		{
			k3d::log() << error << k3d_file_reference << ": " << e.what() << std::endl;
			succeeded = false;
		}
		catch(...)
		{
			k3d::log() << error << k3d_file_reference << ": " << "Unknown exception" << std::endl;
			succeeded = false;
		}

		if(Stdout)
		      PySys_SetObject(const_cast<char*>("stdout"), PySys_GetObject(const_cast<char*>("__stdout__")));

		if(Stderr)
		      PySys_SetObject(const_cast<char*>("stderr"), PySys_GetObject(const_cast<char*>("__stderr__")));

		return succeeded;
	}