Exemple #1
1
/*
 * Initial load of the Python module.
 *
 * Based on the parsed plugin options we set some prerequisits like the
 * module path and the module to load. We also load the dictionary used
 * for looking up the Python methods.
 */
static bRC PyLoadModule(bpContext *ctx, void *value)
{
   bRC retval = bRC_Error;
   struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext;
   PyObject *sysPath,
            *mPath,
            *pName,
            *pFunc,
            *module;

   /*
    * Extend the Python search path with the given module_path.
    */
   if (p_ctx->module_path) {
      sysPath = PySys_GetObject((char *)"path");
      mPath = PyString_FromString(p_ctx->module_path);
      PyList_Append(sysPath, mPath);
      Py_DECREF(mPath);
   }

   /*
    * Make our callback methods available for Python.
    */
   module = Py_InitModule("bareossd", BareosSDMethods);

   /*
    * Try to load the Python module by name.
    */
   if (p_ctx->module_name) {
      Dmsg(ctx, dbglvl, "Trying to load module with name %s\n", p_ctx->module_name);
      pName = PyString_FromString(p_ctx->module_name);
      p_ctx->pModule = PyImport_Import(pName);
      Py_DECREF(pName);

      if (!p_ctx->pModule) {
         Dmsg(ctx, dbglvl, "Failed to load module with name %s\n", p_ctx->module_name);
         goto bail_out;
      }

      Dmsg(ctx, dbglvl, "Successfully loaded module with name %s\n", p_ctx->module_name);

      /*
       * Get the Python dictionary for lookups in the Python namespace.
       */
      p_ctx->pDict = PyModule_GetDict(p_ctx->pModule); /* Borrowed reference */

      /*
       * Encode the bpContext so a Python method can pass it in on calling back.
       */
      p_ctx->bpContext = PyCreatebpContext(ctx);

      /*
       * Lookup the load_bareos_plugin() function in the python module.
       */
      pFunc = PyDict_GetItemString(p_ctx->pDict, "load_bareos_plugin"); /* Borrowed reference */
      if (pFunc && PyCallable_Check(pFunc)) {
         PyObject *pPluginDefinition,
                  *pRetVal;

         pPluginDefinition = PyString_FromString((char *)value);
         if (!pPluginDefinition) {
            goto bail_out;
         }

         pRetVal = PyObject_CallFunctionObjArgs(pFunc, p_ctx->bpContext, pPluginDefinition, NULL);
         Py_DECREF(pPluginDefinition);

         if (!pRetVal) {
            goto bail_out;
         } else {
            retval = conv_python_retval(pRetVal);
            Py_DECREF(pRetVal);
         }
      } else {
         Dmsg(ctx, dbglvl, "Failed to find function named load_bareos_plugins()\n");
         goto bail_out;
      }
   }

   /*
    * Keep track we successfully loaded.
    */
   p_ctx->python_loaded = true;

   return retval;

bail_out:
   if (PyErr_Occurred()) {
      PyErrorHandler(ctx, M_FATAL);
   }

   return retval;
}
Exemple #2
0
static int
Channel_tp_init(Channel *self, PyObject *args, PyObject *kwargs)
{
    int r, flags, tries, ndots, tcp_port, udp_port, optmask, ndomains, socket_send_buffer_size, socket_receive_buffer_size;
    char *lookups;
    char **c_domains;
    double timeout;
    struct ares_options options;
    PyObject *servers, *domains, *sock_state_cb;

    static char *kwlist[] = {"flags", "timeout", "tries", "ndots", "tcp_port", "udp_port",
                             "servers", "domains", "lookups", "sock_state_cb", "socket_send_buffer_size", "socket_receive_buffer_size", NULL};

    optmask = 0;
    flags = tries = ndots = tcp_port = udp_port = socket_send_buffer_size = socket_receive_buffer_size = -1;
    timeout = -1.0;
    lookups = NULL;
    c_domains = NULL;
    servers = domains = sock_state_cb = NULL;

    if (self->channel) {
        PyErr_SetString(PyExc_AresError, "Object already initialized");
        return -1;
    }

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|idiiiiOOsOii:__init__", kwlist, &flags, &timeout, &tries, &ndots, &tcp_port, &udp_port, &servers,
                                                                                     &domains, &lookups, &sock_state_cb, &socket_send_buffer_size, &socket_receive_buffer_size)) {
        return -1;
    }

    if (sock_state_cb && !PyCallable_Check(sock_state_cb)) {
        PyErr_SetString(PyExc_TypeError, "sock_state_cb is not callable");
        return -1;
    }

    r = ares_library_init(ARES_LIB_INIT_ALL);
    if (r != ARES_SUCCESS) {
        RAISE_ARES_EXCEPTION(r);
        return -1;
    }
    self->lib_initialized = True;

    memset(&options, 0, sizeof(struct ares_options));

    if (flags != -1) {
        options.flags = flags;
        optmask |= ARES_OPT_FLAGS;
    }
    if (timeout != -1) {
        options.timeout = (int)timeout * 1000;
        optmask |= ARES_OPT_TIMEOUTMS;
    }
    if (tries != -1) {
        options.tries = tries;
        optmask |= ARES_OPT_TRIES;
    }
    if (ndots != -1) {
        options.ndots = ndots;
        optmask |= ARES_OPT_NDOTS;
    }
    if (tcp_port != -1) {
        options.tcp_port = tcp_port;
        optmask |= ARES_OPT_TCP_PORT;
    }
    if (udp_port != -1) {
        options.udp_port = udp_port;
        optmask |= ARES_OPT_UDP_PORT;
    }
    if (socket_send_buffer_size != -1) {
        options.socket_send_buffer_size = socket_send_buffer_size;
        optmask |= ARES_OPT_SOCK_SNDBUF;
    }
    if (socket_receive_buffer_size != -1) {
        options.socket_receive_buffer_size = socket_receive_buffer_size;
        optmask |= ARES_OPT_SOCK_RCVBUF;
    }
    if (sock_state_cb) {
        options.sock_state_cb = ares__sock_state_cb;
        options.sock_state_cb_data = (void *)self;
        optmask |= ARES_OPT_SOCK_STATE_CB;
        Py_INCREF(sock_state_cb);
        self->sock_state_cb = sock_state_cb;
    }
    if (lookups) {
        options.lookups = lookups;
        optmask |= ARES_OPT_LOOKUPS;
    }
    if (domains) {
        process_domains(domains, &c_domains, &ndomains);
        if (ndomains == -1) {
            goto error;
        }
        options.domains = c_domains;
        options.ndomains = ndomains;
        optmask |= ARES_OPT_DOMAINS;
    }

    r = ares_init_options(&self->channel, &options, optmask);
    if (r != ARES_SUCCESS) {
        RAISE_ARES_EXCEPTION(r);
        goto error;
    }

    free_domains(c_domains);

    if (servers) {
        return set_nameservers(self, servers);
    }

    return 0;

error:
    free_domains(c_domains);
    Py_XDECREF(sock_state_cb);
    return -1;
}
Exemple #3
0
int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue, *pArgs;

    if (argc < 5) {
        printf("Usage: exe_name python_source function_name\n");
        return 1;
    }

    /* Initialize the Python Interpreter */
    Py_Initialize();
    PySys_SetArgv(argc, argv);

    /* Build the name object */
    /* Convery C-String to PyString */
    pName = PyString_FromString(argv[1]);

    /* Load the module object */
    pModule = PyImport_Import(pName);

    /* pDict is a borrowed reference */
    /* Equivalent to __dict__ attribute of object */
    pDict = PyModule_GetDict(pModule);

    /* pFunc is also a borrowed reference */
    /* Get value of object with key 'argv[2]' */ 
    /* This is the function we'll execute */
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    /* Prepare a tuple which will contain arguments for our Python function */

    /* Create tuple of size 2 */
    pArgs = PyTuple_New(2);

    /* We set the values at indices as provided by main program arguments */
    PyTuple_SetItem(pArgs, 0, PyInt_FromLong(atoi(argv[3])));
    PyTuple_SetItem(pArgs, 1, PyInt_FromLong(atoi(argv[4])));

    /* First check if the PyObject retrieved is callable */
    if (PyCallable_Check(pFunc)) {
        /* To store return value by the called function */
        PyObject *result;

        /* => PyObject_CallObject(object, arguments) */
        if (result = PyObject_CallObject(pFunc, pArgs)) {
            /* We convery returned PyObject to C's long */
            long resultLong = PyInt_AsLong(result);
            printf("Result is: %ld\n", resultLong);
        }
        else {
            /* Since NULL is returned, and NULL is error */
            printf("Failed\n");
        }
    } 
    else {
        /* What you provided wasnt callable */
        PyErr_Print();
    }

    /* Clean up */
    Py_DECREF(pModule);
    Py_DECREF(pName);
    Py_DECREF(pArgs);

    /* Shutdown Python Interpreter */
    Py_Finalize();

    return 0;
}
Exemple #4
0
static PyObject *
DNSResolver_func_getaddrinfo(DNSResolver *self, PyObject *args, PyObject *kwargs)
{
    char *name;
    char port_str[6];
    int port, family, socktype, protocol, flags, r;
    struct addrinfo hints;
    ares_cb_data_t *cb_data = NULL;
    uv_getaddrinfo_t* handle = NULL;
    PyObject *callback;

    static char *kwlist[] = {"callback", "name", "port", "family", "socktype", "protocol", "flags", NULL};

    port = socktype = protocol = flags = 0;
    family = AF_UNSPEC;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sO|iiiii:getaddrinfo", kwlist, &name, &callback, &port, &family, &socktype, &protocol, &flags)) {
        return NULL;
    }

    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        return NULL;
    }

    if (port < 0 || port > 65536) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65536");
        return NULL;
    }
    snprintf(port_str, sizeof(port_str), "%d", port);

    handle = PyMem_Malloc(sizeof(uv_getaddrinfo_t));
    if (!handle) {
        PyErr_NoMemory();
        goto error;
    }

    cb_data = (ares_cb_data_t*) PyMem_Malloc(sizeof *cb_data);
    if (!cb_data) {
        PyErr_NoMemory();
        goto error;
    }

    Py_INCREF(callback);
    cb_data->resolver = self;
    cb_data->cb = callback;
    handle->data = (void *)cb_data;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = family;
    hints.ai_socktype = socktype;
    hints.ai_protocol = protocol;
    hints.ai_flags = flags;

    r = uv_getaddrinfo(UV_LOOP(self), handle, &getaddrinfo_cb, name, port_str, &hints);
    if (r != 0) {
        raise_uv_exception(self->loop, PyExc_DNSError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    if (handle) {
        PyMem_Free(handle);
    }
    if (cb_data) {
        Py_DECREF(callback);
        PyMem_Free(cb_data);
    }
    return NULL;
}
Exemple #5
0
// Create a dynamic meta-object for a Python type by introspecting its
// attributes.  Note that it leaks if the type is deleted.
static int create_dynamic_metaobject(pyqtWrapperType *pyqt_wt)
{
    PyTypeObject *pytype = (PyTypeObject *)pyqt_wt;
    qpycore_metaobject *qo = new qpycore_metaobject;
    QMetaObjectBuilder builder;

    // Get any class info.
    QList<ClassInfo> class_info_list = qpycore_get_class_info_list();

    // Get any enums/flags.
    QList<EnumsFlags> enums_flags_list = qpycore_get_enums_flags_list();

    // Get the super-type's meta-object.
    builder.setSuperClass(get_qmetaobject((pyqtWrapperType *)pytype->tp_base));

    // Get the name of the type.  Dynamic types have simple names.
    builder.setClassName(pytype->tp_name);

    // Go through the class hierarchy getting all PyQt properties, slots and
    // signals.

    QList<const qpycore_pyqtSignal *> psigs;
    QMap<uint, PropertyData> pprops;

    if (trawl_hierarchy(pytype, qo, builder, psigs, pprops) < 0)
        return -1;

    qo->nr_signals = psigs.count();

    // Initialise the header section of the data table.  Note that Qt v4.5
    // introduced revision 2 which added constructors.  However the design is
    // broken in that the static meta-call function doesn't provide enough
    // information to determine which Python sub-class of a Qt class is to be
    // created.  So we stick with revision 1 (and don't allow pyqtSlot() to
    // decorate __init__).

    // Set up any class information.
    for (int i = 0; i < class_info_list.count(); ++i)
    {
        const ClassInfo &ci = class_info_list.at(i);

        builder.addClassInfo(ci.first, ci.second);
    }

    // Set up any enums/flags.
    for (int i = 0; i < enums_flags_list.count(); ++i)
    {
        const EnumsFlags &ef = enums_flags_list.at(i);

        QByteArray scoped_name(pytype->tp_name);
        scoped_name.append("::");
        scoped_name.append(ef.name);
        QMetaEnumBuilder enum_builder = builder.addEnumerator(scoped_name);

        enum_builder.setIsFlag(ef.isFlag);

        QHash<QByteArray, int>::const_iterator it = ef.keys.constBegin();

        while (it != ef.keys.constEnd())
        {
            enum_builder.addKey(it.key(), it.value());
            ++it;
        }
    }

    // Add the signals to the meta-object.
    for (int g = 0; g < qo->nr_signals; ++g)
    {
        const qpycore_pyqtSignal *ps = psigs.at(g);

        QMetaMethodBuilder signal_builder = builder.addSignal(
                ps->parsed_signature->signature.mid(1));

        if (ps->parameter_names)
            signal_builder.setParameterNames(*ps->parameter_names);

        signal_builder.setRevision(ps->revision);
    }

    // Add the slots to the meta-object.
    for (int s = 0; s < qo->pslots.count(); ++s)
    {
        const Chimera::Signature *slot_signature = qo->pslots.at(s)->slotSignature();
        const QByteArray &sig = slot_signature->signature;

        QMetaMethodBuilder slot_builder = builder.addSlot(sig);

        // Add any type.
        if (slot_signature->result)
            slot_builder.setReturnType(slot_signature->result->name());

        slot_builder.setRevision(slot_signature->revision);
    }

    // Add the properties to the meta-object.
    QMapIterator<uint, PropertyData> it(pprops);

    for (int p = 0; it.hasNext(); ++p)
    {
        it.next();

        const PropertyData &pprop = it.value();
        const char *prop_name = SIPBytes_AS_STRING(pprop.first);
        qpycore_pyqtProperty *pp = (qpycore_pyqtProperty *)pprop.second;
        int notifier_id;

        if (pp->pyqtprop_notify)
        {
            qpycore_pyqtSignal *ps = (qpycore_pyqtSignal *)pp->pyqtprop_notify;
            const QByteArray &sig = ps->parsed_signature->signature;

            notifier_id = builder.indexOfSignal(sig.mid(1));

            if (notifier_id < 0)
            {
                PyErr_Format(PyExc_TypeError,
                        "the notify signal '%s' was not defined in this class",
                        sig.constData() + 1);

                // Note that we leak the property name.
                return -1;
            }
        }
        else
        {
            notifier_id = -1;
        }

        // A Qt v5 revision 7 meta-object holds the QMetaType::Type of the type
        // or its name if it is unresolved (ie. not known to the type system).
        // In Qt v4 both are held.  For QObject sub-classes Chimera will fall
        // back to the QMetaType::QObjectStar if there is no specific meta-type
        // for the sub-class.  This means that, for Qt v4,
        // QMetaProperty::read() can handle the type.  However, Qt v5 doesn't
        // know that the unresolved type is a QObject sub-class.  Therefore we
        // have to tell it that the property is a QObject, rather than the
        // sub-class.  This means that QMetaProperty.typeName() will always
        // return "QObject*".
        QByteArray prop_type;

        if (pp->pyqtprop_parsed_type->metatype() == QMetaType::QObjectStar)
        {
            // However, if the type is a Python sub-class of QObject then we
            // use the name of the Python type.  This anticipates that the type
            // is one that will be proxied by QML at some point.
            if (pp->pyqtprop_parsed_type->typeDef() == sipType_QObject)
            {
                prop_type = ((PyTypeObject *)pp->pyqtprop_parsed_type->py_type())->tp_name;
                prop_type.append('*');
            }
            else
            {
                prop_type = "QObject*";
            }
        }
        else
        {
            prop_type = pp->pyqtprop_parsed_type->name();
        }

        QMetaPropertyBuilder prop_builder = builder.addProperty(prop_name,
                prop_type, notifier_id);

        // Reset the defaults.
        prop_builder.setReadable(false);
        prop_builder.setWritable(false);

        // Enum or flag.
        if (pp->pyqtprop_parsed_type->isEnum() || pp->pyqtprop_parsed_type->isFlag())
        {
            prop_builder.setEnumOrFlag(true);
        }

        if (pp->pyqtprop_get && PyCallable_Check(pp->pyqtprop_get))
        {
            // Readable.
            prop_builder.setReadable(true);
        }

        if (pp->pyqtprop_set && PyCallable_Check(pp->pyqtprop_set))
        {
            // Writable.
            prop_builder.setWritable(true);

            // See if the name of the setter follows the Designer convention.
            // If so tell the UI compilers not to use setProperty().
            PyObject *setter_name_obj = PyObject_GetAttr(pp->pyqtprop_set,
                    qpycore_dunder_name);

            if (setter_name_obj)
            {
                PyObject *ascii_obj = setter_name_obj;
                const char *ascii = sipString_AsASCIIString(&ascii_obj);
                Py_DECREF(setter_name_obj);

                if (ascii)
                {
                    if (qstrlen(ascii) > 3 && ascii[0] == 's' &&
                            ascii[1] == 'e' && ascii[2] == 't' &&
                            ascii[3] == toupper(prop_name[0]) &&
                            qstrcmp(&ascii[4], &prop_name[1]) == 0)
                        prop_builder.setStdCppSet(true);
                }

                Py_DECREF(ascii_obj);
            }

            PyErr_Clear();
        }

        if (pp->pyqtprop_reset && PyCallable_Check(pp->pyqtprop_reset))
        {
            // Resetable.
            prop_builder.setResettable(true);
        }

        // Add the property flags.  Note that Qt4 always seems to have
        // ResolveEditable set but QMetaObjectBuilder doesn't provide an API
        // call to do it.
        prop_builder.setDesignable(pp->pyqtprop_flags & 0x00001000);
        prop_builder.setScriptable(pp->pyqtprop_flags & 0x00004000);
        prop_builder.setStored(pp->pyqtprop_flags & 0x00010000);
        prop_builder.setUser(pp->pyqtprop_flags & 0x00100000);
        prop_builder.setConstant(pp->pyqtprop_flags & 0x00000400);
        prop_builder.setFinal(pp->pyqtprop_flags & 0x00000800);

        prop_builder.setRevision(pp->pyqtprop_revision);

        // Save the property data for qt_metacall().  (We already have a
        // reference.)
        qo->pprops.append(pp);

        // We've finished with the property name.
        Py_DECREF(pprop.first);
    }

    // Initialise the rest of the meta-object.
    qo->mo = builder.toMetaObject();

    // Save the meta-object.
    pyqt_wt->metaobject = qo;

    return 0;
}
Exemple #6
0
/**
 * @name    Callback Handling
 * @brief   Handle a callback coming from GPI
 * @ingroup python_c_api
 *
 * GILState before calling: Unknown
 *
 * GILState after calling: Unknown
 *
 * Makes one call to TAKE_GIL and one call to DROP_GIL
 *
 * Returns 0 on success or 1 on a failure.
 *
 * Handles a callback from the simulator, all of which call this function.
 *
 * We extract the associated context and find the Python function (usually
 * cocotb.scheduler.react) calling it with a reference to the trigger that
 * fired. The scheduler can then call next() on all the coroutines that
 * are waiting on that particular trigger.
 *
 * TODO:
 *  - Tidy up return values
 *  - Ensure cleanup correctly in exception cases
 *
 */
int handle_gpi_callback(void *user_data)
{
    int ret = 0;
    to_python();
    p_callback_data callback_data_p = (p_callback_data)user_data;

    if (callback_data_p->id_value != COCOTB_ACTIVE_ID) {
        fprintf(stderr, "Userdata corrupted!\n");
        ret = 1;
        goto err;
    }
    callback_data_p->id_value = COCOTB_INACTIVE_ID;

    /* Cache the sim time */
    gpi_get_sim_time(&cache_time.high, &cache_time.low);

    PyGILState_STATE gstate;
    gstate = TAKE_GIL();

    // Python allowed

    if (!PyCallable_Check(callback_data_p->function)) {
        fprintf(stderr, "Callback fired but function isn't callable?!\n");
        ret = 1;
        goto out;
    }

    // Call the callback
    PyObject *pValue = PyObject_Call(callback_data_p->function, callback_data_p->args, callback_data_p->kwargs);

    // If the return value is NULL a Python exception has occurred
    // The best thing to do here is shutdown as any subsequent
    // calls will go back to python which is now in an unknown state
    if (pValue == NULL)
    {
        fprintf(stderr, "ERROR: called callback function returned NULL\n");
        if (PyErr_Occurred()) {
            fprintf(stderr, "Failed to execute callback due to python exception\n");
            PyErr_Print();
        } else {
            fprintf(stderr, "Failed to execute callback\n");
        }

        gpi_sim_end();
        ret = 0;
        goto out;
    }

    // Free up our mess
    Py_DECREF(pValue);

    // Callbacks may have been re-enabled
    if (callback_data_p->id_value == COCOTB_INACTIVE_ID) {
        Py_DECREF(callback_data_p->function);
        Py_DECREF(callback_data_p->args);

        // Free the callback data
        free(callback_data_p);
    }

out:
    DROP_GIL(gstate);

err:
    to_simulator();
    return ret;
}
Exemple #7
0
static void python_process_tracepoint(struct perf_sample *sample,
				      struct perf_evsel *evsel,
				      struct thread *thread,
				      struct addr_location *al)
{
	PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
	static char handler_name[256];
	struct format_field *field;
	unsigned long long val;
	unsigned long s, ns;
	struct event_format *event;
	unsigned n = 0;
	int pid;
	int cpu = sample->cpu;
	void *data = sample->raw_data;
	unsigned long long nsecs = sample->time;
	const char *comm = thread__comm_str(thread);

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	event = find_cache_event(evsel);
	if (!event)
		die("ug! no event found for type %d", (int)evsel->attr.config);

	pid = raw_field_value(event, "common_pid", data);

	sprintf(handler_name, "%s__%s", event->system, event->name);

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		handler = NULL;
	if (!handler) {
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
	s = nsecs / NSECS_PER_SEC;
	ns = nsecs - s * NSECS_PER_SEC;

	scripting_context->event_data = data;
	scripting_context->pevent = evsel->tp_format->pevent;

	context = PyCObject_FromVoidPtr(scripting_context, NULL);

	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
	PyTuple_SetItem(t, n++, context);

	if (handler) {
		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
		PyTuple_SetItem(t, n++, PyString_FromString(comm));
	} else {
		pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
		pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
		pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
		pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
		pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
	}
	for (field = event->format.fields; field; field = field->next) {
		if (field->flags & FIELD_IS_STRING) {
			int offset;
			if (field->flags & FIELD_IS_DYNAMIC) {
				offset = *(int *)(data + field->offset);
				offset &= 0xffff;
			} else
				offset = field->offset;
			obj = PyString_FromString((char *)data + offset);
		} else { /* FIELD_IS_NUMERIC */
			val = read_size(event, data + field->offset,
					field->size);
			if (field->flags & FIELD_IS_SIGNED) {
				if ((long long)val >= LONG_MIN &&
				    (long long)val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromLongLong(val);
			} else {
				if (val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromUnsignedLongLong(val);
			}
		}
		if (handler)
			PyTuple_SetItem(t, n++, obj);
		else
			pydict_set_item_string_decref(dict, field->name, obj);

	}
	if (!handler)
		PyTuple_SetItem(t, n++, dict);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	if (handler) {
		retval = PyObject_CallObject(handler, t);
		if (retval == NULL)
			handler_call_die(handler_name);
	} else {
		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
		if (handler && PyCallable_Check(handler)) {

			retval = PyObject_CallObject(handler, t);
			if (retval == NULL)
				handler_call_die("trace_unhandled");
		}
		Py_DECREF(dict);
	}

	Py_DECREF(t);
}
Exemple #8
0
static PyObject *
UDP_func_send(UDP *self, PyObject *args)
{
    int r, dest_port, address_type;
    char *dest_ip;
    uv_buf_t buf;
    Py_buffer pbuf;
    PyObject *callback;
    uv_udp_send_t *wr = NULL;
    udp_send_data_t *req_data = NULL;

    callback = Py_None;

    RAISE_IF_HANDLE_CLOSED(self, PyExc_HandleClosedError, NULL);

    if (!PyArg_ParseTuple(args, "(si)s*|O:send", &dest_ip, &dest_port, &pbuf, &callback)) {
        return NULL;
    }

    if (callback != Py_None && !PyCallable_Check(callback)) {
        PyBuffer_Release(&pbuf);
        PyErr_SetString(PyExc_TypeError, "a callable or None is required");
        return NULL;
    }

    if (dest_port < 0 || dest_port > 65535) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65535");
        return NULL;
    }

    if (pyuv_guess_ip_family(dest_ip, &address_type)) {
        PyErr_SetString(PyExc_ValueError, "invalid IP address");
        return NULL;
    }

    Py_INCREF(callback);

    wr = (uv_udp_send_t *)PyMem_Malloc(sizeof(uv_udp_send_t));
    if (!wr) {
        PyErr_NoMemory();
        goto error;
    }

    req_data = (udp_send_data_t*) PyMem_Malloc(sizeof(udp_send_data_t));
    if (!req_data) {
        PyErr_NoMemory();
        goto error;
    }

    buf = uv_buf_init(pbuf.buf, pbuf.len);
    req_data->callback = callback;
    req_data->buf_count = 1;
    req_data->data.view = pbuf;

    wr->data = (void *)req_data;

    if (address_type == AF_INET) {
        r = uv_udp_send(wr, (uv_udp_t *)UV_HANDLE(self), &buf, 1, uv_ip4_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
    } else {
        r = uv_udp_send6(wr, (uv_udp_t *)UV_HANDLE(self), &buf, 1, uv_ip6_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
    }
    if (r != 0) {
        RAISE_UV_EXCEPTION(UV_HANDLE_LOOP(self), PyExc_UDPError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    PyBuffer_Release(&pbuf);
    Py_DECREF(callback);
    if (req_data) {
        PyMem_Free(req_data);
    }
    if (wr) {
        PyMem_Free(wr);
    }
    return NULL;
}
Exemple #9
0
 virtual void load(const gcore::Path &path, lwc::Registry *reg) {
   
   std::string modulename = path.basename();
   modulename = modulename.substr(0, modulename.length()-3);
   
   gcore::Path dirname = path;
   dirname.pop();
   dirname.makeAbsolute().normalize();
   
   addToSysPath(dirname);
   
   PyObject *pymodname;
   pymodname = PyString_FromString(modulename.c_str());
   PyObject *mod = PyImport_Import(pymodname);
   Py_DECREF(pymodname);
   
   if (!mod) {
     std::cout << "pyloader: Could not load python module" << std::endl;
     PyErr_Print();
     return;
   }
   
   PyObject *getCountFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeCount");
   if (!getCountFunc || !PyCallable_Check(getCountFunc)) {
     if (getCountFunc) {
       Py_DECREF(getCountFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *getNameFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeName");
   if (!getNameFunc || !PyCallable_Check(getNameFunc)) {
     Py_DECREF(getCountFunc);
     if (getNameFunc) {
       Py_DECREF(getNameFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *getClassFunc = PyObject_GetAttrString(mod, "LWC_ModuleGetTypeClass");
   if (!getClassFunc || !PyCallable_Check(getClassFunc)) {
     Py_DECREF(getCountFunc);
     Py_DECREF(getNameFunc);
     if (getClassFunc) {
       Py_DECREF(getClassFunc);
     }
     Py_DECREF(mod);
     return;
   }
   
   PyObject *count = PyObject_CallObject(getCountFunc, NULL);
   long n = PyInt_AsLong(count);
   Py_DECREF(count);
   
   PyObject *args = PyTuple_New(1);
   
   for (long i=0; i<n; ++i) {
     // will this DECREF the old index?
     PyTuple_SetItem(args, 0, PyInt_FromLong(i));
     
     PyObject *pname = PyObject_CallObject(getNameFunc, args);
     PyObject *klass = PyObject_CallObject(getClassFunc, args);
     
     if (!klass) {
       std::cout << "pyloader: No class object for type" << std::endl;
       continue;
     }
     
     char *tn = PyString_AsString(pname);
     
     if (!reg->hasType(tn)) {
       if (mFactory->addType(tn, klass)) {
         registerType(tn, mFactory, reg);
       } else {
         std::cout << "pyloader: Invalid type \"" << tn << "\"" << std::endl;
       }
     } else {
       std::cout << "pyloader: Type \"" << tn << "\" already registered" << std::endl;
     }
     
     Py_DECREF(pname);
     Py_DECREF(klass);
   }
   
   Py_DECREF(args);
   Py_DECREF(getCountFunc);
   Py_DECREF(getNameFunc);
   Py_DECREF(getClassFunc);
   
   mPyModules.push_back(mod);
 }
PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args)
{
	void *handle;
	PyObject *cls;
	PyObject *cb_func, *cb_args;
	const char *cb_regiontype_str;
	const char *cb_event_str;
	int cb_event;
	int cb_regiontype;
	StructRNA *srna;

	if (PyTuple_GET_SIZE(args) < 2) {
		PyErr_SetString(PyExc_ValueError, "handler_add(handle): expected at least 2 args");
		return NULL;
	}

	cls = PyTuple_GET_ITEM(args, 0);
	if (!(srna = pyrna_struct_as_srna(cls, false, "handler_add"))) {
		return NULL;
	}
	cb_func = PyTuple_GET_ITEM(args, 1);
	if (!PyCallable_Check(cb_func)) {
		PyErr_SetString(PyExc_TypeError, "first argument isn't callable");
		return NULL;
	}

	/* class specific callbacks */
	if (RNA_struct_is_a(srna, &RNA_Space)) {
		if (!PyArg_ParseTuple(args, "OOO!ss:Space.draw_handler_add",
		                      &cls, &cb_func,  /* already assigned, no matter */
		                      &PyTuple_Type, &cb_args, &cb_regiontype_str, &cb_event_str))
		{
			return NULL;
		}

		if (pyrna_enum_value_from_id(region_draw_mode_items, cb_event_str, &cb_event, "bpy_struct.callback_add()") == -1) {
			return NULL;
		}
		else if (pyrna_enum_value_from_id(region_type_items, cb_regiontype_str, &cb_regiontype, "bpy_struct.callback_add()") == -1) {
			return NULL;
		}
		else {
			const eSpace_Type spaceid = rna_Space_refine_reverse(srna);
			if (spaceid == SPACE_EMPTY) {
				PyErr_Format(PyExc_TypeError, "unknown space type '%.200s'", RNA_struct_identifier(srna));
				return NULL;
			}
			else {
				SpaceType *st = BKE_spacetype_from_id(spaceid);
				ARegionType *art = BKE_regiontype_from_id(st, cb_regiontype);

				handle = ED_region_draw_cb_activate(art, cb_region_draw, (void *)args, cb_event);
				Py_INCREF(args);
			}
		}
	}
	else {
		PyErr_SetString(PyExc_TypeError, "callback_add(): type does not support callbacks");
		return NULL;
	}

	return PyCapsule_New((void *)handle, RNA_CAPSULE_ID, NULL);
}
Exemple #11
0
static int mod_init(void)
{
    char *dname_src, *bname_src;

    int i;
    PyObject *sys_path, *pDir, *pModule, *pFunc, *pArgs;
    PyThreadState *mainThreadState;

    if (script_name.len == 0) {
        script_name.len = strlen(script_name.s);
    }
    if (mod_init_fname.len == 0) {
        mod_init_fname.len = strlen(mod_init_fname.s);
    }
    if (child_init_mname.len == 0) {
        child_init_mname.len = strlen(child_init_mname.s);
    }

    dname_src = as_asciiz(&script_name);
    bname_src = as_asciiz(&script_name);

    if(dname_src==NULL || bname_src==NULL)
    {
        LM_ERR("no more pkg memory\n");
        return -1;
    }

    dname = strdup(dirname(dname_src));
    if (strlen(dname) == 0)
        dname = ".";
    bname = strdup(basename(bname_src));
    i = strlen(bname);
    if (bname[i - 1] == 'c' || bname[i - 1] == 'o')
        i -= 1;
    if (bname[i - 3] == '.' && bname[i - 2] == 'p' && bname[i - 1] == 'y') {
        bname[i - 3] = '\0';
    } else {
        LM_ERR("%s: script_name doesn't look like a python script\n",
          script_name.s);
        return -1;
    }

    Py_Initialize();
    PyEval_InitThreads();
    mainThreadState = PyThreadState_Get();

    format_exc_obj = InitTracebackModule();

    if (format_exc_obj == NULL || !PyCallable_Check(format_exc_obj))
    {
        Py_XDECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    sys_path = PySys_GetObject("path");
    /* PySys_GetObject doesn't pass reference! No need to DEREF */
    if (sys_path == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "'module' object 'sys' has no attribute 'path'");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pDir = PyString_FromString(dname);
    if (pDir == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "PyString_FromString() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    PyList_Insert(sys_path, 0, pDir);
    Py_DECREF(pDir);

    if (init_modules() != 0) {
	if (!PyErr_Occurred())
	    PyErr_SetString(PyExc_AttributeError, "init_modules() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (python_msgobj_init() != 0) {
	if (!PyErr_Occurred())
	    PyErr_SetString(PyExc_AttributeError, "python_msgobj_init() has failed");
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pModule = PyImport_ImportModule(bname);
    if (pModule == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_ImportError, "No module named '%s'", bname);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    pkg_free(dname_src);
    pkg_free(bname_src);

    pFunc = PyObject_GetAttrString(pModule, mod_init_fname.s);
    Py_DECREF(pModule);

    /* pFunc is a new reference */

    if (pFunc == NULL) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "'module' object '%s' has no attribute '%s'",  bname, mod_init_fname.s);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        Py_XDECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }

    if (!PyCallable_Check(pFunc)) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "module object '%s' has is not callable attribute '%s'", bname, mod_init_fname.s);
	python_handle_exception("mod_init");
	Py_DECREF(format_exc_obj);
        Py_XDECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }


    pArgs = PyTuple_New(0);
    if (pArgs == NULL) {
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        Py_DECREF(pFunc);
        PyEval_ReleaseLock();
        return -1;
    }

    handler_obj = PyObject_CallObject(pFunc, pArgs);

    Py_XDECREF(pFunc);
    Py_XDECREF(pArgs);

    if (handler_obj == Py_None) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned None. Should be a class instance.", mod_init_fname.s, bname);
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (PyErr_Occurred()) {
        python_handle_exception("mod_init");
        Py_XDECREF(handler_obj);
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    if (handler_obj == NULL) {
        LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_TypeError, "Function '%s' of module '%s' has returned not returned object. Should be a class instance.", mod_init_fname.s, bname);
	python_handle_exception("mod_init");
        Py_DECREF(format_exc_obj);
        PyEval_ReleaseLock();
        return -1;
    }

    myThreadState = PyThreadState_New(mainThreadState->interp);
    PyEval_ReleaseLock();

    return 0;
}
Exemple #12
0
static int child_init(int rank)
{
    PyObject *pFunc, *pArgs, *pValue, *pResult;
    int rval;
    char *classname;

    PyEval_AcquireLock();
    PyThreadState_Swap(myThreadState);

    // get instance class name
    classname = get_instance_class_name(handler_obj);
    if (classname == NULL)
    {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "'module' instance has no class name");
	python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
	Py_XDECREF(classname);
	PyThreadState_Swap(NULL);
	PyEval_ReleaseLock();
	return -1;
    }

    pFunc = PyObject_GetAttrString(handler_obj, child_init_mname.s);

    if (pFunc == NULL) {
	python_handle_exception("child_init");
	Py_XDECREF(pFunc);
	Py_DECREF(format_exc_obj);
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }

    if (!PyCallable_Check(pFunc)) {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_AttributeError, "class object '%s' has is not callable attribute '%s'", !classname ? "None" : classname, mod_init_fname.s);
	python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
	Py_XDECREF(classname);
	Py_XDECREF(pFunc);
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }

    pArgs = PyTuple_New(1);
    if (pArgs == NULL) {
	python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
	Py_XDECREF(classname);
        Py_DECREF(pFunc);
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }

    pValue = PyInt_FromLong((long)rank);
    if (pValue == NULL) {
	python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
        Py_DECREF(pArgs);
        Py_DECREF(pFunc);
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }
    PyTuple_SetItem(pArgs, 0, pValue);
    /* pValue has been stolen */

    pResult = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pFunc);
    Py_DECREF(pArgs);

    


    if (PyErr_Occurred()) {
        python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
        Py_XDECREF(pResult);
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }

    if (pResult == NULL) {
        LM_ERR("PyObject_CallObject() returned NULL but no exception!\n");
        PyThreadState_Swap(NULL);
        PyEval_ReleaseLock();
        return -1;
    }

    if (!PyInt_Check(pResult))
    {
	if (!PyErr_Occurred())
	    PyErr_Format(PyExc_TypeError, "method '%s' of class '%s' should return 'int' type", child_init_mname.s, !classname ? "None" : classname);
	python_handle_exception("child_init");
	Py_DECREF(format_exc_obj);
	Py_XDECREF(pResult);
	Py_XDECREF(classname);
	PyThreadState_Swap(NULL);
	PyEval_ReleaseLock();
	return -1;
    }


    rval = PyInt_AsLong(pResult);
    Py_DECREF(pResult);
    Py_XDECREF(classname);
    PyThreadState_Swap(NULL);
    PyEval_ReleaseLock();

    return rval;
}
Exemple #13
0
static gboolean
_pygi_marshal_from_py_interface_callback (PyGIInvokeState   *state,
                                          PyGICallableCache *callable_cache,
                                          PyGIArgCache      *arg_cache,
                                          PyObject          *py_arg,
                                          GIArgument        *arg,
                                          gpointer          *cleanup_data)
{
    GICallableInfo *callable_info;
    PyGICClosure *closure;
    PyGIArgCache *user_data_cache = NULL;
    PyGIArgCache *destroy_cache = NULL;
    PyGICallbackCache *callback_cache;
    PyObject *py_user_data = NULL;

    callback_cache = (PyGICallbackCache *)arg_cache;

    if (callback_cache->user_data_index > 0) {
        user_data_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->user_data_index);
        if (user_data_cache->py_arg_index < state->n_py_in_args) {
            /* py_user_data is a borrowed reference. */
            py_user_data = PyTuple_GetItem (state->py_in_args, user_data_cache->py_arg_index);
            if (!py_user_data)
                return FALSE;
            /* NULL out user_data if it was not supplied and the default arg placeholder
             * was used instead.
             */
            if (py_user_data == _PyGIDefaultArgPlaceholder) {
                py_user_data = NULL;
            } else if (callable_cache->user_data_varargs_index < 0) {
                /* For non-variable length user data, place the user data in a
                 * single item tuple which is concatenated to the callbacks arguments.
                 * This allows callback input arg marshaling to always expect a
                 * tuple for user data. Note the
                 */
                py_user_data = Py_BuildValue("(O)", py_user_data, NULL);
            } else {
                /* increment the ref borrowed from PyTuple_GetItem above */
                Py_INCREF (py_user_data);
            }
        }
    }

    if (py_arg == Py_None) {
        return TRUE;
    }

    if (!PyCallable_Check (py_arg)) {
        PyErr_Format (PyExc_TypeError,
                      "Callback needs to be a function or method not %s",
                      py_arg->ob_type->tp_name);

        return FALSE;
    }

    callable_info = (GICallableInfo *)callback_cache->interface_info;

    closure = _pygi_make_native_closure (callable_info, callback_cache->scope, py_arg, py_user_data);
    arg->v_pointer = closure->closure;

    /* always decref the user data as _pygi_make_native_closure adds its own ref */
    Py_XDECREF (py_user_data);

    /* The PyGICClosure instance is used as user data passed into the C function.
     * The return trip to python will marshal this back and pull the python user data out.
     */
    if (user_data_cache != NULL) {
        state->args[user_data_cache->c_arg_index].arg_value.v_pointer = closure;
    }

    /* Setup a GDestroyNotify callback if this method supports it along with
     * a user data field. The user data field is a requirement in order
     * free resources and ref counts associated with this arguments closure.
     * In case a user data field is not available, show a warning giving
     * explicit information and setup a dummy notification to avoid a crash
     * later on in _pygi_destroy_notify_callback_closure.
     */
    if (callback_cache->destroy_notify_index > 0) {
        destroy_cache = _pygi_callable_cache_get_arg (callable_cache, callback_cache->destroy_notify_index);
    }

    if (destroy_cache) {
        if (user_data_cache != NULL) {
            state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_invoke_closure_free;
        } else {
            char *full_name = pygi_callable_cache_get_full_name (callable_cache);
            gchar *msg = g_strdup_printf("Callables passed to %s will leak references because "
                                         "the method does not support a user_data argument. "
                                         "See: https://bugzilla.gnome.org/show_bug.cgi?id=685598",
                                         full_name);
            g_free (full_name);
            if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 2)) {
                g_free(msg);
                _pygi_invoke_closure_free(closure);
                return FALSE;
            }
            g_free(msg);
            state->args[destroy_cache->c_arg_index].arg_value.v_pointer = _pygi_destroy_notify_dummy;
        }
    }

    /* Use the PyGIClosure as data passed to cleanup for GI_SCOPE_TYPE_CALL. */
    *cleanup_data = closure;

    return TRUE;
}
Exemple #14
0
int main(int argc, char *argv[])
{
    Py_Initialize();  
    if(!Py_IsInitialized())   
    {  
        return -1;  
    }  
    
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject* pName;
    PyObject* pModule;
    PyObject* pDict;
    PyObject* pFunc;
    
    pName = PyString_FromString("call");
    pModule = PyImport_Import(pName);
    if(!pModule)
    {
        printf("can't find call.py");
        getchar();
        return -1;
    }
    
    pDict = PyModule_GetDict(pModule);
    if(!pDict)
    {
        return -1;
    }
    
    {
        pFunc = PyDict_GetItemString(pDict,"test");
        if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf("can't find function [test]");
            getchar();
            return -1;
        }
        
        PyObject_CallObject(pFunc,0);
    }
    
    {
        pFunc = PyDict_GetItemString(pDict,"add");
        if(!pFunc || !PyCallable_Check(pFunc))
        {
            printf("can't find function [test]");
            getchar();
            return -1;
        }
        
        PyObject* args = PyTuple_New(2);
        PyTuple_SetItem(args,0,Py_BuildValue("l",3));
        PyTuple_SetItem(args,1,Py_BuildValue("l",4));
        PyObject *pAdded = PyObject_CallObject(pFunc,args);
        int ret = PyInt_AsLong(pAdded);  
        printf("add value:%d\n",ret);
        Py_DECREF(args);
    }    
    
    Py_DECREF(pName);
    Py_DECREF(pDict);
    Py_DECREF(pModule);
    Py_Finalize();    
    system("PAUSE");
    return 0;
}
Exemple #15
0
static PyObject *
Channel_func_query(Channel *self, PyObject *args)
{
    char *name;
    int query_type;
    PyObject *callback, *ret;

    CHECK_CHANNEL(self);

    if (!PyArg_ParseTuple(args, "etiO:query", "idna", &name, &query_type, &callback)) {
        return NULL;
    }

    if (!PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable is required");
        ret = NULL;
        goto finally;
    }

    Py_INCREF(callback);

    switch (query_type) {
        case T_A:
        {
            ares_query(self->channel, name, C_IN, T_A, &query_a_cb, (void *)callback);
            break;
        }

        case T_AAAA:
        {
            ares_query(self->channel, name, C_IN, T_AAAA, &query_aaaa_cb, (void *)callback);
            break;
        }

        case T_CNAME:
        {
            ares_query(self->channel, name, C_IN, T_CNAME, &query_cname_cb, (void *)callback);
            break;
        }

        case T_MX:
        {
            ares_query(self->channel, name, C_IN, T_MX, &query_mx_cb, (void *)callback);
            break;
        }

        case T_NAPTR:
        {
            ares_query(self->channel, name, C_IN, T_NAPTR, &query_naptr_cb, (void *)callback);
            break;
        }

        case T_NS:
        {
            ares_query(self->channel, name, C_IN, T_NS, &query_ns_cb, (void *)callback);
            break;
        }

        case T_PTR:
        {
            ares_query(self->channel, name, C_IN, T_PTR, &query_ptr_cb, (void *)callback);
            break;
        }

        case T_SOA:
        {
            ares_query(self->channel, name, C_IN, T_SOA, &query_soa_cb, (void *)callback);
            break;
        }

        case T_SRV:
        {
            ares_query(self->channel, name, C_IN, T_SRV, &query_srv_cb, (void *)callback);
            break;
        }

        case T_TXT:
        {
            ares_query(self->channel, name, C_IN, T_TXT, &query_txt_cb, (void *)callback);
            break;
        }

        default:
        {
            Py_DECREF(callback);
            PyErr_SetString(PyExc_ValueError, "invalid query type specified");
            ret = NULL;
            goto finally;
        }
    }
    ret = Py_None;

finally:
    PyMem_Free(name);
    Py_XINCREF(ret);
    return ret;
}
Exemple #16
0
// this code is heavily adapted from the paint license, which is in
// the file paint.license (BSD compatible) included in this
// distribution.  TODO, add license file to MANIFEST.in and CVS
Py::Object _png_module::write_png(const Py::Tuple& args)
{
    args.verify_length(4, 5);

    FILE *fp = NULL;
    bool close_file = false;
    bool close_dup_file = false;
    Py::Object buffer_obj = Py::Object(args[0]);
    PyObject* buffer = buffer_obj.ptr();
    if (!PyObject_CheckReadBuffer(buffer))
    {
        throw Py::TypeError("First argument must be an rgba buffer.");
    }

    const void* pixBufferPtr = NULL;
    Py_ssize_t pixBufferLength = 0;
    if (PyObject_AsReadBuffer(buffer, &pixBufferPtr, &pixBufferLength))
    {
        throw Py::ValueError("Couldn't get data from read buffer.");
    }

    png_byte* pixBuffer = (png_byte*)pixBufferPtr;
    int width = (int)Py::Int(args[1]);
    int height = (int)Py::Int(args[2]);

    if (pixBufferLength < width * height * 4)
    {
        throw Py::ValueError("Buffer and width, height don't seem to match.");
    }

    Py::Object py_fileobj = Py::Object(args[3]);
    PyObject* py_file = NULL;
    if (py_fileobj.isString())
    {
        if ((py_file = npy_PyFile_OpenFile(py_fileobj.ptr(), (char *)"wb")) == NULL) {
            throw Py::Exception();
        }
        close_file = true;
    }
    else
    {
        py_file = py_fileobj.ptr();
    }

    if ((fp = npy_PyFile_Dup(py_file, (char *)"wb")))
    {
        close_dup_file = true;
    }
    else
    {
        PyErr_Clear();
        PyObject* write_method = PyObject_GetAttrString(
                                     py_file, "write");
        if (!(write_method && PyCallable_Check(write_method)))
        {
            Py_XDECREF(write_method);
            throw Py::TypeError(
                "Object does not appear to be a 8-bit string path or "
                "a Python file-like object");
        }
        Py_XDECREF(write_method);
    }

    png_bytep *row_pointers = NULL;
    png_structp png_ptr = NULL;
    png_infop info_ptr = NULL;

    try
    {
        struct png_color_8_struct sig_bit;
        png_uint_32 row;

        row_pointers = new png_bytep[height];
        for (row = 0; row < (png_uint_32)height; ++row)
        {
            row_pointers[row] = pixBuffer + row * width * 4;
        }

        png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
        if (png_ptr == NULL)
        {
            throw Py::RuntimeError("Could not create write struct");
        }

        info_ptr = png_create_info_struct(png_ptr);
        if (info_ptr == NULL)
        {
            throw Py::RuntimeError("Could not create info struct");
        }

        if (setjmp(png_jmpbuf(png_ptr)))
        {
            throw Py::RuntimeError("Error building image");
        }

        if (fp)
        {
            png_init_io(png_ptr, fp);
        }
        else
        {
            png_set_write_fn(png_ptr, (void*)py_file,
                             &write_png_data, &flush_png_data);
        }
        png_set_IHDR(png_ptr, info_ptr,
                     width, height, 8,
                     PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
                     PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

        // Save the dpi of the image in the file
        if (args.size() == 5)
        {
            double dpi = Py::Float(args[4]);
            size_t dots_per_meter = (size_t)(dpi / (2.54 / 100.0));
            png_set_pHYs(png_ptr, info_ptr, dots_per_meter, dots_per_meter, PNG_RESOLUTION_METER);
        }

        // this a a color image!
        sig_bit.gray = 0;
        sig_bit.red = 8;
        sig_bit.green = 8;
        sig_bit.blue = 8;
        /* if the image has an alpha channel then */
        sig_bit.alpha = 8;
        png_set_sBIT(png_ptr, info_ptr, &sig_bit);

        png_write_info(png_ptr, info_ptr);
        png_write_image(png_ptr, row_pointers);
        png_write_end(png_ptr, info_ptr);
    }
    catch (...)
    {
        if (png_ptr && info_ptr)
        {
            png_destroy_write_struct(&png_ptr, &info_ptr);
        }
        delete [] row_pointers;

        if (close_dup_file)
        {
            if (npy_PyFile_DupClose(py_file, fp)) {
                throw Py::RuntimeError("Error closing dupe file handle");
            }
        }

        if (close_file)
        {
            npy_PyFile_CloseFile(py_file);
            Py_DECREF(py_file);
        }
        /* Changed calls to png_destroy_write_struct to follow
           http://www.libpng.org/pub/png/libpng-manual.txt.
           This ensures the info_ptr memory is released.
        */
        throw;
    }

    png_destroy_write_struct(&png_ptr, &info_ptr);
    delete [] row_pointers;
    if (close_dup_file)
    {
        if (npy_PyFile_DupClose(py_file, fp)) {
            throw Py::RuntimeError("Error closing dupe file handle");
        }
    }

    if (close_file)
    {
        npy_PyFile_CloseFile(py_file);
        Py_DECREF(py_file);
    }

    if (PyErr_Occurred()) {
        throw Py::Exception();
    } else {
        return Py::Object();
    }
}
Exemple #17
0
PyObject*
_png_module::_read_png(const Py::Object& py_fileobj, const bool float_result,
                       int result_bit_depth)
{
    png_byte header[8];   // 8 is the maximum size that can be checked
    FILE* fp = NULL;
    bool close_file = false;
    bool close_dup_file = false;
    PyObject *py_file = NULL;

    if (py_fileobj.isString())
    {
        if ((py_file = npy_PyFile_OpenFile(py_fileobj.ptr(), (char *)"rb")) == NULL) {
            throw Py::Exception();
        }
        close_file = true;
    } else {
        py_file = py_fileobj.ptr();
    }

    if ((fp = npy_PyFile_Dup(py_file, "rb")))
    {
        close_dup_file = true;
    }
    else
    {
        PyErr_Clear();
        PyObject* read_method = PyObject_GetAttrString(py_file, "read");
        if (!(read_method && PyCallable_Check(read_method)))
        {
            Py_XDECREF(read_method);
            throw Py::TypeError(
                "Object does not appear to be a 8-bit string path or a Python "
                "file-like object");
        }
        Py_XDECREF(read_method);
    }

    if (fp)
    {
        if (fread(header, 1, 8, fp) != 8)
        {
            throw Py::RuntimeError(
                "_image_module::readpng: error reading PNG header");
        }
    }
    else
    {
        _read_png_data(py_file, header, 8);
    }
    if (png_sig_cmp(header, 0, 8))
    {
        throw Py::RuntimeError(
            "_image_module::readpng: file not recognized as a PNG file");
    }

    /* initialize stuff */
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);

    if (!png_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_read_struct failed");
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);
    if (!info_ptr)
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  png_create_info_struct failed");
    }

    if (setjmp(png_jmpbuf(png_ptr)))
    {
        throw Py::RuntimeError(
            "_image_module::readpng:  error during init_io");
    }

    if (fp)
    {
        png_init_io(png_ptr, fp);
    }
    else
    {
        png_set_read_fn(png_ptr, (void*)py_file, &read_png_data);
    }
    png_set_sig_bytes(png_ptr, 8);
    png_read_info(png_ptr, info_ptr);

    png_uint_32 width = png_get_image_width(png_ptr, info_ptr);
    png_uint_32 height = png_get_image_height(png_ptr, info_ptr);

    int bit_depth = png_get_bit_depth(png_ptr, info_ptr);

    // Unpack 1, 2, and 4-bit images
    if (bit_depth < 8)
        png_set_packing(png_ptr);

    // If sig bits are set, shift data
    png_color_8p sig_bit;
    if ((png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_PALETTE) &&
            png_get_sBIT(png_ptr, info_ptr, &sig_bit))
    {
        png_set_shift(png_ptr, sig_bit);
    }

    // Convert big endian to little
    if (bit_depth == 16)
    {
        png_set_swap(png_ptr);
    }

    // Convert palletes to full RGB
    if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(png_ptr);
        bit_depth = 8;
    }

    // If there's an alpha channel convert gray to RGB
    if (png_get_color_type(png_ptr, info_ptr) == PNG_COLOR_TYPE_GRAY_ALPHA)
    {
        png_set_gray_to_rgb(png_ptr);
    }

    png_set_interlace_handling(png_ptr);
    png_read_update_info(png_ptr, info_ptr);

    /* read file */
    if (setjmp(png_jmpbuf(png_ptr)))
    {
        throw Py::RuntimeError(
            "_image_module::readpng: error during read_image");
    }

    png_bytep *row_pointers = new png_bytep[height];
    png_uint_32 row;

    for (row = 0; row < height; row++)
    {
        row_pointers[row] = new png_byte[png_get_rowbytes(png_ptr,info_ptr)];
    }

    png_read_image(png_ptr, row_pointers);

    npy_intp dimensions[3];
    dimensions[0] = height;  //numrows
    dimensions[1] = width;   //numcols
    if (png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_ALPHA)
    {
        dimensions[2] = 4;     //RGBA images
    }
    else if (png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_COLOR)
    {
        dimensions[2] = 3;     //RGB images
    }
    else
    {
        dimensions[2] = 1;     //Greyscale images
    }
    //For gray, return an x by y array, not an x by y by 1
    int num_dims  = (png_get_color_type(png_ptr, info_ptr)
                     & PNG_COLOR_MASK_COLOR) ? 3 : 2;

    PyArrayObject *A = NULL;
    if (float_result) {
        double max_value = (1 << bit_depth) - 1;

        A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_FLOAT);

        if (A == NULL)
        {
            throw Py::MemoryError("Could not allocate image array");
        }

        for (png_uint_32 y = 0; y < height; y++)
        {
            png_byte* row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++)
            {
                size_t offset = y * A->strides[0] + x * A->strides[1];
                if (bit_depth == 16)
                {
                    png_uint_16* ptr = &reinterpret_cast<png_uint_16*>(row)[x * dimensions[2]];
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
                    }
                }
                else
                {
                    png_byte* ptr = &(row[x * dimensions[2]]);
                    for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                    {
                        *(float*)(A->data + offset + p*A->strides[2]) = (float)(ptr[p]) / max_value;
                    }
                }
            }
        }
    } else {
        if (result_bit_depth < 0) {
            result_bit_depth = bit_depth;
        }

        if (result_bit_depth == 8) {
            A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_UBYTE);
        } else if (result_bit_depth == 16) {
            A = (PyArrayObject *) PyArray_SimpleNew(num_dims, dimensions, NPY_UINT16);
        } else {
            throw Py::RuntimeError(
                "_image_module::readpng: image has unknown bit depth");
        }

        if (A == NULL)
        {
            throw Py::MemoryError("Could not allocate image array");
        }

        for (png_uint_32 y = 0; y < height; y++)
        {
            png_byte* row = row_pointers[y];
            for (png_uint_32 x = 0; x < width; x++)
            {
                size_t offset = y * A->strides[0] + x * A->strides[1];
                if (bit_depth == 16)
                {
                    png_uint_16* ptr = &reinterpret_cast<png_uint_16*>(row)[x * dimensions[2]];

                    if (result_bit_depth == 16) {
                        for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                        {
                            *(png_uint_16*)(A->data + offset + p*A->strides[2]) = ptr[p];
                        }
                    } else {
                        for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                        {
                            *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p] >> 8;
                        }
                    }
                }
                else
                {
                    png_byte* ptr = &(row[x * dimensions[2]]);
                    if (result_bit_depth == 16) {
                        for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                        {
                            *(png_uint_16*)(A->data + offset + p*A->strides[2]) = ptr[p];
                        }
                    } else {
                        for (png_uint_32 p = 0; p < (png_uint_32)dimensions[2]; p++)
                        {
                            *(png_byte*)(A->data + offset + p*A->strides[2]) = ptr[p];
                        }
                    }
                }
            }
        }
Exemple #18
0
void PythonTransform::transform(const QByteArray &input, QByteArray &output)
{
    if (input.isEmpty())
        return;

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();
    if (loadModule()) {
        PyObject * pyInbound = Py_False; // need reference count management

        if (twoWays)
            pyInbound = (wayValue == INBOUND ? Py_True : Py_False );
        Py_INCREF(pyInbound);

        if (PyModule_AddObject(pModule, INBOUND_ATTR_NAME, pyInbound) == -1) { // steal reference
            pythonmgm->checkPyError();
            logError(tr("T_T Could not set the direction value properly:\n%1").arg(pythonmgm->getLastError()),id);
            Py_XDECREF(pyInbound);
        }

        // setting parameters in the python environment
        if (!parameters.isEmpty()) {
            PyObject *paramsdict = PyDict_New();
            if (!pythonmgm->checkPyError()) {
                logError(tr("T_T Error while creating the Python parameter dict:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(paramsdict);
                PyGILState_Release(lgstate);
                return;
            }
            // adding parameters to the python list
            QHashIterator<QByteArray, QByteArray> i(parameters);
            while (i.hasNext()) {
                i.next();
                PyObject* paramKey = PyUnicode_FromStringAndSize(i.key(),i.key().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter key:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    PyGILState_Release(lgstate);
                    return;
                }

                PyObject* paramValue = PyUnicode_FromStringAndSize(i.value(),i.value().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter value:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    PyGILState_Release(lgstate);
                    return;
                }

                if (PyDict_SetItem(paramsdict,paramKey,paramValue) == -1) { // stealing reference
                    pythonmgm->checkPyError(); // we already know there was an error
                    logError(tr("T_T Error while setting Python parameter pair:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    Py_XDECREF(paramValue);
                    PyGILState_Release(lgstate);
                    return;
                }

                // Cleaning the values (references not stolen)
                Py_XDECREF(paramKey);
                Py_XDECREF(paramValue);
            }

            if (PyModule_AddObject(pModule,PARAMS_ATTR_NAME , paramsdict) == -1) { // stolen paramsdict reference
                pythonmgm->checkPyError();
                logError(tr("T_T Could not set the Pip3line_params value properly:\n%1").arg(pythonmgm->getLastError()),id);
            }


        } else {
            Py_INCREF(Py_None);
            if (PyModule_AddObject(pModule,PARAMS_ATTR_NAME , Py_None) == -1) { // stealing reference
                pythonmgm->checkPyError();
                logError(tr("T_T Could not set the Pip3line_params None value properly:\n%1").arg(pythonmgm->getLastError()),id);
                Py_DECREF(Py_None);
            }
        }

        PyObject * pFunc = PyObject_GetAttrString(pModule, MAIN_FUNCTION_NAME);

        if (pythonmgm->checkPyError() && PyCallable_Check(pFunc)) {
            PyObject* pArgs = PyTuple_New(1);

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python argument tuple:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }

            PyObject* inputPy = PyByteArray_FromStringAndSize(input.data(),input.size());
            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                Py_XDECREF(inputPy);
                PyGILState_Release(lgstate);
                return;
            }

            if (PyTuple_SetItem(pArgs, 0, inputPy) != 0) {// stealing the reference of inputPy
                pythonmgm->checkPyError();
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(inputPy);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }
            PyObject* returnValue = PyObject_CallObject(pFunc, pArgs); // new ref or NULL

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Python error while executing the function:\n %1").arg(pythonmgm->getLastError()), id);
            } else {
                if (PyByteArray_Check(returnValue)) {

                    Py_ssize_t templength = PyByteArray_Size(returnValue);
                    if (templength > BLOCK_MAX_SIZE) {
                        templength = BLOCK_MAX_SIZE;
                        Q_EMIT warning(tr("Data block returned is too large, truncating."),id);
                    }

                    char * buffer = PyByteArray_AsString(returnValue); // never to be deleted
                    output.append(QByteArray(buffer,templength));
                } else {
                    Q_EMIT error(tr("The Python object returned is not a bytearray"), id);
                }
            }

            Py_XDECREF(returnValue);
            Py_XDECREF(pArgs);
          //  Py_DECREF(inputPy); // stolen reference, don't touch that
            Py_XDECREF(pFunc);

        } else {
            Q_EMIT error(tr("Python error while calling the function %1():\n%2").arg(MAIN_FUNCTION_NAME).arg(pythonmgm->getLastError()), id);
        }
    } else {
        qDebug() << "[Python transform] could not load the module";
    }

    PyGILState_Release(lgstate);
}
Exemple #19
0
static PyObject *
UDP_func_sendlines(UDP *self, PyObject *args)
{
    int i, r, buf_count, dest_port, address_type;
    char *dest_ip;
    PyObject *callback, *seq;
    uv_buf_t *bufs;
    uv_udp_send_t *wr = NULL;
    udp_send_data_t *req_data = NULL;

    callback = Py_None;

    RAISE_IF_HANDLE_CLOSED(self, PyExc_HandleClosedError, NULL);

    if (!PyArg_ParseTuple(args, "(si)O|O:sendlines", &dest_ip, &dest_port, &seq, &callback)) {
        return NULL;
    }

    if (callback != Py_None && !PyCallable_Check(callback)) {
        PyErr_SetString(PyExc_TypeError, "a callable or None is required");
        return NULL;
    }

    if (dest_port < 0 || dest_port > 65535) {
        PyErr_SetString(PyExc_ValueError, "port must be between 0 and 65535");
        return NULL;
    }

    if (pyuv_guess_ip_family(dest_ip, &address_type)) {
        PyErr_SetString(PyExc_ValueError, "invalid IP address");
        return NULL;
    }

    Py_INCREF(callback);

    r = pyseq2uvbuf(seq, &bufs, &buf_count);
    if (r != 0) {
        /* error is already set */
        goto error;
    }

    if (buf_count == 0) {
        PyErr_SetString(PyExc_ValueError, "Sequence is empty");
        goto error;
    }

    wr = (uv_udp_send_t *)PyMem_Malloc(sizeof(uv_udp_send_t));
    if (!wr) {
        PyErr_NoMemory();
        goto error;
    }

    req_data = (udp_send_data_t*) PyMem_Malloc(sizeof(udp_send_data_t));
    if (!req_data) {
        PyErr_NoMemory();
        goto error;
    }

    req_data->callback = callback;
    req_data->buf_count = buf_count;
    req_data->data.bufs = bufs;
    wr->data = (void *)req_data;

    if (address_type == AF_INET) {
        r = uv_udp_send(wr, (uv_udp_t *)UV_HANDLE(self), bufs, buf_count, uv_ip4_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
    } else {
        r = uv_udp_send6(wr, (uv_udp_t *)UV_HANDLE(self), bufs, buf_count, uv_ip6_addr(dest_ip, dest_port), (uv_udp_send_cb)on_udp_send);
    }
    if (r != 0) {
        RAISE_UV_EXCEPTION(UV_HANDLE_LOOP(self), PyExc_UDPError);
        goto error;
    }

    Py_RETURN_NONE;

error:
    Py_DECREF(callback);
    if (bufs) {
        for (i = 0; i < buf_count; i++) {
            PyMem_Free(bufs[i].base);
        }
        PyMem_Free(bufs);
    }
    if (req_data) {
        PyMem_Free(req_data);
    }
    if (wr) {
        PyMem_Free(wr);
    }
    return NULL;
}
Exemple #20
0
static PyObject *Polygon_sample(Polygon *self, PyObject *args) {
    PyObject *rng, *val1, *val2, *val3, *res;
    double A;
    if (! PyArg_ParseTuple(args, "O", &rng))
        return Polygon_Raise(ERR_ARG);
    if (!PyCallable_Check(rng))
        return Polygon_Raise(ERR_ARG);

    res = NULL;

    Py_INCREF(rng);
    // Sampling requires three random values
    val1 = val2 = val3 = NULL;
    val1 = PyObject_CallObject(rng, NULL);
    val2 = PyObject_CallObject(rng, NULL);
    val3 = PyObject_CallObject(rng, NULL);
    Py_DECREF(rng);

    if ((! PyFloat_Check(val1)) || (! PyFloat_Check(val2)) || (! PyFloat_Check(val3))) {
         Polygon_Raise(PolyError,
                       "rng returned something other than a float");
         goto cleanup;
    }
            
    A = poly_p_area(self->gpc_p);
    if (A == 0.0) {
      Polygon_Raise(PolyError,
                    "cannot sample from a zero-area polygon");
      goto cleanup;
    } else {
        gpc_tristrip *t = (gpc_tristrip *)alloca(sizeof(gpc_tristrip));
        gpc_vertex_list *vl;
        gpc_vertex_list one_tri;
        int i, j;
        gpc_vertex *tri_verts;
        double a, b, c, px, py;
      
        t->num_strips = 0;
        t->strip = NULL;
        gpc_polygon_to_tristrip(self->gpc_p, t);
        
        A *= PyFloat_AS_DOUBLE(val1);
        
        one_tri.num_vertices = 3;
        for (i=0; i < t->num_strips; i++) {
            vl = t->strip + i;
            for (j=0; j < vl->num_vertices - 2; j++) {
                one_tri.vertex = vl->vertex + j;
                A -= poly_c_area(& one_tri);
                if (A <= 0.0)
                    goto tri_found;
          }
        }
      tri_found:
        // sample a point from this triangle
        a = PyFloat_AS_DOUBLE(val2);
        b = PyFloat_AS_DOUBLE(val3);
        if ((a + b) > 1.0) {
            a = 1 - a;
            b = 1 - b;
        }
        c = 1 - a - b;
        tri_verts = one_tri.vertex;
        px = a * tri_verts[0].x + b * tri_verts[1].x + c * tri_verts[2].x;
        py = a * tri_verts[0].y + b * tri_verts[1].y + c * tri_verts[2].y;
        res = PyTuple_New(2);
        PyTuple_SetItem(res, 0, PyFloat_FromDouble(px));
        PyTuple_SetItem(res, 1, PyFloat_FromDouble(py));
        gpc_free_tristrip(t);
    }

  cleanup:
    Py_XDECREF(val1);
    Py_XDECREF(val2);
    Py_XDECREF(val3);
                
    return res;
}
void qpycore_qmetaobject_connectslotsbyname(QObject *qobj,
        PyObject *qobj_wrapper)
{
    // Get the class attributes.
    PyObject *dir = PyObject_Dir((PyObject *)Py_TYPE(qobj_wrapper));

    if (!dir)
        return;

    PyObject *slot_obj = 0;

    for (SIP_SSIZE_T li = 0; li < PyList_GET_SIZE(dir); ++li)
    {
        PyObject *name_obj = PyList_GET_ITEM(dir, li);

        // Get the slot object.
        Py_XDECREF(slot_obj);
        slot_obj = PyObject_GetAttr(qobj_wrapper, name_obj);

        if (!slot_obj)
            continue;

        // Ignore it if it is not a callable.
        if (!PyCallable_Check(slot_obj))
            continue;

        // Use the signature attribute instead of the name if there is one.
        PyObject *sigattr = PyObject_GetAttr(slot_obj,
                qpycore_dunder_pyqtsignature);

        if (sigattr)
        {
            for (SIP_SSIZE_T i = 0; i < PyList_GET_SIZE(sigattr); ++i)
            {
                PyObject *decoration = PyList_GET_ITEM(sigattr, i);
                Chimera::Signature *sig = Chimera::Signature::fromPyObject(decoration);
                QByteArray args = sig->arguments();

                if (!args.isEmpty())
                    connect(qobj, slot_obj, sig->name(), args);
            }

            Py_DECREF(sigattr);
        }
        else
        {
            const char *ascii_name = sipString_AsASCIIString(&name_obj);

            if (!ascii_name)
                continue;

            PyErr_Clear();

            connect(qobj, slot_obj, QByteArray(ascii_name), QByteArray());

            Py_DECREF(name_obj);
        }
    }

    Py_XDECREF(slot_obj);
    Py_DECREF(dir);
}
//=============================================================================
// METHOD: SPELLvariableMonitor::retrieveGlobalVariables()
//=============================================================================
void SPELLvariableMonitor::retrieveGlobalVariables(std::vector<SPELLvarInfo>& vars,
												   std::set<std::string> locals)
{
	DEBUG("[VM] Retrieve Globals");

	/*
	 * Once we get the bottom stack frame, we have to iterate over all the keys
	 * in the globals dictionary, and filter them agains the m_initialVariables
	 */
	PyObject* dict = m_frame->f_globals;
	PyObject* itemList = PyDict_Keys(dict);
	unsigned int numItems = PyList_Size(itemList);
	for( unsigned int index = 0; index<numItems; index++)
	{
		PyObject* key = PyList_GetItem( itemList, index );
		std::string varName = PYSSTR(key);

		// Do the following check just when the considered variables are not internal databases
		if ( (varName != DatabaseConstants::SCDB) &&
			 (varName != DatabaseConstants::GDB)  &&
			 (varName != DatabaseConstants::PROC) &&
			 (varName != DatabaseConstants::ARGS) &&
			 (varName != DatabaseConstants::IVARS))
		{
			/* If they key is contained in the initial variables set, then ignore it */
			if (m_initialVariables.find(varName) != m_initialVariables.end())
			{
				continue;
			}
		}
		/* If a variable with the same name has been retrieved in the local scope
		 * then it must be ignored */
		if (locals.find(varName) != locals.end())
		{
			continue;
		}

		// Ignore internal flags
		if (varName == "__USERLIB__") continue;

		PyObject* object = PyDict_GetItem( dict, key );

		if (!SPELLpythonHelper::instance().isInstance(object, "Database", "spell.lib.adapter.databases.database"))
		{
			if (PyCallable_Check(object)) continue;
			if (PyClass_Check(object)) continue;
			if (PyModule_Check(object)) continue;
			if (PyInstance_Check(object)) continue;
		}
		DEBUG("[VM] Processing " + varName);

		std::string type = PYSSTR( PyObject_Type(object) );
		std::string value = PYREPR( object );

		DEBUG("[VM] Type      : " + type);
		DEBUG("[VM] Value     : " + value);
		DEBUG("[VM] Global    : " + BSTR(true));
		DEBUG("[VM] Registered: " + BSTR(isRegistered(PYSSTR(key))));

		// Mark empty values (empty strings) as "<empty>"
		if (value == "") value = EMPTY_STRING;

		vars.push_back( SPELLvarInfo(varName, type, value, true, isRegistered(PYSSTR(key))) );
	}
}
Exemple #23
0
// Register signal change callback
// First argument should be the signal handle
// Second argument is the function to call
// Remaining arguments and keyword arguments are to be passed to the callback
static PyObject *register_value_change_callback(PyObject *self, PyObject *args) //, PyObject *keywds)
{
    FENTER

    PyObject *fArgs;
    PyObject *function;
    gpi_sim_hdl sig_hdl;
    gpi_sim_hdl hdl;
    unsigned int edge;

    p_callback_data callback_data_p;

    Py_ssize_t numargs = PyTuple_Size(args);

    if (numargs < 3) {
        fprintf(stderr, "Attempt to register value change callback without enough arguments!\n");
        return NULL;
    }

    PyObject *pSihHdl = PyTuple_GetItem(args, 0);
    if (!gpi_sim_hdl_converter(pSihHdl, &sig_hdl)) {
        return NULL;
    }

    // Extract the callback function
    function = PyTuple_GetItem(args, 1);
    if (!PyCallable_Check(function)) {
        fprintf(stderr, "Attempt to register value change callback without passing a callable callback!\n");
        return NULL;
    }
    Py_INCREF(function);

    PyObject *pedge = PyTuple_GetItem(args, 2);
    edge = (unsigned int)PyLong_AsLong(pedge);

    // Remaining args for function
    fArgs = PyTuple_GetSlice(args, 3, numargs);   // New reference
    if (fArgs == NULL) {
        return NULL;
    }


    callback_data_p = (p_callback_data)malloc(sizeof(s_callback_data));
    if (callback_data_p == NULL) {
        return PyErr_NoMemory();
    }

    // Set up the user data (no more python API calls after this!)
    // Causes segfault?
    callback_data_p->_saved_thread_state = PyThreadState_Get();//PyThreadState_Get();
    callback_data_p->id_value = COCOTB_ACTIVE_ID;
    callback_data_p->function = function;
    callback_data_p->args = fArgs;
    callback_data_p->kwargs = NULL;

    hdl = gpi_register_value_change_callback((gpi_function_t)handle_gpi_callback,
                                             callback_data_p,
                                             sig_hdl,
                                             edge);

    // Check success
    PyObject *rv = PyLong_FromVoidPtr(hdl);
    FEXIT

    return rv;
}
Exemple #24
0
// python function add_event_detect(gpio, edge, callback=None, bouncetime=0
static PyObject *py_add_event_detect(PyObject *self, PyObject *args, PyObject *kwargs)
{
   unsigned int gpio;
   unsigned int sys_gpio;
   int channel, edge, result;
   unsigned int bouncetime = 0;
   PyObject *cb_func = NULL;
   char *kwlist[] = {"gpio", "edge", "callback", "bouncetime", NULL};

   if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ii|Oi", kwlist, &channel, &edge, &cb_func, &bouncetime))
      return NULL;

   if (cb_func != NULL && !PyCallable_Check(cb_func))
   {
      PyErr_SetString(PyExc_TypeError, "Parameter must be callable");
      return NULL;
   }

   if (get_gpio_number(channel, &gpio, &sys_gpio))
       return NULL;

   // check channel is set up as an input
   if (gpio_direction[sys_gpio] != INPUT)
   {
      PyErr_SetString(PyExc_RuntimeError, "You must setup() the GPIO channel as an input first");
      return NULL;
   }
  
   //check channel whether support the event detected or not
   if(is_a20_platform())
   {
       if(support_event_detect(gpio, gpioEdge_BP) < 0)
      {
         PyErr_SetString(PyExc_RuntimeError, "the pin doesn't support to detect the external event!");
         return NULL;
      }
   }
   else if(is_s500_platform())
   {
       if(support_event_detect(gpio, gpioEdge_GT) < 0)
      {
         PyErr_SetString(PyExc_RuntimeError, "the pin doesn't support to detect the external event!");
         return NULL;
      }        
   }
   
   // is edge valid value
   edge -= PY_EVENT_CONST_OFFSET;
   if(is_a20_platform())
   {
       if (edge != RISING_EDGE && edge != FALLING_EDGE && edge != BOTH_EDGE)
       {
          PyErr_SetString(PyExc_ValueError, "The edge must be set to RISING, FALLING or BOTH");
          return NULL;
       }
   }
   else if(is_s500_platform())  //s500 doesn't support the "BOTH" trigger mode.
   {
       if (edge != RISING_EDGE && edge != FALLING_EDGE)
       {
          PyErr_SetString(PyExc_ValueError, "The edge must be set to RISING and FALLING");
          return NULL;
       }    
   }
   
   if (check_gpio_priv())
      return NULL;
	
   if ((result = add_edge_detect(sys_gpio, edge, bouncetime)) != 0)   // starts a thread
   {
      if (result == 1)
      {
         PyErr_SetString(PyExc_RuntimeError, "Edge detection already enabled for this GPIO channel");
         return NULL;
      } else {
         PyErr_SetString(PyExc_RuntimeError, "Failed to add edge detection");
         return NULL;
      }
   }

   if (cb_func != NULL)
      if (add_py_callback(sys_gpio, cb_func) != 0)
         return NULL;

   Py_RETURN_NONE;
}
void eListboxServiceContent::paint(gPainter &painter, eWindowStyle &style, const ePoint &offset, int selected)
{
	painter.clip(eRect(offset, m_itemsize));

	int marked = 0;

	if (m_current_marked && selected)
		marked = 2;
	else if (cursorValid() && isMarked(*m_cursor))
	{
		if (selected)
			marked = 2;
		else
			marked = 1;
	}
	else
		style.setStyle(painter, selected ? eWindowStyle::styleListboxSelected : eWindowStyle::styleListboxNormal);

	eListboxStyle *local_style = 0;

		/* get local listbox style, if present */
	if (m_listbox)
		local_style = m_listbox->getLocalStyle();

	if (marked == 1)  // marked
	{
		style.setStyle(painter, eWindowStyle::styleListboxMarked);
		if (m_color_set[markedForeground])
			painter.setForegroundColor(m_color[markedForeground]);
		if (m_color_set[markedBackground])
			painter.setBackgroundColor(m_color[markedBackground]);
	}
	else if (marked == 2) // marked and selected
	{
		style.setStyle(painter, eWindowStyle::styleListboxMarkedAndSelected);
		if (m_color_set[markedForegroundSelected])
			painter.setForegroundColor(m_color[markedForegroundSelected]);
		if (m_color_set[markedBackgroundSelected])
			painter.setBackgroundColor(m_color[markedBackgroundSelected]);
	}
	else if (local_style)
	{
		if (selected)
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_selected_set)
				painter.setBackgroundColor(local_style->m_background_color_selected);
			/* same for foreground */
			if (local_style->m_foreground_color_selected_set)
				painter.setForegroundColor(local_style->m_foreground_color_selected);
		}
		else
		{
			/* if we have a local background color set, use that. */
			if (local_style->m_background_color_set)
				painter.setBackgroundColor(local_style->m_background_color);
			/* same for foreground */
			if (local_style->m_foreground_color_set)
				painter.setForegroundColor(local_style->m_foreground_color);
		}
	}

	if (!local_style || !local_style->m_transparent_background)
		/* if we have no transparent background */
	{
		/* blit background picture, if available (otherwise, clear only) */
		if (local_style && local_style->m_background)
			painter.blit(local_style->m_background, offset, eRect(), 0);
		else
			painter.clear();
	} else
	{
		if (local_style->m_background)
			painter.blit(local_style->m_background, offset, eRect(), gPainter::BT_ALPHATEST);
		else if (selected && !local_style->m_selection)
			painter.clear();
	}

	if (cursorValid())
	{
		/* get service information */
		ePtr<iStaticServiceInformation> service_info;
		m_service_center->info(*m_cursor, service_info);
		eServiceReference ref = *m_cursor;
		bool isMarker = ref.flags & eServiceReference::isMarker;
		bool isPlayable = !(ref.flags & eServiceReference::isDirectory || isMarker);
		bool isRecorded = m_record_indicator_mode && isPlayable && checkServiceIsRecorded(ref);
		ePtr<eServiceEvent> evt;
		bool serviceAvail = true;
		bool serviceFallback = false;
		int isplayable_value;

		if (!marked && isPlayable && service_info && m_is_playable_ignore.valid())
		{
			isplayable_value = service_info->isPlayable(*m_cursor, m_is_playable_ignore);

			if (isplayable_value == 0) // service unavailable
			{
				if (m_color_set[serviceNotAvail])
					painter.setForegroundColor(m_color[serviceNotAvail]);
				else
					painter.setForegroundColor(gRGB(0xbbbbbb));
				serviceAvail = false;
			}
			else
			{
				if (isplayable_value == 2) // fallback receiver service
				{
					if (m_color_set[serviceItemFallback])
						painter.setForegroundColor(m_color[serviceItemFallback]);
					serviceFallback = true;
				}
			}
		}
		if (m_record_indicator_mode == 3 && isRecorded)
		{
			if (m_color_set[serviceRecorded])
				painter.setForegroundColor(m_color[serviceRecorded]);
			else
				painter.setForegroundColor(gRGB(0xb40431));
		}

		if (selected && local_style && local_style->m_selection)
			painter.blit(local_style->m_selection, offset, eRect(), gPainter::BT_ALPHATEST);

		int xoffset=0;  // used as offset when painting the folder/marker symbol or the serviceevent progress
		time_t now = time(0);

		for (int e = 0; e != celServiceTypePixmap; ++e)
		{
			if (m_element_font[e])
			{
				int flags=gPainter::RT_VALIGN_CENTER;
				int yoffs = 0;
				eRect area = m_element_position[e];
				std::string text = "<n/a>";
				switch (e)
				{
				case celServiceNumber:
				{
					if (area.width() <= 0)
						continue; // no point in going on if we won't paint anything

					if( m_cursor->getChannelNum() == 0 )
						continue;

					char buffer[15];
					snprintf(buffer, sizeof(buffer), "%d", m_cursor->getChannelNum() );
					text = buffer;
					flags|=gPainter::RT_HALIGN_RIGHT;
					if (isPlayable && serviceFallback && selected && m_color_set[serviceSelectedFallback])
						painter.setForegroundColor(m_color[serviceSelectedFallback]);
					break;
				}
				case celServiceName:
				{
					if (service_info)
						service_info->getName(*m_cursor, text);
					if (!isPlayable)
					{
						area.setWidth(area.width() + m_element_position[celServiceEventProgressbar].width() +  m_nonplayable_margins);
						if (m_element_position[celServiceEventProgressbar].left() == 0)
							area.setLeft(0);
						if (m_element_position[celServiceNumber].width() && m_element_position[celServiceEventProgressbar].left() == m_element_position[celServiceNumber].width() +  m_nonplayable_margins)
							area.setLeft(m_element_position[celServiceNumber].width() +  m_nonplayable_margins);
					}
					if (!(m_record_indicator_mode == 3 && isRecorded) && isPlayable && serviceFallback && selected && m_color_set[serviceSelectedFallback])
						painter.setForegroundColor(m_color[serviceSelectedFallback]);
					break;
				}
				case celServiceInfo:
				{
					if ( isPlayable && service_info && !service_info->getEvent(*m_cursor, evt) )
					{
						std::string name = evt->getEventName();
						if (name.empty())
							continue;
						text = evt->getEventName();
						if (serviceAvail)
						{
							if (!selected && m_color_set[eventForeground])
								painter.setForegroundColor(m_color[eventForeground]);
							else if (selected && m_color_set[eventForegroundSelected])
								painter.setForegroundColor(m_color[eventForegroundSelected]);
							else
								painter.setForegroundColor(gRGB(0xe7b53f));

							if (serviceFallback && !selected && m_color_set[eventForegroundFallback]) // fallback receiver
								painter.setForegroundColor(m_color[eventForegroundFallback]);
							else if (serviceFallback && selected && m_color_set[eventForegroundSelectedFallback])
								painter.setForegroundColor(m_color[eventForegroundSelectedFallback]);

						}
						break;
					}
					continue;
				}
				case celServiceEventProgressbar:
				{
					if (area.width() > 0 && isPlayable && service_info && !service_info->getEvent(*m_cursor, evt))
					{
						char buffer[15];
						snprintf(buffer, sizeof(buffer), "%d %%", (int)(100 * (now - evt->getBeginTime()) / evt->getDuration()));
						text = buffer;
						flags|=gPainter::RT_HALIGN_RIGHT;
						break;
					}
					continue;
				}
				}

				eRect tmp = area;
				int xoffs = 0;
				ePtr<gPixmap> piconPixmap;

				if (e == celServiceName)
				{
					//picon stuff
					if (isPlayable && PyCallable_Check(m_GetPiconNameFunc))
					{
						ePyObject pArgs = PyTuple_New(1);
						PyTuple_SET_ITEM(pArgs, 0, PyString_FromString(ref.toString().c_str()));
						ePyObject pRet = PyObject_CallObject(m_GetPiconNameFunc, pArgs);
						Py_DECREF(pArgs);
						if (pRet)
						{
							if (PyString_Check(pRet))
							{
								std::string piconFilename = PyString_AS_STRING(pRet);
								if (!piconFilename.empty())
									loadPNG(piconPixmap, piconFilename.c_str());
							}
							Py_DECREF(pRet);
						}
					}
					xoffs = xoffset;
					tmp.setWidth(((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? tmp.width() : m_column_width) - xoffs);
				}

				ePtr<eTextPara> para = new eTextPara(tmp);
				para->setFont(m_element_font[e]);
				para->renderString(text.c_str());

				if (e == celServiceName)
				{
					eRect bbox = para->getBoundBox();

					int servicenameWidth = ((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? bbox.width() : m_column_width);
					m_element_position[celServiceInfo].setLeft(area.left() + servicenameWidth + m_items_distances + xoffs);
					m_element_position[celServiceInfo].setTop(area.top());
					m_element_position[celServiceInfo].setWidth(area.width() - (servicenameWidth + m_items_distances + xoffs));
					m_element_position[celServiceInfo].setHeight(area.height());

					if (isPlayable)
					{
						//picon stuff
						if (PyCallable_Check(m_GetPiconNameFunc) and (m_column_width || piconPixmap))
						{
							eRect area = m_element_position[celServiceInfo];
							/* PIcons are usually about 100:60. Make it a
							 * bit wider in case the icons are diffently
							 * shaped, and to add a bit of margin between
							 * icon and text. */
							const int iconWidth = area.height() * 9 / 5;
							m_element_position[celServiceInfo].setLeft(area.left() + iconWidth);
							m_element_position[celServiceInfo].setWidth(area.width() - iconWidth);
							area = m_element_position[celServiceName];
							xoffs += iconWidth;
							if (piconPixmap)
							{
								area.moveBy(offset);
								painter.clip(area);
								painter.blitScale(piconPixmap,
									eRect(area.left(), area.top(), iconWidth, area.height()),
									area,
									gPainter::BT_ALPHABLEND | gPainter::BT_KEEP_ASPECT_RATIO | gPainter::BT_HALIGN_CENTER | gPainter::BT_VALIGN_CENTER);
								painter.clippop();
							}
						}

						//service type marker stuff
						if (m_servicetype_icon_mode)
						{
							int orbpos = m_cursor->getUnsignedData(4) >> 16;
							const char *filename = ref.path.c_str();
							ePtr<gPixmap> &pixmap =
								(m_cursor->flags & eServiceReference::isGroup) ? m_pixmaps[picServiceGroup] :
								(strstr(filename, "://")) ? m_pixmaps[picStream] :
								(orbpos == 0xFFFF) ? m_pixmaps[picDVB_C] :
								(orbpos == 0xEEEE) ? m_pixmaps[picDVB_T] : m_pixmaps[picDVB_S];
							if (pixmap)
							{
								eSize pixmap_size = pixmap->size();
								eRect area = m_element_position[celServiceInfo];
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances);
								int offs = 0;
								if (m_servicetype_icon_mode == 1)
								{
									area = m_element_position[celServiceName];
									offs = xoffs;
									xoffs += pixmap_size.width() + m_items_distances;
								}
								else if (m_crypto_icon_mode == 1 && m_pixmaps[picCrypto])
									offs = offs + m_pixmaps[picCrypto]->size().width() + m_items_distances;
								int correction = (area.height() - pixmap_size.height()) / 2;
								area.moveBy(offset);
								painter.clip(area);
								painter.blit(pixmap, ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHATEST);
								painter.clippop();
							}
						}

						//crypto icon stuff
						if (m_crypto_icon_mode && m_pixmaps[picCrypto])
						{
							eSize pixmap_size = m_pixmaps[picCrypto]->size();
							eRect area = m_element_position[celServiceInfo];
							int offs = 0;
							if (m_crypto_icon_mode == 1)
							{
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances);
								area = m_element_position[celServiceName];
								offs = xoffs;
								xoffs += pixmap_size.width() + m_items_distances;
							}
							int correction = (area.height() - pixmap_size.height()) / 2;
							area.moveBy(offset);
							if (service_info && service_info->isCrypted())
							{
								if (m_crypto_icon_mode == 2)
								{
									m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances);
									m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances);
								}
								painter.clip(area);
								painter.blit(m_pixmaps[picCrypto], ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHATEST);
								painter.clippop();
							}
						}

						//record icon stuff
						if (isRecorded && m_record_indicator_mode < 3 && m_pixmaps[picRecord])
						{
							eSize pixmap_size = m_pixmaps[picRecord]->size();
							eRect area = m_element_position[celServiceInfo];
							int offs = 0;
							if (m_record_indicator_mode == 1)
							{
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances);
								area = m_element_position[celServiceName];
								offs = xoffs;
								xoffs += pixmap_size.width() + m_items_distances;
							}
							int correction = (area.height() - pixmap_size.height()) / 2;
							area.moveBy(offset);
							if (m_record_indicator_mode == 2)
							{
								m_element_position[celServiceInfo].setLeft(area.left() + pixmap_size.width() + m_items_distances);
								m_element_position[celServiceInfo].setWidth(area.width() - pixmap_size.width() - m_items_distances);
							}
							painter.clip(area);
							painter.blit(m_pixmaps[picRecord], ePoint(area.left() + offs, offset.y() + correction), area, gPainter::BT_ALPHATEST);
							painter.clippop();
						}
					}
				}

				if (flags & gPainter::RT_HALIGN_RIGHT)
					para->realign(eTextPara::dirRight);
				else if (flags & gPainter::RT_HALIGN_CENTER)
					para->realign(eTextPara::dirCenter);
				else if (flags & gPainter::RT_HALIGN_BLOCK)
					para->realign(eTextPara::dirBlock);

				if (flags & gPainter::RT_VALIGN_CENTER)
				{
					eRect bbox = para->getBoundBox();
					yoffs = (area.height() - bbox.height()) / 2 - bbox.top();
				}

				painter.renderPara(para, offset+ePoint(xoffs, yoffs));
			}
			else if ((e == celFolderPixmap && m_cursor->flags & eServiceReference::isDirectory) ||
				(e == celMarkerPixmap && m_cursor->flags & eServiceReference::isMarker &&
				!(m_cursor->flags & eServiceReference::isNumberedMarker)))
			{
				ePtr<gPixmap> &pixmap =
					(e == celFolderPixmap) ? m_pixmaps[picFolder] : m_pixmaps[picMarker];
				if (pixmap)
				{
					eSize pixmap_size = pixmap->size();
					eRect area;
					if (e == celFolderPixmap || m_element_position[celServiceNumber].width() < pixmap_size.width())
					{
						area = m_element_position[celServiceName];
						if (m_element_position[celServiceEventProgressbar].left() == 0)
							area.setLeft(0);
						xoffset = pixmap_size.width() + m_items_distances;			
					}
					else
						area = m_element_position[celServiceNumber];
					int correction = (area.height() - pixmap_size.height()) / 2;
					area.moveBy(offset);
					painter.clip(area);
					painter.blit(pixmap, ePoint(area.left(), offset.y() + correction), area, gPainter::BT_ALPHATEST);
					painter.clippop();
				}
			}
		}
Exemple #26
0
void PythonPlugin::initialize()
{
    addObject(&mLogger);

    if (!Py_IsInitialized()) {
        // PEP370
        Py_NoSiteFlag = 1;
        Py_NoUserSiteDirectory = 1;

        Py_Initialize();
        inittiled();

        // Get reference to base class to find its extensions later on
        PyObject *pmod = PyImport_ImportModule("tiled");
        if (pmod) {
            PyObject *tiledPlugin = PyObject_GetAttrString(pmod, "Plugin");
            Py_DECREF(pmod);

            if (tiledPlugin) {
                if (PyCallable_Check(tiledPlugin)) {
                    mPluginClass = tiledPlugin;
                } else {
                    Py_DECREF(tiledPlugin);
                }
            }
        }

        if (!mPluginClass) {
            log(Tiled::LoggingInterface::ERROR, "Can't find tiled.Plugin baseclass\n");
            handleError();
            return;
        }

        // w/o differentiating error messages could just rename "log"
        // to "write" in the binding and assign plugin directly to stdout/stderr
        PySys_SetObject((char *)"_tiledplugin",
                        _wrap_convert_c2py__Tiled__LoggingInterface(&mLogger));

        PyRun_SimpleString("import sys\n"
                           "#from tiled.Tiled.LoggingInterface import INFO,ERROR\n"
                           "class _Catcher:\n"
                           "   def __init__(self, type):\n"
                           "      self.buffer = ''\n"
                           "      self.type = type\n"
                           "   def write(self, msg):\n"
                           "      self.buffer += msg\n"
                           "      if self.buffer.endswith('\\n'):\n"
                           "         sys._tiledplugin.log(self.type, self.buffer)\n"
                           "         self.buffer = ''\n"
                           "sys.stdout = _Catcher(0)\n"
                           "sys.stderr = _Catcher(1)\n");

        PyRun_SimpleString(QString("import sys; sys.path.insert(0, \"%1\")")
                           .arg(mScriptDir).toUtf8().constData());

        log(QString("-- Added %1 to path\n").arg(mScriptDir));
    }

    reloadModules();

    if (QFile::exists(mScriptDir)) {
        mFileSystemWatcher.addPath(mScriptDir);

        connect(&mFileSystemWatcher, SIGNAL(directoryChanged(QString)),
                &mReloadTimer, SLOT(start()));
    }
}
PyObject *
PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
{
    PyWeakReference *result = NULL;
    PyWeakReference **list;
    PyWeakReference *ref, *proxy;

    if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) {
        PyErr_Format(PyExc_TypeError,
                     "cannot create weak reference to '%s' object",
                     Py_TYPE(ob)->tp_name);
        return NULL;
    }
    list = GET_WEAKREFS_LISTPTR(ob);
    get_basic_refs(*list, &ref, &proxy);
    if (callback == Py_None)
        callback = NULL;
    if (callback == NULL)
        /* attempt to return an existing weak reference if it exists */
        result = proxy;
    if (result != NULL)
        Py_INCREF(result);
    else {
        /* Note: new_weakref() can trigger cyclic GC, so the weakref
           list on ob can be mutated.  This means that the ref and
           proxy pointers we got back earlier may have been collected,
           so we need to compute these values again before we use
           them. */
        result = new_weakref(ob, callback);
        if (result != NULL) {
            PyWeakReference *prev;

            if (PyCallable_Check(ob))
                Py_TYPE(result) = &_PyWeakref_CallableProxyType;
            else
                Py_TYPE(result) = &_PyWeakref_ProxyType;
            get_basic_refs(*list, &ref, &proxy);
            if (callback == NULL) {
                if (proxy != NULL) {
                    /* Someone else added a proxy without a callback
                       during GC.  Return that one instead of this one
                       to avoid violating the invariants of the list
                       of weakrefs for ob. */
                    Py_DECREF(result);
                    Py_INCREF(result = proxy);
                    goto skip_insert;
                }
                prev = ref;
            }
            else
                prev = (proxy == NULL) ? ref : proxy;

            if (prev == NULL)
                insert_head(result, list);
            else
                insert_after(result, prev);
        skip_insert:
            ;
        }
    }
    return (PyObject *) result;
}
Exemple #28
0
PyObject *
PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
{
	PyWeakReference *result = NULL;
	PyWeakReference **list;
	PyWeakReference *ref, *proxy;

	if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) {
		PyErr_Format(PyExc_TypeError,
				"cannot create weak reference to '%s' object",
				Py_TYPE(ob)->tp_name);
		return NULL;
	}
	list = GET_WEAKREFS_LISTPTR(ob);
	get_basic_refs(*list, &ref, &proxy);
	if (callback == Py_None)
		callback = NULL;
	if (callback == NULL)
		/* attempt to return an existing weak reference if it exists */
		result = proxy;
	if (result != NULL)
		Py_INCREF(result);
	else {
		/* Note: new_weakref() can trigger cyclic GC, so the weakref
		   list on ob can be mutated.  This means that the ref and
		   proxy pointers we got back earlier may have been collected,
		   so we need to compute these values again before we use
		   them. */
		if (PyCallable_Check(ob))
			result = new_weakref(ob, callback, &_PyWeakref_CallableProxyType);
		else
			result = new_weakref(ob, callback, &_PyWeakref_ProxyType);

		if (result != NULL) {
			PyWeakReference *prev;

			//JyNI-note: These lines mess up JyNI-initialization.
			//In new_weakref _PyObject_GC_New(&_PyWeakref_RefType) is
			//called, which caches the tme for _PyWeakref_RefType in
			//jy->jy. Now the type is altered afterwards leading to
			//a wrong tme. Shall we fix it here, or implement a
			//lookup in unconsistent case?
			//(Better fix it here)
//			if (PyCallable_Check(ob))
//				Py_TYPE(result) = &_PyWeakref_CallableProxyType;
//			else
//				Py_TYPE(result) = &_PyWeakref_ProxyType;
			get_basic_refs(*list, &ref, &proxy);
			if (callback == NULL) {
				if (proxy != NULL) {
					/* Someone else added a proxy without a callback
					   during GC.  Return that one instead of this one
					   to avoid violating the invariants of the list
					   of weakrefs for ob. */
					Py_DECREF(result);
					Py_INCREF(result = proxy);
					goto skip_insert;
				}
				prev = ref;
			}
			else
				prev = (proxy == NULL) ? ref : proxy;

			if (prev == NULL)
				insert_head(result, list);
			else
				insert_after(result, prev);
		skip_insert:
			;
		}
	}
	return (PyObject *) result;
}
Exemple #29
0
int py_plugin_open(struct plugin *plugin, char *dir)
{
	PyObject *handle, *info;
	PyObject *PyStr;
	PyObject *PyErrType, *PyErr, *PyTraceback;

	if (!(PyStr = PyString_FromString(dir))) {
		PyErr_Print();
		return -1;
	}

	if (PyList_Insert(PyPath, 0, PyStr)) {
		Py_DECREF(PyStr);
		return -1;
	}

	if (!(handle = PyImport_ImportModule(plugin->name))) {
		/* ignore "module not found" errors in top level module */
		PyErr_Fetch(&PyErrType, &PyErr, &PyTraceback);
		PyErr_NormalizeException(&PyErrType, &PyErr, &PyTraceback);
		if (PyErr_GivenExceptionMatches(PyErr, PyExc_ImportError) &&
		  !PyTraceback) {
			Py_XDECREF(PyErrType);
			Py_XDECREF(PyErr);
		}
		else {
			PyErr_Restore(PyErrType, PyErr, PyTraceback);
			PyErr_Print();
		}

		if (PySequence_DelItem(PyPath, 0)) {
			PyErr_Print();
		}
		Py_DECREF(PyStr);
		return -1;
	}

	if (PySequence_DelItem(PyPath, 0)) {
		PyErr_Print();
	}
	Py_DECREF(PyStr);

	if (!(plugin->p = malloc(sizeof(struct py_plugin)))) {
		wminput_err("Error allocating py_plugin");
		return -1;
	}

	plugin->type = PLUGIN_PYTHON;
	plugin->info = NULL;
	plugin->data = NULL;
	((struct py_plugin *) plugin->p)->init = NULL;
	((struct py_plugin *) plugin->p)->exec = NULL;

	if (!(plugin->info = malloc(sizeof *plugin->info))) {
		wminput_err("Error allocating plugin info");
		goto ERR_HND;
	}
	if (!(plugin->data = malloc(sizeof *plugin->data))) {
		wminput_err("Error allocating plugin data");
		goto ERR_HND;
	}
	if (!(((struct py_plugin *)plugin->p)->init =
	  PyObject_GetAttrString(handle, "wmplugin_init"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(((struct py_plugin *)plugin->p)->init)) {
		wminput_err("Unable to load plugin init function: not callable");
		goto ERR_HND;
	}
	if (!(((struct py_plugin *)plugin->p)->exec =
	  PyObject_GetAttrString(handle, "wmplugin_exec"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(((struct py_plugin *)plugin->p)->exec)) {
		wminput_err("Unable to load plugin exec function: not callable");
		goto ERR_HND;
	}
	if (!(info = PyObject_GetAttrString(handle, "wmplugin_info"))) {
		PyErr_Print();
		goto ERR_HND;
	}
	if (!PyCallable_Check(info)) {
		wminput_err("Unable to load plugin info function: not callable");
		Py_DECREF((PyObject *)info);
		goto ERR_HND;
	}
	if (py_plugin_info(plugin, info)) {
		wminput_err("Error on python_info");
		Py_DECREF((PyObject *)info);
		goto ERR_HND;
	}
	Py_DECREF((PyObject *)info);

	((struct py_plugin *) plugin->p)->handle = handle;

	return 0;

ERR_HND:
	if (plugin->info) {
		free(plugin->info);
	}
	if (plugin->data) {
		free(plugin->data);
	}
	if (plugin->p) {
		if (((struct py_plugin *)plugin->p)->init) {
			Py_DECREF(((struct py_plugin *)plugin->p)->init);
		}
		if (((struct py_plugin *)plugin->p)->exec) {
			Py_DECREF(((struct py_plugin *)plugin->p)->exec);
		}
		free(plugin->p);
	}
	Py_DECREF(handle);
	return -1;
}
Exemple #30
0
static int pyth_metric_init (apr_pool_t *p)
{
    DIR *dp;
    struct dirent *entry;
    int i;
    char* modname;
    PyObject *pmod, *pinitfunc, *pobj, *pparamdict;
    py_metric_init_t minfo;
    Ganglia_25metric *gmi;
    mapped_info_t *mi;
    const char* path = python_module.module_params;
    cfg_t *module_cfg;

    /* Allocate a pool that will be used by this module */
    apr_pool_create(&pool, p);

    metric_info = apr_array_make(pool, 10, sizeof(Ganglia_25metric));
    metric_mapping_info = apr_array_make(pool, 10, sizeof(mapped_info_t));

    /* Verify path exists and can be read */

    if (!path) {
        err_msg("[PYTHON] Missing python module path.\n");
        return -1;
    }

    if (access(path, F_OK))
    {
        /* 'path' does not exist */
        err_msg("[PYTHON] Can't open the python module path %s.\n", path);
        return -1;
    }

    if (access(path, R_OK))
    {
        /* Don't have read access to 'path' */
        err_msg("[PYTHON] Can't read from the python module path %s.\n", path);
        return -1;
    }

    /* Init Python environment */

    /* Set up the python path to be able to load module from our module path */
    Py_Initialize();
    Py_InitModule("ganglia", GangliaMethods);

    PyObject *sys_path = PySys_GetObject("path");
    PyObject *addpath = PyString_FromString(path);
    PyList_Append(sys_path, addpath);

    PyEval_InitThreads();
    gtstate = PyEval_SaveThread();

    /* Initialize each python module */
    if ((dp = opendir(path)) == NULL) {
        /* Error: Cannot open the directory - Shouldn't happen */
        /* Log? */
        err_msg("[PYTHON] Can't open the python module path %s.\n", path);
        return -1;
    }

    i = 0;

    while ((entry = readdir(dp)) != NULL) {
        modname = is_python_module(entry->d_name);

        if (modname == NULL)
            continue;

        /* Find the specified module configuration in gmond.conf 
           If this return NULL then either the module config
           doesn't exist or the module is disabled. */
        module_cfg = find_module_config(modname);
        if (!module_cfg)
            continue;

        PyEval_RestoreThread(gtstate);

        pmod = PyImport_ImportModule(modname);
        if (!pmod) {
            /* Failed to import module. Log? */
            err_msg("[PYTHON] Can't import the metric module [%s].\n", modname);
            if (PyErr_Occurred()) {
                PyErr_Print();
            }
            gtstate = PyEval_SaveThread();
            continue;
        }

        pinitfunc = PyObject_GetAttrString(pmod, "metric_init");
        if (!pinitfunc || !PyCallable_Check(pinitfunc)) {
            /* No metric_init function. */
            err_msg("[PYTHON] Can't find the metric_init function in the python module [%s].\n", modname);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        /* Build a parameter dictionary to pass to the module */
        pparamdict = build_params_dict(module_cfg);
        if (!pparamdict || !PyDict_Check(pparamdict)) {
            /* No metric_init function. */
            err_msg("[PYTHON] Can't build the parameters dictionary for [%s].\n", modname);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        /* Now call the metric_init method of the python module */
        pobj = PyObject_CallFunction(pinitfunc, "(N)", pparamdict);

        if (!pobj) {
            /* failed calling metric_init */
            err_msg("[PYTHON] Can't call the metric_init function in the python module [%s].\n", modname);
            if (PyErr_Occurred()) {
                PyErr_Print();
            }
            Py_DECREF(pinitfunc);
            Py_DECREF(pmod);
            gtstate = PyEval_SaveThread();
            continue;
        }

        if (PyList_Check(pobj)) {
            int j;
            int size = PyList_Size(pobj);
            for (j = 0; j < size; j++) {
                PyObject* plobj = PyList_GetItem(pobj, j);
                if (PyMapping_Check(plobj)) {
                    fill_metric_info(plobj, &minfo, modname, pool);
                    gmi = (Ganglia_25metric*)apr_array_push(metric_info);
                    fill_gmi(gmi, &minfo);
                    mi = (mapped_info_t*)apr_array_push(metric_mapping_info);
                    mi->pmod = pmod;
                    mi->mod_name = apr_pstrdup(pool, modname);
                    mi->pcb = minfo.pcb;
                }
            }
        }
        else if (PyMapping_Check(pobj)) {
            fill_metric_info(pobj, &minfo, modname, pool);
            gmi = (Ganglia_25metric*)apr_array_push(metric_info);
            fill_gmi(gmi, &minfo);
            mi = (mapped_info_t*)apr_array_push(metric_mapping_info);
            mi->pmod = pmod;
            mi->mod_name = apr_pstrdup(pool, modname);
            mi->pcb = minfo.pcb;
        }
        Py_DECREF(pobj);
        Py_DECREF(pinitfunc);
        gtstate = PyEval_SaveThread();
    }
    closedir(dp);

    apr_pool_cleanup_register(pool, NULL,
                              pyth_metric_cleanup,
                              apr_pool_cleanup_null);

    /* Replace the empty static metric definition array with the
       dynamic array that we just created 
    */
    /*XXX Need to put this into a finalize MACRO. This is just pushing
      a NULL entry onto the array so that the looping logic can 
      determine the end if the array. We should probably give back
      a ready APR array rather than a pointer to a Ganglia_25metric
      array. */
    gmi = apr_array_push(metric_info);
    memset (gmi, 0, sizeof(*gmi));
    mi = apr_array_push(metric_mapping_info);
    memset (mi, 0, sizeof(*mi));

    python_module.metrics_info = (Ganglia_25metric *)metric_info->elts;
    return 0;
}