Ejemplo n.º 1
0
bool PythonPlugin::loadOrReloadModule(ScriptEntry &script)
{
    const QByteArray name = script.name.toUtf8();

    if (script.module) {
        PySys_WriteStdout("-- Reloading %s\n", name.constData());

        PyObject *module = PyImport_ReloadModule(script.module);
        Py_DECREF(script.module);
        script.module = module;
    } else {
        PySys_WriteStdout("-- Loading %s\n", name.constData());
        script.module = PyImport_ImportModule(name.constData());
    }

    if (!script.module)
        return false;

    PyObject *pluginClass = findPluginSubclass(script.module);

    if (!pluginClass) {
        PySys_WriteStderr("Extension of tiled.Plugin not defined in "
                          "script: %s\n", name.constData());
        return false;
    }

    if (script.mapFormat) {
        script.mapFormat->setPythonClass(pluginClass);
    } else {
        script.mapFormat = new PythonMapFormat(name, pluginClass, *this);
        addObject(script.mapFormat);
    }

    return true;
}
Ejemplo n.º 2
0
PyObject *
pyotherside_find_module(PyObject *self, PyObject *args) {

    char *fullname, *path;
    int err = PyArg_ParseTuple(args, "s|z", &fullname, &path);

    QString filename(fullname);
    qDebug() << "Search for module " + filename.toUtf8();
    if(err == 0)
    {
        PyObject_Print(PyErr_Occurred(), stdout, Py_PRINT_RAW);
        PySys_WriteStdout("\n");
        PyErr_Print();
        PySys_WriteStdout("\n");
        return Py_None;
    }

    QDir qrc(":/");
    if (((qrc.exists(filename+".py"))
         | (qrc.exists(filename+".pyc"))
         | (qrc.exists(filename+".pyo")))
            | (QDir(":/"+filename).exists())) {
        Py_INCREF(self);
        qDebug() << "Found module "+filename.toUtf8();
        return self;
    }
    qDebug() << "Can't found module "+filename.toUtf8();
    Py_INCREF(Py_None);
    return Py_None;
}
Ejemplo n.º 3
0
hlVoid PrintValidation(HLValidation eValidation)
{
	switch(eValidation)
	{
	case HL_VALIDATES_ASSUMED_OK:
		PySys_WriteStdout("Assumed OK");
		break;
	case HL_VALIDATES_OK:
		PySys_WriteStdout("OK");
		break;
	case HL_VALIDATES_INCOMPLETE:
		PySys_WriteStderr("Incomplete");
		break;
	case HL_VALIDATES_CORRUPT:
		PySys_WriteStderr("Corrupt");
		break;
	case HL_VALIDATES_CANCELED:
		PySys_WriteStderr("Canceled");
		break;
	case HL_VALIDATES_ERROR:
		PySys_WriteStderr("Error");
		break;
	default:
		PySys_WriteStderr("Unknown");
		break;
	}
}
Ejemplo n.º 4
0
hlVoid ExtractItemStartCallback(HLDirectoryItem *pItem)
{
#if 0
	PyEval_RestoreThread(g_extract_save);

	if( pStartExtractFunc == Py_None )
	{
		if(!bSilent)
		{
			if(hlItemGetType(pItem) == HL_ITEM_FILE)
			{
				PySys_WriteStdout("  Extracting %s: ", hlItemGetName(pItem));
				ProgressStart();
			}
			else
			{
				PySys_WriteStdout("  Extracting %s:\n", hlItemGetName(pItem));
			}
		}
	}
	else
	{
		PyEval_CallFunction(pStartExtractFunc, "si", hlItemGetName(pItem), hlItemGetType(pItem));
	}

	g_extract_save = PyEval_SaveThread();
#endif // 0
}
Ejemplo n.º 5
0
static PyObject *
	Package_extract(PackageObject *self, PyObject *args)
{
	hlUInt i;

	hlUInt uiExtractItems = 0;
	hlChar *lpExtractItems[MAX_ITEMS];
	hlChar *lpDestination = 0;;

	HLDirectoryItem *pItem = 0;

	pUpdateFunc = Py_None;

	if (!PyArg_ParseTuple(args, "ss|O", &lpExtractItems[0], &lpDestination, &pUpdateFunc))
	{
		return NULL;
	}

	uiExtractItems = 1;

	// Just before extracting set these globals
	hlSetBoolean(HL_OVERWRITE_FILES, self->bOverwriteFiles);
	hlSetBoolean(HL_FORCE_DEFRAGMENT, self->bForceDefragment);
	bSilent = self->bSilent;

	// Extract the requested items.
	for(i = 0; i < uiExtractItems; i++)
	{
		// Find the item.
		pItem = hlFolderGetItemByPath(hlPackageGetRoot(), lpExtractItems[i], HL_FIND_ALL);

		if(pItem == 0)
		{
			PySys_WriteStdout("%s not found in package.\n", lpExtractItems[i]);
			continue;
		}

		if(!self->bSilent)
		{
			PySys_WriteStdout("Extracting %s...\n\n", hlItemGetName(pItem));
		}

		// Extract the item.
		// Item is extracted to cDestination\Item->GetName().
		g_extract_save = PyEval_SaveThread();
		g_bytesExtracted = 0;
		hlItemExtract(pItem, lpDestination);
		PyEval_RestoreThread(g_extract_save);

		if(!self->bSilent)
		{
			PySys_WriteStdout("\nDone.\n");
		}
	}

	Py_INCREF(Py_None);
	return Py_None;
}
Ejemplo n.º 6
0
void AppCompleteExport initComplete()
{
    // load dependent module
    try {
        Base::Interpreter().loadModule("Part");
        Base::Interpreter().loadModule("Mesh");
        Base::Interpreter().loadModule("Points");
        //Base::Interpreter().loadModule("MeshPart");
        //Base::Interpreter().loadModule("Assembly");
        Base::Interpreter().loadModule("Drawing");
        Base::Interpreter().loadModule("Raytracing");
#       ifdef COMPLETE_SHOW_SKETCHER
        Base::Interpreter().loadModule("Sketcher");
#       endif
        Base::Interpreter().loadModule("PartDesign");
        Base::Interpreter().loadModule("Image");
        //Base::Interpreter().loadModule("Cam");
#       ifdef COMPLETE_USE_DRAFTING
        try {
            Base::Interpreter().loadModule("Draft");
        }
        catch (const Base::Exception& e) {
            // If called from console then issue a message but don't stop with an error
            PySys_WriteStdout("Import error: %s\n", e.what());
        }
#       endif
    }
    catch(const Base::Exception& e) {
        PyErr_SetString(PyExc_ImportError, e.what());
        return;
    }
    Py_InitModule3("Complete", Complete_methods, module_Complete_doc);   /* mod name, table ptr */
    Base::Console().Log("Loading Complete module... done\n");
}
Ejemplo n.º 7
0
hlVoid ProgressStart()
{
#ifndef _WIN32
	uiProgressLast = 0;
	PySys_WriteStdout("0%%");
#endif
}
static PyObject *ignp_fun_sumDegree(PyObject *self, PyObject *args)
{
    PyObject* x_obj;
    PyObject* mem_addr_o;
    long int mem_addr;
    igraph_t* g;
    double value;
    
    /* Parse the input tuple */
    if (!PyArg_ParseTuple(args, "O", &x_obj))
        return NULL;
        
    mem_addr_o = PyObject_CallMethod(x_obj, "_raw_pointer", "()");
    mem_addr = PyInt_AsLong(mem_addr_o);
    Py_DECREF(mem_addr_o);
    if (mem_addr == -1) { 
        printf("PyInt to Long Failed");
        return NULL;
    }
    g = (igraph_t*) mem_addr;
    
    /* Call the external C function to compute sum degree. */
    value = sumDegree(g);

    /* Build the output tuple */
    PyObject *ret = Py_BuildValue("d", value);
    PySys_WriteStdout("Finished Computing Sum\n");
    return ret;
    
}
Ejemplo n.º 9
0
static PyObject *
	Package_validate(PackageObject *self, PyObject *args)
{
	hlUInt i;

	hlUInt uiValidateItems = 0;
	hlChar *lpValidateItems[MAX_ITEMS];

	HLDirectoryItem *pItem = 0;

	if (!PyArg_ParseTuple(args, "s", &lpValidateItems[0]))
	{
		return NULL;
	}

	uiValidateItems = 1;

	// Validate the requested items.
	for(i = 0; i < uiValidateItems; i++)
	{
		// Find the item.
		pItem = hlFolderGetItemByPath(hlPackageGetRoot(), lpValidateItems[i], HL_FIND_ALL);

		if(pItem == 0)
		{
			printf("%s not found in package.\n", lpValidateItems[i]);
			continue;
		}

		if(!self->bSilent)
		{
			PySys_WriteStdout("Validating %s...\n\n", hlItemGetName(pItem));
		}

		// Validate the item.
		Validate(self, pItem);

		if(!self->bSilent)
		{
			PySys_WriteStdout("\nDone.\n");
		}
	}

	Py_INCREF(Py_None);
	return Py_None;
}
Ejemplo n.º 10
0
hlVoid ProgressUpdate(hlULongLong uiBytesDone, hlULongLong uiBytesTotal)
{
	if(!bSilent)
	{
#ifdef _WIN32
		HANDLE Handle = GetStdHandle(STD_OUTPUT_HANDLE);
		if (Handle != INVALID_HANDLE_VALUE)
		{
			CONSOLE_SCREEN_BUFFER_INFO Info;
			if(GetConsoleScreenBufferInfo(Handle, &Info))
			{
				if(uiBytesTotal == 0)
				{
					PySys_WriteStdout("100.0%%");
				}
				else
				{
					PySys_WriteStdout("%0.0f%%", (hlSingle)((hlDouble)uiBytesDone / (hlDouble)uiBytesTotal * 100.0));
				}
				SetConsoleCursorPosition(Handle, Info.dwCursorPosition);
			}
		}
#else
		hlUInt uiProgress = uiBytesTotal == 0 ? 100 : (hlUInt)((hlUInt64)uiBytesDone * 100 / (hlUInt64)uiBytesTotal);
		while(uiProgress >= uiProgressLast + 10)
		{
			uiProgressLast += 10;
			if(uiProgressLast == 100)
			{
				PySys_WriteStdout("100%% ");
			}
			else if(uiProgressLast == 50)
			{
				PySys_WriteStdout("50%%");
			}
			else
			{
				PySys_WriteStdout(".");
			}
		}
#endif
	}
}
Ejemplo n.º 11
0
    std::streamsize write(const char* rawString, std::streamsize stringSize) {

        std::streamsize charactersWritten;
        charactersWritten = std::min(stringSize, SIZE_STREAM_BUFFER);

        PySys_WriteStdout((boost::format("%%.%1%s") %
                charactersWritten).str().c_str(), rawString);

        return charactersWritten;

    } // PythonOutputStreamSink::write
Ejemplo n.º 12
0
/* Print complex to stdout*/
DYNAMIC_LIB_DECORATION void qcs_print_complex(tf_qcs_complex *a_in)
{
#ifdef PYTHON_SCRIPT
     if(a_in->im>0)
         PySys_WriteStdout("%2.2f + %2.2fi ", a_in->re,  a_in->im);
     if(a_in->im<0)
         PySys_WriteStdout("%2.2f - %2.2fi ", a_in->re, -a_in->im);
     if(a_in->re!=0 && a_in->im == 0)
         PySys_WriteStdout("%2.2f ", a_in->re);
     if(a_in->re == 0 && a_in->im == 0)
         PySys_WriteStdout("0.00 ");
#else
     if(a_in->im>0)
         printf("%2.2f + %2.2fi ", a_in->re,  a_in->im);
     if(a_in->im<0)
         printf("%2.2f - %2.2fi ", a_in->re, -a_in->im);
     if(a_in->re!=0 && a_in->im == 0 )
         printf("%2.2f ", a_in->re);
     if(a_in->re == 0 && a_in->im == 0)
         printf("0.00 ");
#endif
}
Ejemplo n.º 13
0
/*
 * FIXME: use module or package constants for the log levels,
 * either in pyipoptcore or in the parent package.
 * They are currently #defined in a header file.
 */
static PyObject *set_loglevel(PyObject * obj, PyObject * args)
{
	int l;
	if (!PyArg_ParseTuple(args, "i", &l)) {
		PySys_WriteStdout("l is %d \n", l);
		return NULL;
	}
	if (l < 0 || l > 2) {
		return NULL;
	}
	user_log_level = l;
	Py_INCREF(Py_True);
	return Py_True;
}
Ejemplo n.º 14
0
static _LevelData _get_level_data(pyGLTexture* self, GLint level, bool bgra, bool quiet) {
    GLint width, height;
    glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_WIDTH, &width);
    glGetTexLevelParameteriv(GL_TEXTURE_2D, level, GL_TEXTURE_HEIGHT, &height);
    GLenum fmt = bgra ? GL_BGRA_EXT : GL_RGBA;

    if (!quiet)
        PySys_WriteStdout("        Level #%i: %ix%i\n", level, width, height);

    size_t bufsz;
    bufsz = (width * height * 4);
    uint8_t* buf = new uint8_t[bufsz];
    glGetTexImage(GL_TEXTURE_2D, level, fmt, GL_UNSIGNED_BYTE, reinterpret_cast<GLvoid*>(buf));
    return _LevelData(width, height, buf, bufsz);
}
Ejemplo n.º 15
0
/*..............................................................................
. This "helper" function does the actual computations; it isn't directly
. accessed by Python.
..............................................................................*/
static void t2EA (double t, double *c, double *s) {
    double f, hi, lo, EA, W, EA_p, dE;
    int i;
    double imodf;
    double th, th2;

    double pi = 3.141592653;
    const int maxit = 20;

    /*** First, convert time to eccentric anomaly.  We just copy the t2EA
    **** code here to avoid overhead. */

    /*--- Convert time to phase mod 2*pi. */
    f = modf((t-T0)/tau, &imodf);
    if (f > 0.5) f = f - 1.;
    else if (f < -0.5) f = f + 1.;
    f = 2*pi*f;

    /*--- Initial guess and bracket for root. */
    EA = f;
    hi = pi;
    lo = - pi;

    /*--- Use Newton-Raphson; but if we jump too far, bisect. */
    for (i=1; i<=maxit; i++) {
        W = EA - e*sin(EA) - f;
        if (W < 0.) lo = EA;
        else hi = EA;
        dE = - W/(1. - e*cos(EA));
        EA_p = EA;
        EA = EA_p + dE;
        if (EA < lo || EA > hi) {
            EA = lo + 0.5*(hi-lo);
            dE = EA - EA_p;
        }
        if (fabs(dE) < err || EA == EA_p) goto EACalc;
    }
    PySys_WriteStdout("t2EA did not converge in t2EA!");
    *c = -1.;
    *s = -1.;
    return;

    /*** Now get cos & sin of TA directly from tan(phi/2). */
EACalc:
    *c = cos(EA);
    *s = sin(EA);
}
Ejemplo n.º 16
0
static PyObject *
	Package_close(PackageObject *self, PyObject *args)
{
	// Close the package.
	hlPackageClose();

	if(!self->bSilent)
		PySys_WriteStdout("%s closed.\n", self->lpPackage);

	// Free up the allocated memory.
	hlDeletePackage(self->uiPackage);	

	self->uiPackage = HL_ID_INVALID;

	Py_INCREF(Py_None);
	return Py_None;
}
Ejemplo n.º 17
0
static void
	Package_dealloc(PackageObject* self)
{
	if( self->uiPackage != HL_ID_INVALID )
	{
		// Close the package.
		hlPackageClose();

		if(!self->bSilent)
			PySys_WriteStdout("%s closed.\n", self->lpPackage);

		// Free up the allocated memory.
		hlDeletePackage(self->uiPackage);
	}

	self->ob_type->tp_free((PyObject*)self);
}
Ejemplo n.º 18
0
static PyObject *
fkepler_t2TA (PyObject *self, PyObject *args) {
    double t;
    double f, hi, lo, EA, W, EA_p, dE;
    int i;
    double imodf;
    double c, s, th, th2;

    double pi = 3.141592653;
    const int maxit = 20;

    /*** Parse the double argument. */
    Py_TRY(PyArg_ParseTuple(args, "d", &t));

    /*** First, convert time to eccentric anomaly.  We just copy the t2EA
    **** code here to avoid overhead. */

    /*--- Convert time to phase mod 2*pi. */
    f = modf((t-T0)/tau, &imodf);
    if (f > 0.5) f = f - 1.;
    else if (f < -0.5) f = f + 1.;
    f = 2*pi*f;

    /*--- Initial guess and bracket for root. */
    EA = f;
    hi = pi;
    lo = - pi;

    /*--- Use Newton-Raphson; but if we jump too far, bisect. */
    for (i=1; i<=maxit; i++) {
        W = EA - e*sin(EA) - f;
        if (W < 0.) lo = EA;
        else hi = EA;
        dE = - W/(1. - e*cos(EA));
        EA_p = EA;
        EA = EA_p + dE;
        if (EA < lo || EA > hi) {
            EA = lo + 0.5*(hi-lo);
            dE = EA - EA_p;
        }
        if (fabs(dE) < err || EA == EA_p) goto TACalc;
    }
    PySys_WriteStdout("t2EA did not converge in t2TA!");
    return NULL;

    /*** Now get cos & sin of TA directly from tan(phi/2). */
TACalc:
    if (EA == 0.) {
        c = 1.;
        s = 0.;
    }
    else if (abs(EA) == pi) {
        c = -1.;
        s = 0.;
    }
    else {
        th = sqrt((1.+e)/(1.-e)) * tan(0.5*EA);
        th2 = th*th;
        c = (1.-th2)/(1.+th2);
        s = (1.-c)/th;
    }
    return Py_BuildValue("dd", c, s);

    /** Misbehavior ends up here! */
FAIL:
    return NULL;
}
Ejemplo n.º 19
0
static PyObject *pyop_call(PyObject *UNUSED(self), PyObject *args)
{
	wmOperatorType *ot;
	int error_val = 0;
	PointerRNA ptr;
	int operator_ret = OPERATOR_CANCELLED;

	char     *opname;
	char     *context_str = NULL;
	PyObject *kw = NULL; /* optional args */
	PyObject *context_dict = NULL; /* optional args */
	PyObject *context_dict_back;

	/* note that context is an int, python does the conversion in this case */
	int context = WM_OP_EXEC_DEFAULT;
	int is_undo = false;

	/* XXX Todo, work out a better solution for passing on context,
	 * could make a tuple from self and pack the name and Context into it... */
	bContext *C = (bContext *)BPy_GetContext();
	
	if (C == NULL) {
		PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
		return NULL;
	}
	
	if (!PyArg_ParseTuple(args, "sO|O!si:_bpy.ops.call",
	                      &opname, &context_dict, &PyDict_Type, &kw, &context_str, &is_undo))
	{
		return NULL;
	}

	ot = WM_operatortype_find(opname, true);

	if (ot == NULL) {
		PyErr_Format(PyExc_AttributeError,
		             "Calling operator \"bpy.ops.%s\" error, "
		             "could not be found", opname);
		return NULL;
	}
	
	if (!pyrna_write_check()) {
		PyErr_Format(PyExc_RuntimeError,
		             "Calling operator \"bpy.ops.%s\" error, "
		             "can't modify blend data in this state (drawing/rendering)",
		             opname);
		return NULL;
	}

	if (context_str) {
		if (RNA_enum_value_from_id(operator_context_items, context_str, &context) == 0) {
			char *enum_str = BPy_enum_as_string(operator_context_items);
			PyErr_Format(PyExc_TypeError,
			             "Calling operator \"bpy.ops.%s\" error, "
			             "expected a string enum in (%.200s)",
			             opname, enum_str);
			MEM_freeN(enum_str);
			return NULL;
		}
	}

	if (context_dict == NULL || context_dict == Py_None) {
		context_dict = NULL;
	}
	else if (!PyDict_Check(context_dict)) {
		PyErr_Format(PyExc_TypeError,
		             "Calling operator \"bpy.ops.%s\" error, "
		             "custom context expected a dict or None, got a %.200s",
		             opname, Py_TYPE(context_dict)->tp_name);
		return NULL;
	}

	context_dict_back = CTX_py_dict_get(C);

	CTX_py_dict_set(C, (void *)context_dict);
	Py_XINCREF(context_dict); /* so we done loose it */

	if (WM_operator_poll_context((bContext *)C, ot, context) == false) {
		const char *msg = CTX_wm_operator_poll_msg_get(C);
		PyErr_Format(PyExc_RuntimeError,
		             "Operator bpy.ops.%.200s.poll() %.200s",
		             opname, msg ? msg : "failed, context is incorrect");
		CTX_wm_operator_poll_msg_set(C, NULL); /* better set to NULL else it could be used again */
		error_val = -1;
	}
	else {
		WM_operator_properties_create_ptr(&ptr, ot);
		WM_operator_properties_sanitize(&ptr, 0);

		if (kw && PyDict_Size(kw))
			error_val = pyrna_pydict_to_props(&ptr, kw, 0, "Converting py args to operator properties: ");


		if (error_val == 0) {
			ReportList *reports;

			reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
			BKE_reports_init(reports, RPT_STORE | RPT_OP_HOLD); /* own so these don't move into global reports */

#ifdef BPY_RELEASE_GIL
			/* release GIL, since a thread could be started from an operator
			 * that updates a driver */
			/* note: I have not seen any examples of code that does this
			 * so it may not be officially supported but seems to work ok. */
			{
				PyThreadState *ts = PyEval_SaveThread();
#endif

				operator_ret = WM_operator_call_py(C, ot, context, &ptr, reports, is_undo);

#ifdef BPY_RELEASE_GIL
				/* regain GIL */
				PyEval_RestoreThread(ts);
			}
#endif

			error_val = BPy_reports_to_error(reports, PyExc_RuntimeError, false);

			/* operator output is nice to have in the terminal/console too */
			if (reports->list.first) {
				char *report_str = BKE_reports_string(reports, 0); /* all reports */
	
				if (report_str) {
					PySys_WriteStdout("%s\n", report_str);
					MEM_freeN(report_str);
				}
			}
	
			BKE_reports_clear(reports);
			if ((reports->flag & RPT_FREE) == 0) {
				MEM_freeN(reports);
			}
		}

		WM_operator_properties_free(&ptr);

#if 0
		/* if there is some way to know an operator takes args we should use this */
		{
			/* no props */
			if (kw != NULL) {
				PyErr_Format(PyExc_AttributeError,
				             "Operator \"%s\" does not take any args",
				             opname);
				return NULL;
			}

			WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
		}
#endif
	}

	/* restore with original context dict, probably NULL but need this for nested operator calls */
	Py_XDECREF(context_dict);
	CTX_py_dict_set(C, (void *)context_dict_back);

	if (error_val == -1) {
		return NULL;
	}

	/* when calling  bpy.ops.wm.read_factory_settings() bpy.data's main pointer is freed by clear_globals(),
	 * further access will crash blender. setting context is not needed in this case, only calling because this
	 * function corrects bpy.data (internal Main pointer) */
	BPY_modules_update(C);

	/* needed for when WM_OT_read_factory_settings us called from within a script */
	bpy_import_main_set(CTX_data_main(C));

	/* return operator_ret as a bpy enum */
	return pyrna_enum_bitfield_to_py(operator_return_items, operator_ret);

}
Ejemplo n.º 20
0
static PyObject * MidiListener_play(MidiListener *self) {
    int i, num_devices;
    PmError pmerr;

    /* always start the timer before you start midi */
    Pt_Start(1, &process_midi, (void *)self);
    
    pmerr = Pm_Initialize();
    if (pmerr) {
        PySys_WriteStdout("Portmidi warning: could not initialize Portmidi: %s\n", Pm_GetErrorText(pmerr));
    }

    num_devices = Pm_CountDevices();
    if (num_devices > 0) {
        if (self->mididev < num_devices) {
            if (self->mididev == -1)
                self->mididev = Pm_GetDefaultInputDeviceID();
            const PmDeviceInfo *info = Pm_GetDeviceInfo(self->mididev);
            if (info != NULL) {
                if (info->input) {
                    pmerr = Pm_OpenInput(&self->midiin[0], self->mididev, NULL, 100, NULL, NULL);
                    if (pmerr) {
                        PySys_WriteStdout("Portmidi warning: could not open midi input %d (%s): %s\n",
                             self->mididev, info->name, Pm_GetErrorText(pmerr));
                    }
                    else {
                        self->midicount = 1;
                    }
                }
            }
        }
        else if (self->mididev >= num_devices) {
            self->midicount = 0;
            for (i=0; i<num_devices; i++) {
                const PmDeviceInfo *info = Pm_GetDeviceInfo(i);
                if (info != NULL) {
                    if (info->input) {
                        pmerr = Pm_OpenInput(&self->midiin[self->midicount], i, NULL, 100, NULL, NULL);
                        if (pmerr) {
                            PySys_WriteStdout("Portmidi warning: could not open midi input %d (%s): %s\n",
                                    i, info->name, Pm_GetErrorText(pmerr));
                        }
                        else {
                            self->midicount++;
                        }
                    }
                }
            }
        }
    }

    for (i=0; i<self->midicount; i++) {
        Pm_SetFilter(self->midiin[i], PM_FILT_ACTIVE | PM_FILT_CLOCK);
    }

    if (self->midicount > 0)
        self->active = 1;

	Py_INCREF(Py_None);
	return Py_None;
};
Ejemplo n.º 21
0
static int
	Package_init(PackageObject *self, PyObject *args, PyObject *kwds)
{
	int volatileaccess;

	static char *kwlist[] = {"packagename", "volatileaccess", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|i", kwlist, 
                                     &self->lpPackage, &volatileaccess))
	{
		return -1;
	}

	self->bVolatileAccess = volatileaccess;
	/*
	if (!PyArg_ParseTuple(args, "s", &self->lpPackage))
	{
		return -1;
	}*/
	
	// Get the package type from the filename extension.
	self->ePackageType = hlGetPackageTypeFromName(self->lpPackage);

	// If the above fails, try getting the package type from the data at the start of the file.
	if(self->ePackageType == HL_PACKAGE_NONE)
	{
		self->pFile = fopen(self->lpPackage, "rb");
		if(self->pFile != 0)
		{
			hlByte lpBuffer[HL_DEFAULT_PACKAGE_TEST_BUFFER_SIZE];

			hlUInt uiBufferSize = (hlUInt)fread(lpBuffer, 1, HL_DEFAULT_PACKAGE_TEST_BUFFER_SIZE, self->pFile);

			self->ePackageType = hlGetPackageTypeFromMemory(lpBuffer, uiBufferSize);

			fclose(self->pFile);
			self->pFile = 0;
		}
	}

	if(self->ePackageType == HL_PACKAGE_NONE)
	{
		PyErr_Format(PyExc_Exception, "Error loading %s:\nUnsupported package type.\n", self->lpPackage);
		return -1;
	}

	// Create a package element, the element is allocated by the library and cleaned
	// up by the library.  An ID is generated which must be bound to apply operations
	// to the package.
	if(!hlCreatePackage(self->ePackageType, &self->uiPackage))
	{
		PyErr_Format(PyExc_Exception, "Error loading %s:\n%s\n", self->lpPackage, hlGetString(HL_ERROR_SHORT_FORMATED));
		return -1;
	}

	hlBindPackage(self->uiPackage);

	self->uiMode = HL_MODE_READ | (self->bDefragment ? HL_MODE_WRITE : 0);
	self->uiMode |= !self->bFileMapping ? HL_MODE_NO_FILEMAPPING : 0;
	self->uiMode |= self->bQuickFileMapping ? HL_MODE_QUICK_FILEMAPPING : 0;
	self->uiMode |= self->bVolatileAccess ? HL_MODE_VOLATILE : 0;

	// Open the package.
	// Of the above modes, only HL_MODE_READ is required.  HL_MODE_WRITE is present
	// only for future use.  File mapping is recommended as an efficient way to load
	// packages.  Quick file mapping maps the entire file (instead of bits as they are
	// needed) and thus should only be used in Windows 2000 and up (older versions of
	// Windows have poor virtual memory management which means large files won't be able
	// to find a continues block and will fail to load).  Volatile access allows HLLib
	// to share files with other applications that have those file open for writing.
	// This is useful for, say, loading .gcf files while Steam is running.
	if(!hlPackageOpenFile(self->lpPackage, self->uiMode))
	{
		PyErr_Format(PyExc_Exception, "Error loading %s:\n%s\n", self->lpPackage, hlGetString(HL_ERROR_SHORT_FORMATED));

		return -1;
	}

	if(!self->bSilent)
		PySys_WriteStdout("%s opened.\n", self->lpPackage);

	// Package opened!

	return 0;
}
Ejemplo n.º 22
0
hlVoid ExtractItemEndCallback(HLDirectoryItem *pItem, hlBool bSuccess)
{
#if 0
	PyEval_RestoreThread(g_extract_save);

	hlUInt uiSize = 0;
	hlChar lpPath[512] = "";

	if( pEndExtractFunc == Py_None )
	{
		if(bSuccess)
		{
			if(!bSilent)
			{
				hlItemGetSize(pItem, &uiSize);
				if(hlItemGetType(pItem) == HL_ITEM_FILE)
				{
					PySys_WriteStdout("OK");
					PySys_WriteStdout(" (%u B)\n", uiSize);
				}
				else
				{
					PySys_WriteStdout("  Done %s: ", hlItemGetName(pItem));
					PySys_WriteStdout("OK");
					PySys_WriteStdout(" (%u B)\n", uiSize);
				}
			}
		}
		else
		{
			if(!bSilent)
			{
				if(hlItemGetType(pItem) == HL_ITEM_FILE)
				{
					PySys_WriteStdout("Errored\n");
					PySys_WriteStdout("    %s\n", hlGetString(HL_ERROR_SHORT_FORMATED));
				}
				else
				{
					PySys_WriteStdout("  Done %s: ", hlItemGetName(pItem));
					PySys_WriteStdout("Errored\n");
				}
			}
			else
			{
				hlItemGetPath(pItem, lpPath, sizeof(lpPath));
				if(hlItemGetType(pItem) == HL_ITEM_FILE)
				{
					PySys_WriteStdout("  Error extracting %s:\n", lpPath);
					PySys_WriteStdout("    %s\n", hlGetString(HL_ERROR_SHORT_FORMATED));
				}
				else
				{
					PySys_WriteStdout("  Error extracting %s.\n", lpPath);
				}
			}
		}
	}
	else
	{
		hlItemGetSize(pItem, &uiSize);
		hlItemGetPath(pItem, lpPath, sizeof(lpPath));

		PyEval_CallFunction(pEndExtractFunc, "bsisIs", bSuccess, hlItemGetName(pItem), hlItemGetType(pItem), lpPath, uiSize, bSuccess ? "" : hlGetString(HL_ERROR_SHORT_FORMATED));
	}

	g_extract_save = PyEval_SaveThread();
#endif // 0
	hlUInt uiSize = 0;
	hlChar lpPath[512] = "";

	if(hlItemGetType(pItem) == HL_ITEM_FILE) 
	{
		hlItemGetSize(pItem, &uiSize);

		g_bytesExtracted += uiSize;

		if( g_bytesExtracted > 10000000 && pUpdateFunc != Py_None )
		{
			hlItemGetPath(pItem, lpPath, sizeof(lpPath));

			PyEval_RestoreThread(g_extract_save);
			PyEval_CallFunction(pUpdateFunc, "bsisIs", bSuccess, hlItemGetName(pItem), hlItemGetType(pItem), lpPath, g_bytesExtracted, bSuccess ? "" : hlGetString(HL_ERROR_SHORT_FORMATED));
			g_extract_save = PyEval_SaveThread();

			g_bytesExtracted = 0;
		}
	}
}
Ejemplo n.º 23
0
HLValidation Validate(PackageObject *self, HLDirectoryItem *pItem)
{
	hlUInt i, uiItemCount;
	hlChar lpPath[512] = "";
	HLValidation eValidation = HL_VALIDATES_OK, eTest;

	switch(hlItemGetType(pItem))
	{
	case HL_ITEM_FOLDER:
		if(!self->bSilent)
		{
			PySys_WriteStdout("  Validating %s:\n", hlItemGetName(pItem));
		}

		uiItemCount = hlFolderGetCount(pItem);
		for(i = 0; i < uiItemCount; i++)
		{
			eTest = Validate(self, hlFolderGetItem(pItem, i));
			if(eTest > eValidation)
			{
				eValidation = eTest;
			}
		}

		if(!self->bSilent)
		{
			PySys_WriteStdout("  Done %s: ", hlItemGetName(pItem));
			PrintValidation(eValidation);
			PySys_WriteStdout("\n");
		}
		break;
	case HL_ITEM_FILE:
		if(!self->bSilent)
		{
			PySys_WriteStdout("  Validating %s: ", hlItemGetName(pItem));
			//ProgressStart();
		}

		eValidation = hlFileGetValidation(pItem);

		if(self->bSilent)
		{
			switch(eValidation)
			{
			case HL_VALIDATES_INCOMPLETE:
			case HL_VALIDATES_CORRUPT:
				hlItemGetPath(pItem, lpPath, sizeof(lpPath));
				PySys_WriteStdout("  Validating %s: ", lpPath);
				PrintValidation(eValidation);
				PySys_WriteStdout("\n");
				break;
			}
		}
		else
		{
			PrintValidation(eValidation);
			PySys_WriteStdout("  \n");
		}
		break;
	}

	return eValidation;
}
Ejemplo n.º 24
0
static void to_stdout(const char *text)
{
     PySys_WriteStdout("%s", text);     
}
Ejemplo n.º 25
0
void
jack_error_cb(const char *desc) {
    PySys_WriteStdout("JACK error: %s\n", desc);
}