Gui/ApplicationPy.cpp

Go to the documentation of this file.
00001 /***************************************************************************
00002  *   Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net>     *
00003  *                                                                         *
00004  *   This file is part of the FreeCAD CAx development system.              *
00005  *                                                                         *
00006  *   This library is free software; you can redistribute it and/or         *
00007  *   modify it under the terms of the GNU Library General Public           *
00008  *   License as published by the Free Software Foundation; either          *
00009  *   version 2 of the License, or (at your option) any later version.      *
00010  *                                                                         *
00011  *   This library  is distributed in the hope that it will be useful,      *
00012  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
00013  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
00014  *   GNU Library General Public License for more details.                  *
00015  *                                                                         *
00016  *   You should have received a copy of the GNU Library General Public     *
00017  *   License along with this library; see the file COPYING.LIB. If not,    *
00018  *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
00019  *   Suite 330, Boston, MA  02111-1307, USA                                *
00020  *                                                                         *
00021  ***************************************************************************/
00022 
00023 
00024 #include "PreCompiled.h"
00025 
00026 #ifndef _PreComp_
00027 # include <qfileinfo.h>
00028 # include <qdir.h>
00029 #endif
00030 
00031 
00032 #include "Application.h"
00033 #include "BitmapFactory.h"
00034 #include "Command.h"
00035 #include "Document.h"
00036 #include "MainWindow.h"
00037 #include "EditorView.h"
00038 #include "PythonEditor.h"
00039 #include "WidgetFactory.h"
00040 #include "Workbench.h"
00041 #include "WorkbenchManager.h"
00042 #include "Language/Translator.h"
00043 #include <App/DocumentObjectPy.h>
00044 #include <App/PropertyFile.h>
00045 #include <Base/Interpreter.h>
00046 #include <Base/Console.h>
00047 #include <CXX/Objects.hxx>
00048 
00049 using namespace Gui;
00050 
00051 // FCApplication Methods                                                // Methods structure
00052 PyMethodDef Application::Methods[] = {
00053   {"activateWorkbench",(PyCFunction) Application::sActivateWorkbenchHandler,1,
00054    "activateWorkbench(string) -> None\n\n"
00055    "Activate the workbench by name"},
00056   {"addWorkbench",     (PyCFunction) Application::sAddWorkbenchHandler,     1,
00057    "addWorkbench(string, object) -> None\n\n"
00058    "Add a workbench under a defined name."},
00059   {"removeWorkbench",  (PyCFunction) Application::sRemoveWorkbenchHandler,  1,
00060    "removeWorkbench(string) -> None\n\n"
00061    "Remove the workbench with name"},
00062   {"getWorkbench",     (PyCFunction) Application::sGetWorkbenchHandler,     1,
00063    "getWorkbench(string) -> object\n\n"
00064    "Get the workbench by its name"},
00065   {"listWorkbenches",   (PyCFunction) Application::sListWorkbenchHandlers,    1,
00066    "listWorkbenches() -> list\n\n"
00067    "Show a list of all workbenches"},
00068   {"activeWorkbench", (PyCFunction) Application::sActiveWorkbenchHandler,   1,
00069    "activeWorkbench() -> object\n\n"
00070    "Return the active workbench object"},
00071   {"addResourcePath",             (PyCFunction) Application::sAddResPath,      1,
00072    "addResourcePath(string) -> None\n\n"
00073    "Add a new path to the system where to find resource files\n"
00074    "like icons or localization files"},
00075   {"addLanguagePath",             (PyCFunction) Application::sAddLangPath,      1,
00076    "addLanguagePath(string) -> None\n\n"
00077    "Add a new path to the system where to find language files"},
00078   {"addIconPath",             (PyCFunction) Application::sAddIconPath,      1,
00079    "addIconPath(string) -> None\n\n"
00080    "Add a new path to the system where to find icon files"},
00081   {"addIcon",                 (PyCFunction) Application::sAddIcon,          1,
00082    "addIcon(string, string or list) -> None\n\n"
00083    "Add an icon as file name or in XPM format to the system"},
00084   {"updateGui",               (PyCFunction) Application::sUpdateGui,        1,
00085    "updateGui() -> None\n\n"
00086    "Update the main window and all its windows"},
00087   {"updateLocale",            (PyCFunction) Application::sUpdateLocale,     1,
00088    "updateLocale() -> None\n\n"
00089    "Update the localization"},
00090   {"getLocale",            (PyCFunction) Application::sGetLocale,     1,
00091    "getLocale() -> string\n\n"
00092    "Returns the locale currently used by FreeCAD"},
00093   {"createDialog",            (PyCFunction) Application::sCreateDialog,     1,
00094    "createDialog(string) -- Open a UI file"},
00095   {"addPreferencePage",       (PyCFunction) Application::sAddPreferencePage,1,
00096    "addPreferencePage(string,string) -- Add a UI form to the\n"
00097    "preferences dialog. The first argument specifies the file name"
00098    "and the second specifies the group name"},
00099   {"addCommand",              (PyCFunction) Application::sAddCommand,       1,
00100    "addCommand(string, object) -> None\n\n"
00101    "Add a command object"},
00102   {"runCommand",              (PyCFunction) Application::sRunCommand,       1,
00103    "runCommand(string) -> None\n\n"
00104    "Run command with name"},
00105   {"SendMsgToActiveView",     (PyCFunction) Application::sSendActiveView,   1,
00106    "deprecated -- use class View"},
00107   {"hide",                    (PyCFunction) Application::sHide,             1,
00108    "deprecated"},
00109   {"show",                    (PyCFunction) Application::sShow,             1,
00110    "deprecated"},
00111   {"hideObject",              (PyCFunction) Application::sHideObject,       1,
00112    "hideObject(object) -> None\n\n"
00113    "Hide the view provider to the given object"},
00114   {"showObject",              (PyCFunction) Application::sShowObject,       1,
00115    "showObject(object) -> None\n\n"
00116    "Show the view provider to the given object"},
00117   {"open",                    (PyCFunction) Application::sOpen,             1,
00118    "Open a macro, Inventor or VRML file"},
00119   {"insert",                  (PyCFunction) Application::sInsert,           1,
00120    "Open a macro, Inventor or VRML file"},
00121   {"export",                  (PyCFunction) Application::sExport,           1,
00122    "save scene to Inventor or VRML file"},
00123   {"activeDocument",          (PyCFunction) Application::sActiveDocument,   1,
00124    "activeDocument() -> object or None\n\n"
00125    "Return the active document or None if no one exists"},
00126   {"getDocument",             (PyCFunction) Application::sGetDocument,      1,
00127    "getDocument(string) -> object\n\n"
00128    "Get a document by its name"},
00129 
00130   {NULL, NULL}          /* Sentinel */
00131 };
00132 
00133 PyObject* Gui::Application::sActiveDocument(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00134 {
00135     if (!PyArg_ParseTuple(args, ""))     // convert args: Python->C 
00136         return NULL;                       // NULL triggers exception 
00137 
00138     Document *pcDoc = Instance->activeDocument();
00139     if (pcDoc) {
00140         return pcDoc->getPyObject();
00141     } else {
00142         Py_Return;
00143     }
00144 }
00145 
00146 PyObject* Application::sGetDocument(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00147 {
00148     char *pstr=0;
00149     if (!PyArg_ParseTuple(args, "s", &pstr))     // convert args: Python->C 
00150         return NULL;                             // NULL triggers exception
00151 
00152     Document *pcDoc = Instance->getDocument(pstr);
00153     if (!pcDoc) {
00154         PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr);
00155         return 0;
00156     }
00157 
00158     return pcDoc->getPyObject();
00159 }
00160 
00161 PyObject* Application::sHide(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00162 {
00163     char *psFeatStr;
00164     if (!PyArg_ParseTuple(args, "s;Name of the object to hide has to be given!",&psFeatStr))     // convert args: Python->C 
00165         return NULL;                                      // NULL triggers exception 
00166 
00167     Document *pcDoc = Instance->activeDocument();
00168 
00169     if (pcDoc)
00170         pcDoc->setHide(psFeatStr);
00171 
00172     Py_Return;
00173 }
00174 
00175 PyObject* Application::sShow(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00176 {
00177     char *psFeatStr;
00178     if (!PyArg_ParseTuple(args, "s;Name of the object to show has to be given!",&psFeatStr))     // convert args: Python->C 
00179         return NULL;                                      // NULL triggers exception 
00180 
00181     Document *pcDoc = Instance->activeDocument();
00182 
00183     if (pcDoc)
00184         pcDoc->setShow(psFeatStr);
00185 
00186     Py_Return;
00187 }
00188 
00189 PyObject* Application::sHideObject(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00190 {
00191     PyObject *object;
00192     if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&object))
00193         return 0;
00194 
00195     App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(object)->getDocumentObjectPtr();
00196     Instance->hideViewProvider(obj);
00197 
00198     Py_Return;
00199 }
00200 
00201 PyObject* Application::sShowObject(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00202 {
00203     PyObject *object;
00204     if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&object))
00205         return 0;
00206 
00207     App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(object)->getDocumentObjectPtr();
00208     Instance->showViewProvider(obj);
00209 
00210     Py_Return;
00211 }
00212 
00213 PyObject* Application::sOpen(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00214 {
00215     // only used to open Python files
00216     const char* Name;
00217     if (!PyArg_ParseTuple(args, "s",&Name))
00218         return NULL;
00219     PY_TRY {
00220         QString fileName = QString::fromUtf8(Name);
00221         QFileInfo fi;
00222         fi.setFile(fileName);
00223         QString ext = fi.completeSuffix().toLower();
00224         QList<EditorView*> views = getMainWindow()->findChildren<EditorView*>();
00225         for (QList<EditorView*>::Iterator it = views.begin(); it != views.end(); ++it) {
00226             if ((*it)->fileName() == fileName) {
00227                 (*it)->setFocus();
00228                 Py_Return;
00229             }
00230         }
00231 
00232         if (ext == QLatin1String("iv")) {
00233             if (!Application::Instance->activeDocument())
00234                 App::GetApplication().newDocument();
00235             //QString cmd = QString("Gui.activeDocument().addAnnotation(\"%1\",\"%2\")").arg(fi.baseName()).arg(fi.absoluteFilePath());
00236             QString cmd = QString::fromLatin1(
00237                 "App.ActiveDocument.addObject(\"App::InventorObject\",\"%1\")."
00238                 "FileName=\"%2\"\n"
00239                 "App.ActiveDocument.ActiveObject.Label=\"%1\"\n"
00240                 "App.ActiveDocument.recompute()")
00241                 .arg(fi.baseName()).arg(fi.absoluteFilePath());
00242             Base::Interpreter().runString(cmd.toUtf8());
00243         }
00244         else if (ext == QLatin1String("wrl") ||
00245                  ext == QLatin1String("vrml") ||
00246                  ext == QLatin1String("wrz")) {
00247             if (!Application::Instance->activeDocument())
00248                 App::GetApplication().newDocument();
00249             //QString cmd = QString("Gui.activeDocument().addAnnotation(\"%1\",\"%2\")").arg(fi.baseName()).arg(fi.absoluteFilePath());
00250             QString cmd = QString::fromLatin1(
00251                 "App.ActiveDocument.addObject(\"App::VRMLObject\",\"%1\")."
00252                 "VrmlFile=\"%2\"\n"
00253                 "App.ActiveDocument.ActiveObject.Label=\"%1\"\n"
00254                 "App.ActiveDocument.recompute()")
00255                 .arg(fi.baseName()).arg(fi.absoluteFilePath());
00256             Base::Interpreter().runString(cmd.toUtf8());
00257         }
00258         else if (ext == QLatin1String("py") || ext == QLatin1String("fcmacro") ||
00259                  ext == QLatin1String("fcscript")) {
00260             PythonEditor* editor = new PythonEditor();
00261             editor->setWindowIcon(Gui::BitmapFactory().pixmap("python_small"));
00262             PythonEditorView* edit = new PythonEditorView(editor, getMainWindow());
00263             edit->open(fileName);
00264             edit->resize(400, 300);
00265             getMainWindow()->addWindow( edit );
00266         }
00267     } PY_CATCH;
00268 
00269     Py_Return;
00270 }
00271 
00272 PyObject* Application::sInsert(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00273 {
00274     const char* Name;
00275     const char* DocName=0;
00276     if (!PyArg_ParseTuple(args, "s|s",&Name,&DocName))
00277         return NULL;
00278 
00279     PY_TRY {
00280         QString fileName = QString::fromUtf8(Name);
00281         QFileInfo fi;
00282         fi.setFile(fileName);
00283         QString ext = fi.completeSuffix().toLower();
00284         if (ext == QLatin1String("iv")) {
00285             App::Document *doc = 0;
00286             if (DocName)
00287                 doc = App::GetApplication().getDocument(DocName);
00288             else
00289                 doc = App::GetApplication().getActiveDocument();
00290             if (!doc)
00291                 doc = App::GetApplication().newDocument(DocName);
00292 
00293             App::DocumentObject* obj = doc->addObject("App::InventorObject",
00294                 (const char*)fi.baseName().toUtf8());
00295             obj->Label.setValue((const char*)fi.baseName().toUtf8());
00296             static_cast<App::PropertyString*>(obj->getPropertyByName("FileName"))
00297                 ->setValue((const char*)fi.absoluteFilePath().toUtf8());
00298             doc->recompute();
00299         }
00300         else if (ext == QLatin1String("wrl") ||
00301                  ext == QLatin1String("vrml") ||
00302                  ext == QLatin1String("wrz")) {
00303             App::Document *doc = 0;
00304             if (DocName)
00305                 doc = App::GetApplication().getDocument(DocName);
00306             else
00307                 doc = App::GetApplication().getActiveDocument();
00308             if (!doc)
00309                 doc = App::GetApplication().newDocument(DocName);
00310 
00311             App::DocumentObject* obj = doc->addObject("App::VRMLObject",
00312                 (const char*)fi.baseName().toUtf8());
00313             obj->Label.setValue((const char*)fi.baseName().toUtf8());
00314             static_cast<App::PropertyFileIncluded*>(obj->getPropertyByName("VrmlFile"))
00315                 ->setValue((const char*)fi.absoluteFilePath().toUtf8());
00316             doc->recompute();
00317         }
00318         else if (ext == QLatin1String("py") || ext == QLatin1String("fcmacro") ||
00319                  ext == QLatin1String("fcscript")) {
00320             PythonEditor* editor = new PythonEditor();
00321             editor->setWindowIcon(Gui::BitmapFactory().pixmap("python_small"));
00322             PythonEditorView* edit = new PythonEditorView(editor, getMainWindow());
00323             edit->open(fileName);
00324             edit->resize(400, 300);
00325             getMainWindow()->addWindow( edit );
00326         }
00327     } PY_CATCH;
00328 
00329     Py_Return;
00330 }
00331 
00332 PyObject* Application::sExport(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00333 {
00334     PyObject* object;
00335     const char* filename;
00336     if (!PyArg_ParseTuple(args, "Os",&object,&filename))
00337         return NULL;
00338 
00339     PY_TRY {
00340         App::Document* doc = 0;
00341         Py::List list(object);
00342         for (Py::List::iterator it = list.begin(); it != list.end(); ++it) {
00343             PyObject* item = (*it).ptr();
00344             if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
00345                 App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
00346                 doc = obj->getDocument();
00347                 break;
00348             }
00349         }
00350 
00351         // get the view that belongs to the found document
00352         if (doc) {
00353             QString fileName = QString::fromUtf8(filename);
00354             QFileInfo fi;
00355             fi.setFile(fileName);
00356             QString ext = fi.completeSuffix().toLower();
00357             if (ext == QLatin1String("iv") || ext == QLatin1String("wrl") ||
00358                 ext == QLatin1String("vrml") || ext == QLatin1String("wrz") ||
00359                 ext == QLatin1String("svg") || ext == QLatin1String("idtf")) {
00360                 QString cmd = QString::fromLatin1(
00361                     "Gui.getDocument(\"%1\").ActiveView.dump(\"%2\")"
00362                     ).arg(QLatin1String(doc->getName())).arg(fi.absoluteFilePath());
00363                 Base::Interpreter().runString(cmd.toUtf8());
00364             }
00365         }
00366     } PY_CATCH;
00367 
00368     Py_Return;
00369 }
00370 
00371 PyObject* Application::sSendActiveView(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00372 {
00373     char *psCommandStr;
00374     if (!PyArg_ParseTuple(args, "s",&psCommandStr))     // convert args: Python->C 
00375         return NULL;                                      // NULL triggers exception 
00376 
00377     const char* ppReturn=0;
00378     if (!Instance->sendMsgToActiveView(psCommandStr,&ppReturn))
00379         Base::Console().Warning("Unknown view command: %s\n",psCommandStr);
00380 
00381     // Print the return value to the output
00382     if (ppReturn) {
00383         return Py_BuildValue("s",ppReturn);
00384     }
00385 
00386     Py_INCREF(Py_None);
00387     return Py_None;
00388 } 
00389 
00390 PyObject* Application::sUpdateGui(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00391 {
00392     if (!PyArg_ParseTuple(args, ""))     // convert args: Python->C 
00393         return NULL;                                      // NULL triggers exception 
00394 
00395     qApp->processEvents();
00396 
00397     Py_INCREF(Py_None);
00398     return Py_None;
00399 } 
00400 
00401 PyObject* Application::sUpdateLocale(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00402 {
00403     if (!PyArg_ParseTuple(args, ""))     // convert args: Python->C 
00404         return NULL;                                      // NULL triggers exception 
00405 
00406     Translator::instance()->refresh();
00407 
00408     Py_INCREF(Py_None);
00409     return Py_None;
00410 } 
00411 
00412 PyObject* Application::sGetLocale(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00413 {
00414     if (!PyArg_ParseTuple(args, ""))     // convert args: Python->C 
00415         return NULL;                                      // NULL triggers exception 
00416 
00417     std::string locale = Translator::instance()->activeLanguage();
00418     return PyString_FromString(locale.c_str());
00419 } 
00420 
00421 PyObject* Application::sCreateDialog(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00422 {
00423     char* fn = 0;
00424     if (!PyArg_ParseTuple(args, "s", &fn))     // convert args: Python->C 
00425         return NULL;                                      // NULL triggers exception 
00426 
00427     PyObject* pPyResource=0L;
00428     try{
00429         pPyResource = new PyResource();
00430         ((PyResource*)pPyResource)->load(fn);
00431     }
00432     catch (const Base::Exception& e) {
00433         PyErr_SetString(PyExc_AssertionError, e.what());
00434         return NULL;
00435     }
00436 
00437     return pPyResource;
00438 } 
00439 
00440 PyObject* Application::sAddPreferencePage(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00441 {
00442     char *fn, *grp;
00443     if (!PyArg_ParseTuple(args, "ss", &fn,&grp))     // convert args: Python->C 
00444         return NULL;                                      // NULL triggers exception 
00445 
00446     QFileInfo fi(QString::fromUtf8(fn));
00447     if (!fi.exists()) {
00448         PyErr_SetString(PyExc_RuntimeError, "UI file does not exist");
00449         return 0;
00450     }
00451 
00452     // add to the preferences dialog
00453     new PrefPageUiProducer(fn, grp);
00454 
00455     Py_INCREF(Py_None);
00456     return Py_None;
00457 } 
00458 
00459 PyObject* Application::sActivateWorkbenchHandler(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00460 {
00461     char*       psKey;
00462     if (!PyArg_ParseTuple(args, "s", &psKey))     // convert args: Python->C 
00463         return NULL;                    // NULL triggers exception 
00464 
00465     // search for workbench handler from the dictionary
00466     PyObject* pcWorkbench = PyDict_GetItemString(Instance->_pcWorkbenchDictionary, psKey);
00467     if (!pcWorkbench) {
00468         PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
00469         return NULL;
00470     }
00471 
00472     Instance->activateWorkbench(psKey);
00473 
00474     Py_INCREF(Py_None);
00475     return Py_None;
00476 } 
00477 
00478 PyObject* Application::sAddWorkbenchHandler(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00479 {
00480     PyObject*   pcObject;
00481     std::string item;
00482     if (!PyArg_ParseTuple(args, "O", &pcObject))     // convert args: Python->C 
00483         return NULL;                    // NULL triggers exception 
00484 
00485     try {
00486         // get the class object 'Workbench' from the main module that is expected
00487         // to be base class for all workbench classes
00488         Py::Module module("__main__");
00489         Py::Object baseclass(module.getAttr(std::string("Workbench")));
00490         
00491         // check whether it is an instance or class object
00492         Py::Object object(pcObject);
00493         Py::String name;
00494         
00495         if (PyObject_IsSubclass(object.ptr(), baseclass.ptr()) == 1) {
00496             // create an instance of this class
00497             name = object.getAttr(std::string("__name__"));
00498             Py::Tuple args;
00499             Py::Callable creation(object);
00500             object = creation.apply(args);
00501         }
00502         else if (PyObject_IsInstance(object.ptr(), baseclass.ptr()) == 1) {
00503             // extract the class name of the instance
00504             PyErr_Clear(); // PyObject_IsSubclass set an exception
00505             Py::Object classobj = object.getAttr(std::string("__class__"));
00506             name = classobj.getAttr(std::string("__name__"));
00507         }
00508         else {
00509             PyErr_SetString(PyExc_TypeError, "arg must be a subclass or an instance of "
00510                                              "a subclass of 'Workbench'");
00511             return NULL;
00512         }
00513 
00514         // Search for some methods and members without invoking them
00515         Py::Callable(object.getAttr(std::string("Initialize")));
00516         Py::Callable(object.getAttr(std::string("GetClassName")));
00517         item = name.as_std_string();
00518 
00519         PyObject* wb = PyDict_GetItemString(Instance->_pcWorkbenchDictionary,item.c_str()); 
00520         if (wb) {
00521             PyErr_Format(PyExc_KeyError, "'%s' already exists.", item.c_str());
00522             return NULL;
00523         }
00524 
00525         PyDict_SetItemString(Instance->_pcWorkbenchDictionary,item.c_str(),object.ptr());
00526         Instance->signalAddWorkbench(item.c_str());
00527     }
00528     catch (const Py::Exception&) {
00529         return NULL;
00530     }
00531 
00532     Py_INCREF(Py_None);
00533     return Py_None;
00534 }
00535 
00536 PyObject* Application::sRemoveWorkbenchHandler(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00537 {
00538     char*       psKey;
00539     if (!PyArg_ParseTuple(args, "s", &psKey))     // convert args: Python->C 
00540         return NULL;                    // NULL triggers exception 
00541 
00542     PyObject* wb = PyDict_GetItemString(Instance->_pcWorkbenchDictionary,psKey); 
00543     if (!wb) {
00544         PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
00545         return NULL;
00546     }
00547 
00548     Instance->signalRemoveWorkbench(psKey);
00549     WorkbenchManager::instance()->removeWorkbench(psKey);
00550     PyDict_DelItemString(Instance->_pcWorkbenchDictionary,psKey);
00551 
00552     Py_INCREF(Py_None);
00553     return Py_None;
00554 } 
00555 
00556 PyObject* Application::sGetWorkbenchHandler(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00557 {
00558     char* psKey;
00559     if (!PyArg_ParseTuple(args, "s", &psKey))     // convert args: Python->C 
00560         return NULL;                                // NULL triggers exception 
00561    
00562     // get the python workbench object from the dictionary
00563     PyObject* pcWorkbench = PyDict_GetItemString(Instance->_pcWorkbenchDictionary, psKey);
00564     if (!pcWorkbench) {
00565         PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
00566         return NULL;
00567     }
00568 
00569     Py_INCREF(pcWorkbench);
00570     return pcWorkbench;
00571 } 
00572 
00573 PyObject* Application::sListWorkbenchHandlers(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00574 {
00575     Py_INCREF(Instance->_pcWorkbenchDictionary);
00576     return Instance->_pcWorkbenchDictionary;
00577 } 
00578 
00579 PyObject* Application::sActiveWorkbenchHandler(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00580 {
00581     if (!PyArg_ParseTuple(args, ""))     // convert args: Python->C 
00582         return NULL;                       // NULL triggers exception 
00583 
00584     Workbench* actWb = WorkbenchManager::instance()->active();
00585     if (!actWb) {
00586         PyErr_SetString(PyExc_AssertionError, "No active workbench\n");         
00587         return NULL;
00588     }
00589 
00590     // get the python workbench object from the dictionary
00591     std::string key = actWb->name();
00592     PyObject* pcWorkbench = PyDict_GetItemString(Instance->_pcWorkbenchDictionary, key.c_str());
00593     if (!pcWorkbench) {
00594         PyErr_Format(PyExc_KeyError, "No such workbench '%s'", key.c_str());
00595         return NULL;
00596     }
00597 
00598     // object get incremented
00599     Py_INCREF(pcWorkbench);
00600     return pcWorkbench;
00601 } 
00602 
00603 PyObject* Application::sAddResPath(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00604 {
00605     char* filePath;
00606     if (!PyArg_ParseTuple(args, "s", &filePath))     // convert args: Python->C
00607         return NULL;                    // NULL triggers exception
00608     QString path = QString::fromUtf8(filePath);
00609     if (QDir::isRelativePath(path)) {
00610         // Home path ends with '/'
00611         QString home = QString::fromUtf8(App::GetApplication().GetHomePath());
00612         path = home + path;
00613     }
00614 
00615     BitmapFactory().addPath(path);
00616     Translator::instance()->addPath(path);
00617     Py_INCREF(Py_None);
00618     return Py_None;
00619 }
00620 
00621 PyObject* Application::sAddLangPath(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00622 {
00623     char* filePath;
00624     if (!PyArg_ParseTuple(args, "s", &filePath))     // convert args: Python->C
00625         return NULL;                    // NULL triggers exception
00626     QString path = QString::fromUtf8(filePath);
00627     if (QDir::isRelativePath(path)) {
00628         // Home path ends with '/'
00629         QString home = QString::fromUtf8(App::GetApplication().GetHomePath());
00630         path = home + path;
00631     }
00632 
00633     Translator::instance()->addPath(path);
00634     Py_INCREF(Py_None);
00635     return Py_None;
00636 }
00637 
00638 PyObject* Application::sAddIconPath(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00639 {
00640     char* filePath;
00641     if (!PyArg_ParseTuple(args, "s", &filePath))     // convert args: Python->C 
00642         return NULL;                    // NULL triggers exception 
00643     QString path = QString::fromUtf8(filePath);
00644     if (QDir::isRelativePath(path)) {
00645         // Home path ends with '/'
00646         QString home = QString::fromUtf8(App::GetApplication().GetHomePath());
00647         path = home + path;
00648     }
00649 
00650     BitmapFactory().addPath(path);
00651     Py_INCREF(Py_None);
00652     return Py_None;
00653 }
00654 
00655 PyObject* Application::sAddIcon(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00656 {
00657     char *iconName;
00658     char *pixmap;
00659     if (!PyArg_ParseTuple(args, "ss", &iconName,&pixmap))     // convert args: Python->C 
00660         return NULL;                    // NULL triggers exception 
00661     
00662     QPixmap icon;
00663     if (BitmapFactory().findPixmapInCache(iconName, icon)) {
00664         PyErr_SetString(PyExc_AssertionError, "Icon with this name already registered");
00665         return NULL;
00666     }
00667 
00668     QByteArray ary;
00669     std::string content = pixmap;
00670     int strlen = (int)content.size();
00671     ary.resize(strlen);
00672     for (int j=0; j<strlen; j++)
00673         ary[j]=content[j];
00674     icon.loadFromData(ary, "XPM");
00675 
00676     if (icon.isNull()){
00677         QString file = QString::fromUtf8(pixmap);
00678         icon.load(file);
00679     }
00680 
00681     if (icon.isNull()) {
00682         PyErr_SetString(PyExc_Exception, "Invalid icon added to application");
00683         return NULL;
00684     }
00685 
00686     BitmapFactory().addPixmapToCache(iconName, icon);
00687 
00688     Py_INCREF(Py_None);
00689     return Py_None;
00690 }
00691 
00692 PyObject* Application::sAddCommand(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00693 {
00694     char*       pName;
00695     char*       pSource=0;
00696     PyObject*   pcCmdObj;
00697     if (!PyArg_ParseTuple(args, "sO|s", &pName,&pcCmdObj,&pSource))     // convert args: Python->C 
00698         return NULL;                    // NULL triggers exception 
00699 #if 0
00700     std::string source = (pSource ? pSource : "");
00701 
00702     if (source.empty()) {
00703         try {
00704             Py::Module module(PyImport_ImportModule("inspect"),true);
00705             Py::Dict dict = module.getDict();
00706             Py::Callable call(dict.getItem("getsourcelines"));
00707             Py::Tuple arg(1);
00708             arg.setItem(0, Py::Object(pcCmdObj).getAttr("Activated"));
00709             Py::Tuple tuple(call.apply(arg));
00710             Py::List lines(tuple[0]);
00711 
00712             int pos=0;
00713             std::string code = (std::string)(Py::String(lines[1]));
00714             while (code[pos] == ' ' || code[pos] == '\t')
00715                 pos++;
00716             for (Py::List::iterator it = lines.begin()+1; it != lines.end(); ++it) {
00717                 Py::String str(*it);
00718                 source += ((std::string)str).substr(pos);
00719             }
00720         }
00721         catch (Py::Exception& e) {
00722             e.clear();
00723         }
00724     }
00725 
00726     Application::Instance->commandManager().addCommand(new PythonCommand(pName,pcCmdObj,source.c_str()));
00727 #else
00728     Application::Instance->commandManager().addCommand(new PythonCommand(pName,pcCmdObj,pSource));
00729 #endif
00730     Py_INCREF(Py_None);
00731     return Py_None;
00732 }
00733 
00734 PyObject* Application::sRunCommand(PyObject * /*self*/, PyObject *args,PyObject * /*kwd*/)
00735 {
00736     char*       pName;
00737     if (!PyArg_ParseTuple(args, "s", &pName))     // convert args: Python->C 
00738         return NULL;                    // NULL triggers exception 
00739 
00740     Command* cmd = Application::Instance->commandManager().getCommandByName(pName);
00741     if (cmd) {
00742         cmd->invoke(0);
00743         Py_INCREF(Py_None);
00744         return Py_None;
00745     }
00746     else {
00747         PyErr_Format(PyExc_Exception, "No such command '%s'", pName);
00748         return 0;
00749     }
00750 } 

Generated on Wed Nov 23 18:59:56 2011 for FreeCAD by  doxygen 1.6.1