Debian Codegraph @

src/App/ApplicationPy.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU Library General Public License (LGPL) *
8 * as published by the Free Software Foundation; either version 2 of *
9 * the License, or (at your option) any later version. *
10 * for detail see the LICENCE text file. *
11 * *
12 * FreeCAD is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU Library General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU Library General Public *
18 * License along with FreeCAD; if not, write to the Free Software *
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
20 * USA *
21 * *
22 ***************************************************************************/
23
24 #include <FCConfig.h>
25
26 #include <Base/Console.h>
27 #include <Base/Exception.h>
28 #include <Base/FileInfo.h>
29 #include <Base/Interpreter.h>
30 #include <Base/Parameter.h>
31 #include <Base/PyWrapParseTupleAndKeywords.h>
32 #include <Base/Sequencer.h>
33
34 #include "Application.h"
35 #include "DocumentPy.h"
36 #include "DocumentObserverPython.h"
37 #include "DocumentObjectPy.h"
38
39
40 // using Base::GetConsole;
41 using namespace Base;
42 using namespace App;
43
44
45 //**************************************************************************
46 // Python stuff
47
48 // Application methods structure
49 PyMethodDef Application::Methods[] = {
50 {"ParamGet", (PyCFunction)Application::sGetParam, METH_VARARGS, "Get parameters by path"},
51 {"saveParameter",
52 (PyCFunction)Application::sSaveParameter,
53 METH_VARARGS,
54 "saveParameter(config='User parameter') -> None\n"
55 "Save parameter set to file. The default set is 'User parameter'"},
56 {"Version",
57 (PyCFunction)Application::sGetVersion,
58 METH_VARARGS,
59 "Print the version to the output."},
60 {"ConfigGet",
61 (PyCFunction)Application::sGetConfig,
62 METH_VARARGS,
63 "ConfigGet(string) -- Get the value for the given key."},
64 {"ConfigSet",
65 (PyCFunction)Application::sSetConfig,
66 METH_VARARGS,
67 "ConfigSet(string, string) -- Set the given key to the given value."},
68 {"ConfigDump",
69 (PyCFunction)Application::sDumpConfig,
70 METH_VARARGS,
71 "Dump the configuration to the output."},
72 {"addImportType",
73 (PyCFunction)Application::sAddImportType,
74 METH_VARARGS,
75 "Register filetype for import"},
76 {"changeImportModule",
77 (PyCFunction)Application::sChangeImportModule,
78 METH_VARARGS,
79 "Change the import module name of a registered filetype"},
80 {"getImportType",
81 (PyCFunction)Application::sGetImportType,
82 METH_VARARGS,
83 "Get the name of the module that can import the filetype"},
84 {"addExportType",
85 (PyCFunction)Application::sAddExportType,
86 METH_VARARGS,
87 "Register filetype for export"},
88 {"changeExportModule",
89 (PyCFunction)Application::sChangeExportModule,
90 METH_VARARGS,
91 "Change the export module name of a registered filetype"},
92 {"getExportType",
93 (PyCFunction)Application::sGetExportType,
94 METH_VARARGS,
95 "Get the name of the module that can export the filetype"},
96 {"getResourceDir",
97 (PyCFunction)Application::sGetResourcePath,
98 METH_VARARGS,
99 "Get the root directory of all resources"},
100 {"getLibraryDir",
101 (PyCFunction)Application::sGetLibraryPath,
102 METH_VARARGS,
103 "Get the directory of all extension modules"},
104 {"getTempPath",
105 (PyCFunction)Application::sGetTempPath,
106 METH_VARARGS,
107 "Get the root directory of cached files"},
108 {"getUserCachePath",
109 (PyCFunction)Application::sGetUserCachePath,
110 METH_VARARGS,
111 "Get the root path of cached files"},
112 {"getUserConfigDir",
113 (PyCFunction)Application::sGetUserConfigPath,
114 METH_VARARGS,
115 "Get the root path of user config files"},
116 {"getUserAppDataDir",
117 (PyCFunction)Application::sGetUserAppDataPath,
118 METH_VARARGS,
119 "Get the root directory of application data"},
120 {"getUserMacroDir",
121 (PyCFunction)Application::sGetUserMacroPath,
122 METH_VARARGS,
123 "getUserMacroDir(bool=False) -> str\n\n"
124 "Get the directory of the user's macro directory\n"
125 "If parameter is False (the default) it returns the standard path in the"
126 "user's home directory, otherwise it returns the user-defined path."},
127 {"getHelpDir",
128 (PyCFunction)Application::sGetHelpPath,
129 METH_VARARGS,
130 "Get the directory of the documentation"},
131 {"getHomePath",
132 (PyCFunction)Application::sGetHomePath,
133 METH_VARARGS,
134 "Get the home path, i.e. the parent directory of the executable"},
135
136 {"loadFile",
137 (PyCFunction)Application::sLoadFile,
138 METH_VARARGS,
139 "loadFile(string=filename,[string=module]) -> None\n\n"
140 "Loads an arbitrary file by delegating to the given Python module:\n"
141 "* If no module is given it will be determined by the file extension.\n"
142 "* If more than one module can load a file the first one will be taken.\n"
143 "* If no module exists to load the file an exception will be raised."},
144 {"open",
145 reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(Application::sOpenDocument)),
146 METH_VARARGS | METH_KEYWORDS,
147 "See openDocument(string)"},
148 {"openDocument",
149 reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(Application::sOpenDocument)),
150 METH_VARARGS | METH_KEYWORDS,
151 "openDocument(filepath,hidden=False,temporary=False) -> object\n"
152 "Create a document and load the project file into the document.\n\n"
153 "filepath: file path to an existing file. If the file doesn't exist\n"
154 " or the file cannot be loaded an I/O exception is thrown.\n"
155 " In this case the document is kept alive.\n"
156 "hidden: whether to hide document 3D view.\n"
157 "temporary: whether to hide document in the tree view."},
158 // {"saveDocument", (PyCFunction) Application::sSaveDocument, METH_VARARGS,
159 // "saveDocument(string) -- Save the document to a file."},
160 // {"saveDocumentAs", (PyCFunction) Application::sSaveDocumentAs, METH_VARARGS},
161 {"newDocument",
162 reinterpret_cast<PyCFunction>(reinterpret_cast<void (*)()>(Application::sNewDocument)),
163 METH_VARARGS | METH_KEYWORDS,
164 "newDocument(name, label=None, hidden=False, temp=False) -> object\n"
165 "Create a new document with a given name.\n\n"
166 "name: unique document name which is checked automatically.\n"
167 "label: optional user changeable label for the document.\n"
168 "hidden: whether to hide document 3D view.\n"
169 "temp: mark the document as temporary so that it will not be saved"},
170 {"closeDocument",
171 (PyCFunction)Application::sCloseDocument,
172 METH_VARARGS,
173 "closeDocument(string) -> None\n\n"
174 "Close the document with a given name."},
175 {"activeDocument",
176 (PyCFunction)Application::sActiveDocument,
177 METH_VARARGS,
178 "activeDocument() -> object or None\n\n"
179 "Return the active document or None if there is no one."},
180 {"setActiveDocument",
181 (PyCFunction)Application::sSetActiveDocument,
182 METH_VARARGS,
183 "setActiveDocement(string) -> None\n\n"
184 "Set the active document by its name."},
185 {"getDocument",
186 (PyCFunction)Application::sGetDocument,
187 METH_VARARGS,
188 "getDocument(string) -> object\n\n"
189 "Get a document by its name or raise an exception\n"
190 "if there is no document with the given name."},
191 {"listDocuments",
192 (PyCFunction)Application::sListDocuments,
193 METH_VARARGS,
194 "listDocuments(sort=False) -> list\n\n"
195 "Return a list of names of all documents, optionally sort in dependency order."},
196 {"addDocumentObserver",
197 (PyCFunction)Application::sAddDocObserver,
198 METH_VARARGS,
199 "addDocumentObserver() -> None\n\n"
200 "Add an observer to get notified about changes on documents."},
201 {"removeDocumentObserver",
202 (PyCFunction)Application::sRemoveDocObserver,
203 METH_VARARGS,
204 "removeDocumentObserver() -> None\n\n"
205 "Remove an added document observer."},
206 {"setLogLevel",
207 (PyCFunction)Application::sSetLogLevel,
208 METH_VARARGS,
209 "setLogLevel(tag, level) -- Set the log level for a string tag.\n"
210 "'level' can either be string 'Log', 'Msg', 'Wrn', 'Error', or an integer value"},
211 {"getLogLevel",
212 (PyCFunction)Application::sGetLogLevel,
213 METH_VARARGS,
214 "getLogLevel(tag) -- Get the log level of a string tag"},
215 {"checkLinkDepth",
216 (PyCFunction)Application::sCheckLinkDepth,
217 METH_VARARGS,
218 "checkLinkDepth(depth) -- check link recursion depth"},
219 {"getLinksTo",
220 (PyCFunction)Application::sGetLinksTo,
221 METH_VARARGS,
222 "getLinksTo(obj,options=0,maxCount=0) -- return the objects linked to 'obj'\n\n"
223 "options: 1: recursive, 2: check link array. Options can combine.\n"
224 "maxCount: to limit the number of links returned\n"},
225 {"getDependentObjects",
226 (PyCFunction)Application::sGetDependentObjects,
227 METH_VARARGS,
228 "getDependentObjects(obj|[obj,...], options=0)\n"
229 "Return a list of dependent objects including the given objects.\n\n"
230 "options: can have the following bit flags,\n"
231 " 1: to sort the list in topological order.\n"
232 " 2: to exclude dependency of Link type object."},
233 {"setActiveTransaction",
234 (PyCFunction)Application::sSetActiveTransaction,
235 METH_VARARGS,
236 "setActiveTransaction(name, persist=False) -- setup active transaction with the given name\n\n"
237 "name: the transaction name\n"
238 "persist(False): by default, if the calling code is inside any invocation of a command, it\n"
239 " will be auto closed once all commands within the current stack exists. To\n"
240 " disable auto closing, set persist=True\n"
241 "Returns the transaction ID for the active transaction. An application-wide\n"
242 "active transaction causes any document changes to open a transaction with\n"
243 "the given name and ID."},
244 {"getActiveTransaction",
245 (PyCFunction)Application::sGetActiveTransaction,
246 METH_VARARGS,
247 "getActiveTransaction() -> (name,id)\n\n"
248 "return the current active transaction name and ID"},
249 {"closeActiveTransaction",
250 (PyCFunction)Application::sCloseActiveTransaction,
251 METH_VARARGS,
252 "closeActiveTransaction(abort=False) -- commit or abort current active transaction"},
253 {"isRestoring",
254 (PyCFunction)Application::sIsRestoring,
255 METH_VARARGS,
256 "isRestoring() -> bool\n\n"
257 "Test if the application is opening some document"},
258 {"checkAbort",
259 (PyCFunction)Application::sCheckAbort,
260 METH_VARARGS,
261 "checkAbort() -- check for user abort in length operation.\n\n"
262 "This only works if there is an active sequencer (or ProgressIndicator in Python).\n"
263 "There is an active sequencer during document restore and recomputation. User may\n"
264 "abort the operation by pressing the ESC key. Once detected, this function will\n"
265 "trigger a Base.FreeCADAbort exception."},
266 {nullptr, nullptr, 0, nullptr} /* Sentinel */
267 };
268
269
270 PyObject* Application::sLoadFile(PyObject* /*self*/, PyObject* args)
271 {
272 const char* path;
273 const char* doc = "";
274 const char* mod = "";
275 if (!PyArg_ParseTuple(args, "s|ss", &path, &doc, &mod)) {
276 return nullptr;
277 }
278 try {
279 Base::FileInfo fi(path);
280 if (!fi.isFile() || !fi.exists()) {
281 PyErr_Format(PyExc_IOError, "File %s doesn't exist.", path);
282 return nullptr;
283 }
284
285 std::string module = mod;
286 if (module.empty()) {
287 std::string ext = fi.extension();
288 std::vector<std::string> modules = GetApplication().getImportModules(ext.c_str());
289 if (modules.empty()) {
290 PyErr_Format(PyExc_IOError, "Filetype %s is not supported.", ext.c_str());
291 return nullptr;
292 }
293 else {
294 module = modules.front();
295 }
296 }
297
298 // path and doc could contain characters that need escaping, such as quote signs
299 // therefore use their repr() in the Python code string
300 auto pathRepr = static_cast<std::string>(Py::String(path).repr());
301 auto docRepr = static_cast<std::string>(Py::String(doc).repr());
302
303 std::stringstream str;
304 str << "import " << module << std::endl;
305 if (fi.hasExtension("FCStd")) {
306 str << module << ".openDocument(" << pathRepr << ")" << std::endl;
307 }
308 else {
309 str << module << ".insert(" << pathRepr << "," << docRepr << ")" << std::endl;
310 }
311
312 Base::Interpreter().runString(str.str().c_str());
313 Py_Return;
314 }
315 catch (const Base::Exception& e) {
316 e.setPyException();
317 return nullptr;
318 }
319 catch (const std::exception& e) {
320 // might be subclass from zipios
321 PyErr_Format(PyExc_IOError, "Invalid project file %s: %s", path, e.what());
322 return nullptr;
323 }
324 }
325
326 PyObject* Application::sIsRestoring(PyObject* /*self*/, PyObject* args)
327 {
328 if (!PyArg_ParseTuple(args, "")) {
329 return nullptr;
330 }
331 return Py::new_reference_to(Py::Boolean(GetApplication().isRestoring()));
332 }
333
334 PyObject* Application::sOpenDocument(PyObject* /*self*/, PyObject* args, PyObject* kwd)
335 {
336 char* Name;
337 PyObject* hidden = Py_False;
338 PyObject* temporary = Py_False;
339 static const std::array<const char*, 4> kwlist {"name", "hidden", "temporary", nullptr};
340 if (!Base::Wrapped_ParseTupleAndKeywords(args,
341 kwd,
342 "et|O!O!",
343 kwlist,
344 "utf-8",
345 &Name,
346 &PyBool_Type,
347 &hidden,
348 &PyBool_Type,
349 &temporary)) {
350 return nullptr;
351 }
352 std::string EncodedName = std::string(Name);
353 PyMem_Free(Name);
354 try {
355 DocumentInitFlags initFlags {
356 .createView = !Base::asBoolean(hidden),
357 .temporary = Base::asBoolean(temporary)
358 };
359
360 // return new document
361 return (GetApplication()
362 .openDocument(EncodedName.c_str(), initFlags)
363 ->getPyObject());
364 }
365 catch (const Base::Exception& e) {
366 PyErr_SetString(PyExc_IOError, e.what());
367 return nullptr;
368 }
369 catch (const std::exception& e) {
370 // might be subclass from zipios
371 PyErr_Format(PyExc_IOError, "Invalid project file %s: %s\n", EncodedName.c_str(), e.what());
372 return nullptr;
373 }
374 }
375
376 PyObject* Application::sNewDocument(PyObject* /*self*/, PyObject* args, PyObject* kwd)
377 {
378 char* docName = nullptr;
379 char* usrName = nullptr;
380 PyObject* hidden = Py_False;
381 PyObject* temp = Py_False;
382 static const std::array<const char*, 5> kwlist {"name", "label", "hidden", "temp", nullptr};
383 if (!Base::Wrapped_ParseTupleAndKeywords(args,
384 kwd,
385 "|etetO!O!",
386 kwlist,
387 "utf-8",
388 &docName,
389 "utf-8",
390 &usrName,
391 &PyBool_Type,
392 &hidden,
393 &PyBool_Type,
394 &temp)) {
395 return nullptr;
396 }
397
398 PY_TRY
399 {
400 DocumentInitFlags initFlags {
401 .createView = !Base::asBoolean(hidden),
402 .temporary = Base::asBoolean(temp)
403 };
404 App::Document* doc = GetApplication().newDocument(docName,
405 usrName,
406 initFlags);
407 PyMem_Free(docName);
408 PyMem_Free(usrName);
409 return doc->getPyObject();
410 }
411 PY_CATCH;
412 }
413
414 PyObject* Application::sSetActiveDocument(PyObject* /*self*/, PyObject* args)
415 {
416 char* pstr = nullptr;
417 if (!PyArg_ParseTuple(args, "s", &pstr)) {
418 return nullptr;
419 }
420
421 try {
422 GetApplication().setActiveDocument(pstr);
423 }
424 catch (const Base::Exception& e) {
425 e.setPyException();
426 return nullptr;
427 }
428
429 Py_Return;
430 }
431
432 PyObject* Application::sCloseDocument(PyObject* /*self*/, PyObject* args)
433 {
434 char* pstr = nullptr;
435 if (!PyArg_ParseTuple(args, "s", &pstr)) {
436 return nullptr;
437 }
438
439 Document* doc = GetApplication().getDocument(pstr);
440 if (!doc) {
441 PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr);
442 return nullptr;
443 }
444 if (!doc->isClosable()) {
445 PyErr_Format(PyExc_RuntimeError, "The document '%s' is not closable for the moment", pstr);
446 return nullptr;
447 }
448
449 if (!GetApplication().closeDocument(pstr)) {
450 PyErr_Format(PyExc_RuntimeError, "Closing the document '%s' failed", pstr);
451 return nullptr;
452 }
453
454 Py_Return;
455 }
456
457 PyObject* Application::sSaveDocument(PyObject* /*self*/, PyObject* args)
458 {
459 char* pDoc;
460 if (!PyArg_ParseTuple(args, "s", &pDoc)) {
461 return nullptr;
462 }
463
464 Document* doc = GetApplication().getDocument(pDoc);
465 if (doc) {
466 if (!doc->save()) {
467 PyErr_Format(Base::PyExc_FC_GeneralError, "Cannot save document '%s'", pDoc);
468 return nullptr;
469 }
470 }
471 else {
472 PyErr_Format(PyExc_NameError, "Unknown document '%s'", pDoc);
473 return nullptr;
474 }
475
476 Py_Return;
477 }
478
479 PyObject* Application::sActiveDocument(PyObject* /*self*/, PyObject* args)
480 {
481 if (!PyArg_ParseTuple(args, "")) {
482 return nullptr;
483 }
484
485 Document* doc = GetApplication().getActiveDocument();
486 if (doc) {
487 return doc->getPyObject();
488 }
489 else {
490 Py_INCREF(Py_None);
491 return Py_None;
492 }
493 }
494
495 PyObject* Application::sGetDocument(PyObject* /*self*/, PyObject* args)
496 {
497 char* pstr = nullptr;
498 if (!PyArg_ParseTuple(args, "s", &pstr)) {
499 return nullptr;
500 }
501
502 Document* doc = GetApplication().getDocument(pstr);
503 if (!doc) {
504 PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr);
505 return nullptr;
506 }
507
508 return doc->getPyObject();
509 }
510
511 PyObject* Application::sGetParam(PyObject* /*self*/, PyObject* args)
512 {
513 char* pstr = nullptr;
514 if (!PyArg_ParseTuple(args, "s", &pstr)) {
515 return nullptr;
516 }
517
518 PY_TRY
519 {
520 return GetPyObject(GetApplication().GetParameterGroupByPath(pstr));
521 }
522 PY_CATCH;
523 }
524
525 PyObject* Application::sSaveParameter(PyObject* /*self*/, PyObject* args)
526 {
527 const char* pstr = "User parameter";
528 if (!PyArg_ParseTuple(args, "|s", &pstr)) {
529 return nullptr;
530 }
531
532 PY_TRY
533 {
534 ParameterManager* param = App::GetApplication().GetParameterSet(pstr);
535 if (!param) {
536 std::stringstream str;
537 str << "No parameter set found with name: " << pstr;
538 PyErr_SetString(PyExc_ValueError, str.str().c_str());
539 return nullptr;
540 }
541 else if (!param->HasSerializer()) {
542 std::stringstream str;
543 str << "Parameter set cannot be serialized: " << pstr;
544 PyErr_SetString(PyExc_RuntimeError, str.str().c_str());
545 return nullptr;
546 }
547
548 param->SaveDocument();
549 Py_INCREF(Py_None);
550 return Py_None;
551 }
552 PY_CATCH;
553 }
554
555
556 PyObject* Application::sGetConfig(PyObject* /*self*/, PyObject* args)
557 {
558 char* pstr;
559
560 if (!PyArg_ParseTuple(args, "s", &pstr)) {
561 return nullptr;
562 }
563 const std::map<std::string, std::string>& Map = GetApplication().Config();
564
565 std::map<std::string, std::string>::const_iterator it = Map.find(pstr);
566 if (it != Map.end()) {
567 return Py_BuildValue("s", it->second.c_str());
568 }
569 else {
570 // do not set an error because this may break existing python code
571 return PyUnicode_FromString("");
572 }
573 }
574
575 PyObject* Application::sDumpConfig(PyObject* /*self*/, PyObject* args)
576 {
577 if (!PyArg_ParseTuple(args, "")) {
578 return nullptr;
579 }
580
581 PyObject* dict = PyDict_New();
582 for (const auto& It : GetApplication()._mConfig) {
583 PyDict_SetItemString(dict, It.first.c_str(), PyUnicode_FromString(It.second.c_str()));
584 }
585 return dict;
586 }
587
588 PyObject* Application::sSetConfig(PyObject* /*self*/, PyObject* args)
589 {
590 char *pstr, *pstr2;
591
592 if (!PyArg_ParseTuple(args, "ss", &pstr, &pstr2)) {
593 return nullptr;
594 }
595
596 GetApplication()._mConfig[pstr] = pstr2;
597
598 Py_INCREF(Py_None);
599 return Py_None;
600 }
601
602 PyObject* Application::sGetVersion(PyObject* /*self*/, PyObject* args)
603 {
604 if (!PyArg_ParseTuple(args, "")) {
605 return nullptr;
606 }
607
608 Py::List list;
609 const std::map<std::string, std::string>& cfg = Application::Config();
610 std::map<std::string, std::string>::const_iterator it;
611
612 it = cfg.find("BuildVersionMajor");
613 list.append(Py::String(it != cfg.end() ? it->second : ""));
614
615 it = cfg.find("BuildVersionMinor");
616 list.append(Py::String(it != cfg.end() ? it->second : ""));
617
618 it = cfg.find("BuildVersionPoint");
619 list.append(Py::String(it != cfg.end() ? it->second : ""));
620
621 it = cfg.find("BuildRevision");
622 list.append(Py::String(it != cfg.end() ? it->second : ""));
623
624 it = cfg.find("BuildRepositoryURL");
625 list.append(Py::String(it != cfg.end() ? it->second : ""));
626
627 it = cfg.find("BuildRevisionDate");
628 list.append(Py::String(it != cfg.end() ? it->second : ""));
629
630 it = cfg.find("BuildRevisionBranch");
631 if (it != cfg.end()) {
632 list.append(Py::String(it->second));
633 }
634
635 it = cfg.find("BuildRevisionHash");
636 if (it != cfg.end()) {
637 list.append(Py::String(it->second));
638 }
639
640 return Py::new_reference_to(list);
641 }
642
643 PyObject* Application::sAddImportType(PyObject* /*self*/, PyObject* args)
644 {
645 char *psKey, *psMod;
646
647 if (!PyArg_ParseTuple(args, "ss", &psKey, &psMod)) {
648 return nullptr;
649 }
650
651 GetApplication().addImportType(psKey, psMod);
652
653 Py_Return;
654 }
655
656 PyObject* Application::sChangeImportModule(PyObject* /*self*/, PyObject* args)
657 {
658 char *key, *oldMod, *newMod;
659
660 if (!PyArg_ParseTuple(args, "sss", &key, &oldMod, &newMod)) {
661 return nullptr;
662 }
663
664 GetApplication().changeImportModule(key, oldMod, newMod);
665
666 Py_Return;
667 }
668
669 PyObject* Application::sGetImportType(PyObject* /*self*/, PyObject* args)
670 {
671 char* psKey = nullptr;
672
673 if (!PyArg_ParseTuple(args, "|s", &psKey)) {
674 return nullptr;
675 }
676
677 if (psKey) {
678 Py::List list;
679 std::vector<std::string> modules = GetApplication().getImportModules(psKey);
680 for (const auto& it : modules) {
681 list.append(Py::String(it));
682 }
683
684 return Py::new_reference_to(list);
685 }
686 else {
687 Py::Dict dict;
688 std::vector<std::string> types = GetApplication().getImportTypes();
689 for (const auto& it : types) {
690 std::vector<std::string> modules = GetApplication().getImportModules(it.c_str());
691 if (modules.empty()) {
692 dict.setItem(it.c_str(), Py::None());
693 }
694 else if (modules.size() == 1) {
695 dict.setItem(it.c_str(), Py::String(modules.front()));
696 }
697 else {
698 Py::List list;
699 for (const auto& jt : modules) {
700 list.append(Py::String(jt));
701 }
702 dict.setItem(it.c_str(), list);
703 }
704 }
705
706 return Py::new_reference_to(dict);
707 }
708 }
709
710 PyObject* Application::sAddExportType(PyObject* /*self*/, PyObject* args)
711 {
712 char *psKey, *psMod;
713
714 if (!PyArg_ParseTuple(args, "ss", &psKey, &psMod)) {
715 return nullptr;
716 }
717
718 GetApplication().addExportType(psKey, psMod);
719
720 Py_Return;
721 }
722
723 PyObject* Application::sChangeExportModule(PyObject* /*self*/, PyObject* args)
724 {
725 char *key, *oldMod, *newMod;
726
727 if (!PyArg_ParseTuple(args, "sss", &key, &oldMod, &newMod)) {
728 return nullptr;
729 }
730
731 GetApplication().changeExportModule(key, oldMod, newMod);
732
733 Py_Return;
734 }
735
736 PyObject* Application::sGetExportType(PyObject* /*self*/, PyObject* args)
737 {
738 char* psKey = nullptr;
739
740 if (!PyArg_ParseTuple(args, "|s", &psKey)) {
741 return nullptr;
742 }
743
744 if (psKey) {
745 Py::List list;
746 std::vector<std::string> modules = GetApplication().getExportModules(psKey);
747 for (const auto& it : modules) {
748 list.append(Py::String(it));
749 }
750
751 return Py::new_reference_to(list);
752 }
753 else {
754 Py::Dict dict;
755 std::vector<std::string> types = GetApplication().getExportTypes();
756 for (const auto& it : types) {
757 std::vector<std::string> modules = GetApplication().getExportModules(it);
758 if (modules.empty()) {
759 dict.setItem(it.c_str(), Py::None());
760 }
761 else if (modules.size() == 1) {
762 dict.setItem(it.c_str(), Py::String(modules.front()));
763 }
764 else {
765 Py::List list;
766 for (const auto& jt : modules) {
767 list.append(Py::String(jt));
768 }
769 dict.setItem(it.c_str(), list);
770 }
771 }
772
773 return Py::new_reference_to(dict);
774 }
775 }
776
777 PyObject* Application::sGetResourcePath(PyObject* /*self*/, PyObject* args)
778 {
779 if (!PyArg_ParseTuple(args, "")) {
780 return nullptr;
781 }
782
783 Py::String datadir(Application::getResourceDir(), "utf-8");
784 return Py::new_reference_to(datadir);
785 }
786
787 PyObject* Application::sGetLibraryPath(PyObject* /*self*/, PyObject* args)
788 {
789 if (!PyArg_ParseTuple(args, "")) {
790 return nullptr;
791 }
792
793 Py::String datadir(Application::getLibraryDir(), "utf-8");
794 return Py::new_reference_to(datadir);
795 }
796
797 PyObject* Application::sGetTempPath(PyObject* /*self*/, PyObject* args)
798 {
799 if (!PyArg_ParseTuple(args, "")) {
800 return nullptr;
801 }
802
803 Py::String datadir(Application::getTempPath(), "utf-8");
804 return Py::new_reference_to(datadir);
805 }
806
807 PyObject* Application::sGetUserCachePath(PyObject* /*self*/, PyObject* args)
808 {
809 if (!PyArg_ParseTuple(args, "")) {
810 return nullptr;
811 }
812
813 Py::String datadir(Application::getUserCachePath(), "utf-8");
814 return Py::new_reference_to(datadir);
815 }
816
817 PyObject* Application::sGetUserConfigPath(PyObject* /*self*/, PyObject* args)
818 {
819 if (!PyArg_ParseTuple(args, "")) {
820 return nullptr;
821 }
822
823 Py::String datadir(Application::getUserConfigPath(), "utf-8");
824 return Py::new_reference_to(datadir);
825 }
826
827 PyObject* Application::sGetUserAppDataPath(PyObject* /*self*/, PyObject* args)
828 {
829 if (!PyArg_ParseTuple(args, "")) {
830 return nullptr;
831 }
832
833 Py::String user_data_dir(Application::getUserAppDataDir(), "utf-8");
834 return Py::new_reference_to(user_data_dir);
835 }
836
837 PyObject* Application::sGetUserMacroPath(PyObject* /*self*/, PyObject* args)
838 {
839 PyObject* actual = Py_False;
840 if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &actual)) {
841 return nullptr;
842 }
843
844 std::string macroDir = Application::getUserMacroDir();
845 if (Base::asBoolean(actual)) {
846 macroDir = App::GetApplication()
847 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro")
848 ->GetASCII("MacroPath", macroDir.c_str());
849 std::replace(macroDir.begin(), macroDir.end(), '/', PATHSEP);
850 }
851
852 Py::String user_macro_dir(macroDir, "utf-8");
853 return Py::new_reference_to(user_macro_dir);
854 }
855
856 PyObject* Application::sGetHelpPath(PyObject* /*self*/, PyObject* args)
857 {
858 if (!PyArg_ParseTuple(args, "")) {
859 return nullptr;
860 }
861
862 Py::String user_macro_dir(Application::getHelpDir(), "utf-8");
863 return Py::new_reference_to(user_macro_dir);
864 }
865
866 PyObject* Application::sGetHomePath(PyObject* /*self*/, PyObject* args)
867 {
868 if (!PyArg_ParseTuple(args, "")) {
869 return nullptr;
870 }
871
872 Py::String homedir(Application::getHomePath(), "utf-8");
873 return Py::new_reference_to(homedir);
874 }
875
876 PyObject* Application::sListDocuments(PyObject* /*self*/, PyObject* args)
877 {
878 PyObject* sort = Py_False;
879 if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &sort)) {
880 return nullptr;
881 }
882 PY_TRY
883 {
884 PyObject* pDict = PyDict_New();
885 PyObject* pKey;
886 Base::PyObjectBase* pValue;
887
888 std::vector<Document*> docs = GetApplication().getDocuments();
889 ;
890 if (Base::asBoolean(sort)) {
891 docs = Document::getDependentDocuments(docs, true);
892 }
893
894 for (auto doc : docs) {
895 pKey = PyUnicode_FromString(doc->getName());
896 // GetPyObject() increments
897 pValue = static_cast<Base::PyObjectBase*>(doc->getPyObject());
898 PyDict_SetItem(pDict, pKey, pValue);
899 // now we can decrement again as PyDict_SetItem also has incremented
900 pValue->DecRef();
901 }
902
903 return pDict;
904 }
905 PY_CATCH;
906 }
907
908 PyObject* Application::sAddDocObserver(PyObject* /*self*/, PyObject* args)
909 {
910 PyObject* o;
911 if (!PyArg_ParseTuple(args, "O", &o)) {
912 return nullptr;
913 }
914 PY_TRY
915 {
916 DocumentObserverPython::addObserver(Py::Object(o));
917 Py_Return;
918 }
919 PY_CATCH;
920 }
921
922 PyObject* Application::sRemoveDocObserver(PyObject* /*self*/, PyObject* args)
923 {
924 PyObject* o;
925 if (!PyArg_ParseTuple(args, "O", &o)) {
926 return nullptr;
927 }
928 PY_TRY
929 {
930 DocumentObserverPython::removeObserver(Py::Object(o));
931 Py_Return;
932 }
933 PY_CATCH;
934 }
935
936 PyObject* Application::sSetLogLevel(PyObject* /*self*/, PyObject* args)
937 {
938 char* tag;
939 PyObject* pcObj;
940 if (!PyArg_ParseTuple(args, "sO", &tag, &pcObj)) {
941 return nullptr;
942 }
943 PY_TRY
944 {
945 int l;
946 if (PyUnicode_Check(pcObj)) {
947 const char* pstr = PyUnicode_AsUTF8(pcObj);
948 if (strcmp(pstr, "Log") == 0) {
949 l = FC_LOGLEVEL_LOG;
950 }
951 else if (strcmp(pstr, "Warning") == 0) {
952 l = FC_LOGLEVEL_WARN;
953 }
954 else if (strcmp(pstr, "Message") == 0) {
955 l = FC_LOGLEVEL_MSG;
956 }
957 else if (strcmp(pstr, "Error") == 0) {
958 l = FC_LOGLEVEL_ERR;
959 }
960 else if (strcmp(pstr, "Trace") == 0) {
961 l = FC_LOGLEVEL_TRACE;
962 }
963 else if (strcmp(pstr, "Default") == 0) {
964 l = FC_LOGLEVEL_DEFAULT;
965 }
966 else {
967 Py_Error(PyExc_ValueError,
968 "Unknown Log Level (use 'Default', 'Error', 'Warning', 'Message', 'Log', "
969 "'Trace' or an integer)");
970 return nullptr;
971 }
972 }
973 else {
974 l = PyLong_AsLong(pcObj);
975 }
976 GetApplication()
977 .GetParameterGroupByPath("User parameter:BaseApp/LogLevels")
978 ->SetInt(tag, l);
979 if (strcmp(tag, "Default") == 0) {
980 #ifndef FC_DEBUG
981 if (l >= 0) {
982 Base::Console().setDefaultLogLevel(l);
983 }
984 #endif
985 }
986 else if (strcmp(tag, "DebugDefault") == 0) {
987 #ifdef FC_DEBUG
988 if (l >= 0) {
989 Base::Console().setDefaultLogLevel(l);
990 }
991 #endif
992 }
993 else {
994 *Base::Console().getLogLevel(tag) = l;
995 }
996 Py_INCREF(Py_None);
997 return Py_None;
998 }
999 PY_CATCH;
1000 }
1001
1002 PyObject* Application::sGetLogLevel(PyObject* /*self*/, PyObject* args)
1003 {
1004 char* tag;
1005 if (!PyArg_ParseTuple(args, "s", &tag)) {
1006 return nullptr;
1007 }
1008
1009 PY_TRY
1010 {
1011 int l = -1;
1012 if (strcmp(tag, "Default") == 0) {
1013 #ifdef FC_DEBUG
1014 l = _pcUserParamMngr->GetGroup("BaseApp/LogLevels")->GetInt(tag, -1);
1015 #endif
1016 }
1017 else if (strcmp(tag, "DebugDefault") == 0) {
1018 #ifndef FC_DEBUG
1019 l = _pcUserParamMngr->GetGroup("BaseApp/LogLevels")->GetInt(tag, -1);
1020 #endif
1021 }
1022 else {
1023 int* pl = Base::Console().getLogLevel(tag, false);
1024 l = pl ? *pl : -1;
1025 }
1026 // For performance reason, we only output integer value
1027 return Py_BuildValue("i", Base::Console().logLevel(l));
1028 }
1029 PY_CATCH;
1030 }
1031
1032 PyObject* Application::sCheckLinkDepth(PyObject* /*self*/, PyObject* args)
1033 {
1034 short depth = 0;
1035 if (!PyArg_ParseTuple(args, "h", &depth)) {
1036 return nullptr;
1037 }
1038
1039 PY_TRY
1040 {
1041 return Py::new_reference_to(
1042 Py::Long(GetApplication().checkLinkDepth(depth, MessageOption::Throw)));
1043 }
1044 PY_CATCH;
1045 }
1046
1047 PyObject* Application::sGetLinksTo(PyObject* /*self*/, PyObject* args)
1048 {
1049 PyObject* pyobj = Py_None;
1050 int options = 0;
1051 short count = 0;
1052 if (!PyArg_ParseTuple(args, "|Oih", &pyobj, &options, &count)) {
1053 return nullptr;
1054 }
1055
1056 PY_TRY
1057 {
1058 Base::PyTypeCheck(&pyobj,
1059 &DocumentObjectPy::Type,
1060 "Expect the first argument of type App.DocumentObject or None");
1061 DocumentObject* obj = nullptr;
1062 if (pyobj) {
1063 obj = static_cast<DocumentObjectPy*>(pyobj)->getDocumentObjectPtr();
1064 }
1065
1066 auto links = GetApplication().getLinksTo(obj, options, count);
1067 Py::Tuple ret(links.size());
1068 int i = 0;
1069 for (auto o : links) {
1070 ret.setItem(i++, Py::Object(o->getPyObject(), true));
1071 }
1072
1073 return Py::new_reference_to(ret);
1074 }
1075 PY_CATCH;
1076 }
1077
1078 PyObject* Application::sGetDependentObjects(PyObject* /*self*/, PyObject* args)
1079 {
1080 PyObject* obj;
1081 int options = 0;
1082 if (!PyArg_ParseTuple(args, "O|i", &obj, &options)) {
1083 return nullptr;
1084 }
1085
1086 std::vector<App::DocumentObject*> objs;
1087 if (PySequence_Check(obj)) {
1088 Py::Sequence seq(obj);
1089 for (Py_ssize_t i = 0; i < seq.size(); ++i) {
1090 if (!PyObject_TypeCheck(seq[i].ptr(), &DocumentObjectPy::Type)) {
1091 PyErr_SetString(PyExc_TypeError,
1092 "Expect element in sequence to be of type document object");
1093 return nullptr;
1094 }
1095 objs.push_back(static_cast<DocumentObjectPy*>(seq[i].ptr())->getDocumentObjectPtr());
1096 }
1097 }
1098 else if (!PyObject_TypeCheck(obj, &DocumentObjectPy::Type)) {
1099 PyErr_SetString(
1100 PyExc_TypeError,
1101 "Expect first argument to be either a document object or sequence of document objects");
1102 return nullptr;
1103 }
1104 else {
1105 objs.push_back(static_cast<DocumentObjectPy*>(obj)->getDocumentObjectPtr());
1106 }
1107
1108 PY_TRY
1109 {
1110 auto ret = App::Document::getDependencyList(objs, options);
1111
1112 Py::Tuple tuple(ret.size());
1113 for (size_t i = 0; i < ret.size(); ++i) {
1114 tuple.setItem(i, Py::Object(ret[i]->getPyObject(), true));
1115 }
1116 return Py::new_reference_to(tuple);
1117 }
1118 PY_CATCH;
1119 }
1120
1121
1122 PyObject* Application::sSetActiveTransaction(PyObject* /*self*/, PyObject* args)
1123 {
1124 char* name;
1125 PyObject* persist = Py_False;
1126 if (!PyArg_ParseTuple(args, "s|O!", &name, &PyBool_Type, &persist)) {
1127 return nullptr;
1128 }
1129
1130 PY_TRY
1131 {
1132 Py::Long ret(GetApplication().setActiveTransaction(name, Base::asBoolean(persist)));
1133 return Py::new_reference_to(ret);
1134 }
1135 PY_CATCH;
1136 }
1137
1138 PyObject* Application::sGetActiveTransaction(PyObject* /*self*/, PyObject* args)
1139 {
1140 if (!PyArg_ParseTuple(args, "")) {
1141 return nullptr;
1142 }
1143
1144 PY_TRY
1145 {
1146 int id = 0;
1147 const char* name = GetApplication().getActiveTransaction(&id);
1148 if (!name || id <= 0) {
1149 Py_Return;
1150 }
1151 Py::Tuple ret(2);
1152 ret.setItem(0, Py::String(name));
1153 ret.setItem(1, Py::Long(id));
1154 return Py::new_reference_to(ret);
1155 }
1156 PY_CATCH;
1157 }
1158
1159 PyObject* Application::sCloseActiveTransaction(PyObject* /*self*/, PyObject* args)
1160 {
1161 PyObject* abort = Py_False;
1162 int id = 0;
1163 if (!PyArg_ParseTuple(args, "|O!i", &PyBool_Type, &abort, &id)) {
1164 return nullptr;
1165 }
1166
1167 PY_TRY
1168 {
1169 GetApplication().closeActiveTransaction(Base::asBoolean(abort), id);
1170 Py_Return;
1171 }
1172 PY_CATCH;
1173 }
1174
1175 PyObject* Application::sCheckAbort(PyObject* /*self*/, PyObject* args)
1176 {
1177 if (!PyArg_ParseTuple(args, "")) {
1178 return nullptr;
1179 }
1180
1181 PY_TRY
1182 {
1183 Base::Sequencer().checkAbort();
1184 Py_Return;
1185 }
1186 PY_CATCH
1187 }