Debian Codegraph @

src/Gui/ApplicationPy.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2005 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <QApplication>
24 #include <QDir>
25 #include <QPrinter>
26 #include <QFileInfo>
27 #include <Inventor/SoInput.h>
28 #include <Inventor/actions/SoGetPrimitiveCountAction.h>
29 #include <Inventor/nodes/SoSeparator.h>
30 #include <xercesc/util/TranscodingException.hpp>
31 #include <xercesc/util/XMLString.hpp>
32
33 #include <boost/regex.hpp>
34
35 #include <App/DocumentObjectPy.h>
36 #include <App/DocumentPy.h>
37 #include <App/PropertyFile.h>
38 #include <Base/Interpreter.h>
39 #include <Base/Console.h>
40 #include <Base/PyWrapParseTupleAndKeywords.h>
41 #include <CXX/Objects.hxx>
42
43 #include <Gui/PreferencePages/DlgSettingsPDF.h>
44
45 #include "Application.h"
46 #include "ApplicationPy.h"
47 #include "BitmapFactory.h"
48 #include "Command.h"
49 #include "Dialogs/DlgPreferencesImp.h"
50 #include "Document.h"
51 #include "DocumentObserverPython.h"
52 #include "DownloadManager.h"
53 #include "EditorView.h"
54 #include "FileHandler.h"
55 #include "Macro.h"
56 #include "MainWindow.h"
57 #include "MainWindowPy.h"
58 #include "PythonEditor.h"
59 #include "PythonWrapper.h"
60 #include "SoFCDB.h"
61 #include "SplitView3DInventor.h"
62 #include "View3DInventor.h"
63 #include "ViewProvider.h"
64 #include "WaitCursor.h"
65 #include "WidgetFactory.h"
66 #include "Workbench.h"
67 #include "WorkbenchManager.h"
68 #include "WorkbenchManipulatorPython.h"
69 #include "Inventor/MarkerBitmaps.h"
70 #include "Language/Translator.h"
71
72
73 using namespace Gui;
74
75 // Application methods structure
76 PyMethodDef ApplicationPy::Methods[] = {
77 {"activateWorkbench",
78 (PyCFunction)ApplicationPy::sActivateWorkbenchHandler,
79 METH_VARARGS,
80 "activateWorkbench(name) -> bool\n"
81 "\n"
82 "Activate workbench by its name. Return False if the workbench is\n"
83 "already active.\n"
84 "\n"
85 "name : str\n Name of the workbench to activate."},
86 {"addWorkbench",
87 (PyCFunction)ApplicationPy::sAddWorkbenchHandler,
88 METH_VARARGS,
89 "addWorkbench(workbench) -> None\n"
90 "\n"
91 "Add a workbench.\n"
92 "\n"
93 "workbench : Workbench, Workbench type\n"
94 " Instance of a Workbench subclass or subclass of the\n"
95 " Workbench class."},
96 {"removeWorkbench",
97 (PyCFunction)ApplicationPy::sRemoveWorkbenchHandler,
98 METH_VARARGS,
99 "removeWorkbench(name) -> None\n"
100 "\n"
101 "Remove a workbench.\n"
102 "\n"
103 "name : str\n Name of the workbench to remove."},
104 {"getWorkbench",
105 (PyCFunction)ApplicationPy::sGetWorkbenchHandler,
106 METH_VARARGS,
107 "getWorkbench(name) -> Workbench\n"
108 "\n"
109 "Get the workbench by its name.\n"
110 "\n"
111 "name : str\n Name of the workbench to return."},
112 {"listWorkbenches",
113 (PyCFunction)ApplicationPy::sListWorkbenchHandlers,
114 METH_VARARGS,
115 "listWorkbenches() -> dict\n"
116 "\n"
117 "Get a dictionary with all workbenches."},
118 {"activeWorkbench",
119 (PyCFunction)ApplicationPy::sActiveWorkbenchHandler,
120 METH_VARARGS,
121 "activeWorkbench() -> Workbench\n"
122 "\n"
123 "Return the active workbench object."},
124 {"addResourcePath",
125 (PyCFunction)ApplicationPy::sAddResPath,
126 METH_VARARGS,
127 "addResourcePath(path) -> None\n"
128 "\n"
129 "Add a new path to the system where to find resource files\n"
130 "like icons or localization files.\n"
131 "\n"
132 "path : str, bytes, bytearray\n Path to resource files."},
133 {"addLanguagePath",
134 (PyCFunction)ApplicationPy::sAddLangPath,
135 METH_VARARGS,
136 "addLanguagePath(path) -> None\n"
137 "\n"
138 "Add a new path to the system where to find language files.\n"
139 "\n"
140 "path : str, bytes, bytearray\n Path to language files."},
141 {"addIconPath",
142 (PyCFunction)ApplicationPy::sAddIconPath,
143 METH_VARARGS,
144 "addIconPath(path) -> None\n"
145 "\n"
146 "Add a new path to the system where to find icon files.\n"
147 "\n"
148 "path : str, bytes, bytearray\n Path to icon files."},
149 {"addIcon",
150 (PyCFunction)ApplicationPy::sAddIcon,
151 METH_VARARGS,
152 "addIcon(name, content, format='XPM') -> None\n"
153 "\n"
154 "Add an icon to the system.\n"
155 "\n"
156 "name : str\n Name of the icon.\n"
157 "content : str, bytes-like\n Content of the icon.\n"
158 "format : str\n Format of the icon."},
159 {"getIcon",
160 (PyCFunction)ApplicationPy::sGetIcon,
161 METH_VARARGS,
162 "getIcon(name) -> QIcon or None\n"
163 "\n"
164 "Get an icon in the system. If the pixmap is null, return None.\n"
165 "\n"
166 "name : str\n Name of the icon."},
167 {"isIconCached",
168 (PyCFunction)ApplicationPy::sIsIconCached,
169 METH_VARARGS,
170 "isIconCached(name) -> Bool\n"
171 "\n"
172 "Check if an icon with the given name is cached.\n"
173 "\n"
174 "name : str\n Name of the icon."},
175 {"getMainWindow",
176 (PyCFunction)ApplicationPy::sGetMainWindow,
177 METH_VARARGS,
178 "getMainWindow() -> QMainWindow\n"
179 "\n"
180 "Return the main window instance."},
181 {"updateGui",
182 (PyCFunction)ApplicationPy::sUpdateGui,
183 METH_VARARGS,
184 "updateGui() -> None\n"
185 "\n"
186 "Update the main window and all its windows."},
187 {"updateLocale",
188 (PyCFunction)ApplicationPy::sUpdateLocale,
189 METH_VARARGS,
190 "updateLocale() -> None\n"
191 "\n"
192 "Update the localization."},
193 {"getLocale",
194 (PyCFunction)ApplicationPy::sGetLocale,
195 METH_VARARGS,
196 "getLocale() -> str\n"
197 "\n"
198 "Returns the locale currently used by FreeCAD."},
199 {"setLocale",
200 (PyCFunction)ApplicationPy::sSetLocale,
201 METH_VARARGS,
202 "setLocale(name) -> None\n"
203 "\n"
204 "Sets the locale used by FreeCAD. Can be set by top-level\n"
205 "domain (e.g. \"de\") or the language name (e.g. \"German\").\n"
206 "\n"
207 "name : str\n Locale name."},
208 {"supportedLocales",
209 (PyCFunction)ApplicationPy::sSupportedLocales,
210 METH_VARARGS,
211 "supportedLocales() -> dict\n"
212 "\n"
213 "Returns a dict of all supported locales. The keys are the language\n"
214 "names and the values the top-level domains."},
215 {"createDialog",
216 (PyCFunction)ApplicationPy::sCreateDialog,
217 METH_VARARGS,
218 "createDialog(path) -> PyResource\n"
219 "\n"
220 "Open a UI file.\n"
221 "\n"
222 "path : str\n UI file path."},
223 {"addPreferencePage",
224 (PyCFunction)ApplicationPy::sAddPreferencePage,
225 METH_VARARGS,
226 "addPreferencePage(path, group) -> None\n"
227 "addPreferencePage(dialog, group) -> None\n"
228 "\n"
229 "Add a UI form to the preferences dialog in the specified group.\n"
230 "\n"
231 "path : str\n UI file path.\n"
232 "group : str\n Group name.\n"
233 "dialog : type\n Preference page."},
234 {"addCommand",
235 (PyCFunction)ApplicationPy::sAddCommand,
236 METH_VARARGS,
237 "addCommand(name, cmd, activation) -> None\n"
238 "\n"
239 "Add a command object.\n"
240 "\n"
241 "name : str\n Name of the command.\n"
242 "cmd : object\n Command instance.\n"
243 "activation : str\n Activation sequence. Optional."},
244 {"runCommand",
245 (PyCFunction)ApplicationPy::sRunCommand,
246 METH_VARARGS,
247 "runCommand(name, index=0) -> None\n"
248 "\n"
249 "Run command by its name.\n"
250 "\n"
251 "name : str\n Name of the command.\n"
252 "index : int\n Index of the child command."},
253 {"SendMsgToActiveView",
254 (PyCFunction)ApplicationPy::sSendActiveView,
255 METH_VARARGS,
256 "SendMsgToActiveView(name, suppress=False) -> str or None\n"
257 "\n"
258 "Send message to the active view. Deprecated, use class View.\n"
259 "\n"
260 "name : str\n Name of the view command.\n"
261 "suppress : bool\n If the sent message fail, suppress warning message."},
262 {"sendMsgToFocusView",
263 (PyCFunction)ApplicationPy::sSendFocusView,
264 METH_VARARGS,
265 "sendMsgToFocusView(name, suppress=False) -> str or None\n"
266 "\n"
267 "Send message to the focused view.\n"
268 "\n"
269 "name : str\n Name of the view command.\n"
270 "suppress : bool\n If send message fail, suppress warning message."},
271 {"hide",
272 (PyCFunction)ApplicationPy::sHide,
273 METH_VARARGS,
274 "hide(name) -> None\n"
275 "\n"
276 "Hide the given feature. Deprecated.\n"
277 "\n"
278 "name : str\n Feature name."},
279 {"show",
280 (PyCFunction)ApplicationPy::sShow,
281 METH_VARARGS,
282 "show(name) -> None\n"
283 "\n"
284 "Show the given feature. Deprecated.\n"
285 "\n"
286 "name : str\n Feature name."},
287 {"hideObject",
288 (PyCFunction)ApplicationPy::sHideObject,
289 METH_VARARGS,
290 "hideObject(obj) -> None\n"
291 "\n"
292 "Hide the view provider of the given object.\n"
293 "\n"
294 "obj : App.DocumentObject"},
295 {"showObject",
296 (PyCFunction)ApplicationPy::sShowObject,
297 METH_VARARGS,
298 "showObject(obj) -> None\n"
299 "\n"
300 "Show the view provider of the given object.\n"
301 "\n"
302 "obj : App.DocumentObject"},
303 {"open",
304 (PyCFunction)ApplicationPy::sOpen,
305 METH_VARARGS,
306 "open(fileName) -> None\n"
307 "\n"
308 "Open a macro, Inventor or VRML file.\n"
309 "\n"
310 "fileName : str, bytes, bytearray\n File name."},
311 {"insert",
312 (PyCFunction)ApplicationPy::sInsert,
313 METH_VARARGS,
314 "insert(fileName, docName) -> None\n"
315 "\n"
316 "Insert a macro, Inventor or VRML file. If no document name\n"
317 "is given the active document is used.\n"
318 "\n"
319 "fileName : str, bytes, bytearray\n File name.\n"
320 "docName : str\n Document name."},
321 {"export",
322 (PyCFunction)ApplicationPy::sExport,
323 METH_VARARGS,
324 "export(objs, fileName) -> None\n"
325 "\n"
326 "Save scene to Inventor or VRML file.\n"
327 "\n"
328 "objs : sequence of App.DocumentObject\n Sequence of objects to save.\n"
329 "fileName : str, bytes, bytearray\n File name."},
330 {"activeDocument",
331 (PyCFunction)ApplicationPy::sActiveDocument,
332 METH_VARARGS,
333 "activeDocument() -> Gui.Document or None\n"
334 "\n"
335 "Return the active document. If no one exists, return None."},
336 {"setActiveDocument",
337 (PyCFunction)ApplicationPy::sSetActiveDocument,
338 METH_VARARGS,
339 "setActiveDocument(doc) -> None\n"
340 "\n"
341 "Activate the specified document.\n"
342 "\n"
343 "doc : str, App.Document\n Document to activate."},
344 {"activeView",
345 (PyCFunction)ApplicationPy::sActiveView,
346 METH_VARARGS,
347 "activeView(typeName) -> object or None\n"
348 "\n"
349 "Return the active view of the active document. If no one\n"
350 "exists, return None.\n"
351 "\n"
352 "typeName : str\n Type name."},
353 {"activateView",
354 (PyCFunction)ApplicationPy::sActivateView,
355 METH_VARARGS,
356 "activateView(typeName, create=False) -> None\n"
357 "\n"
358 "Activate a view of the given type in the active document.\n"
359 "If a view of this type doesn't exist and create is True, a\n"
360 "new view of this type is created.\n"
361 "\n"
362 "type : str\n Type name.\n"
363 "create : bool"},
364 {"editDocument",
365 (PyCFunction)ApplicationPy::sEditDocument,
366 METH_VARARGS,
367 "editDocument() -> Gui.Document or None\n"
368 "\n"
369 "Return the current editing document. If no one exists,\n"
370 "return None."},
371 {"getDocument",
372 (PyCFunction)ApplicationPy::sGetDocument,
373 METH_VARARGS,
374 "getDocument(doc) -> Gui.Document\n"
375 "\n"
376 "Get a document.\n"
377 "\n"
378 "doc : str, App.Document\n `App.Document` name or `App.Document` object."},
379 {"doCommand",
380 (PyCFunction)ApplicationPy::sDoCommand,
381 METH_VARARGS,
382 "doCommand(cmd) -> None\n"
383 "\n"
384 "Prints the given string in the python console and runs it.\n"
385 "\n"
386 "cmd : str"},
387 {"doCommandGui",
388 (PyCFunction)ApplicationPy::sDoCommandGui,
389 METH_VARARGS,
390 "doCommandGui(cmd) -> None\n"
391 "\n"
392 "Prints the given string in the python console and runs it\n"
393 "but doesn't record it in macros.\n"
394 "\n"
395 "cmd : str"},
396 {"doCommandEval",
397 (PyCFunction)ApplicationPy::sDoCommandEval,
398 METH_VARARGS,
399 "doCommandEval(cmd) -> PyObject\n"
400 "\n"
401 "Runs the given string without showing in the python console or recording in\n"
402 "macros, and returns the result.\n"
403 "\n"
404 "cmd : str"},
405 {"doCommandSkip",
406 (PyCFunction)ApplicationPy::sDoCommandSkip,
407 METH_VARARGS,
408 "doCommandSkip(cmd) -> None\n"
409 "\n"
410 "Record the given string in the Macro but comment it out in the console\n"
411 "\n"
412 "cmd : str"},
413 {"addModule",
414 (PyCFunction)ApplicationPy::sAddModule,
415 METH_VARARGS,
416 "addModule(mod) -> None\n"
417 "\n"
418 "Prints the given module import only once in the macro recording.\n"
419 "\n"
420 "mod : str"},
421 {"showDownloads",
422 (PyCFunction)ApplicationPy::sShowDownloads,
423 METH_VARARGS,
424 "showDownloads() -> None\n\n"
425 "Show the downloads manager window."},
426 {"showPreferences",
427 (PyCFunction)ApplicationPy::sShowPreferences,
428 METH_VARARGS,
429 "showPreferences(grp, index=0) -> None\n"
430 "\n"
431 "Show the preferences window.\n"
432 "\n"
433 "grp: str\n Group to show.\n"
434 "index : int\n Page index."},
435 {"showPreferencesByName",
436 (PyCFunction)ApplicationPy::sShowPreferencesByName,
437 METH_VARARGS,
438 "showPreferencesByName(grp, pagename) -> None\n"
439 "\n"
440 "Show the preferences window.\n"
441 "\n"
442 "grp: str\n Group to show.\n"
443 "pagename : str\n Page to show."},
444 {"createViewer",
445 (PyCFunction)ApplicationPy::sCreateViewer,
446 METH_VARARGS,
447 "createViewer(views=1, name) -> View3DInventorPy or AbstractSplitViewPy\n"
448 "\n"
449 "Show and returns a viewer.\n"
450 "\n"
451 "views : int\n If > 1 a `AbstractSplitViewPy` object is returned.\n"
452 "name : str\n Viewer title."},
453 {"getMarkerIndex",
454 (PyCFunction)ApplicationPy::sGetMarkerIndex,
455 METH_VARARGS,
456 "getMarkerIndex(marker, size=9) -> int\n"
457 "\n"
458 "Get marker index according to marker name and size.\n"
459 "\n"
460 "marker : str\n Marker style name.\n"
461 "size : int\n Marker size."},
462 {"addDocumentObserver",
463 (PyCFunction)ApplicationPy::sAddDocObserver,
464 METH_VARARGS,
465 "addDocumentObserver(obj) -> None\n"
466 "\n"
467 "Add an observer to get notifications about changes on documents.\n"
468 "\n"
469 "obj : object"},
470 {"removeDocumentObserver",
471 (PyCFunction)ApplicationPy::sRemoveDocObserver,
472 METH_VARARGS,
473 "removeDocumentObserver(obj) -> None\n"
474 "\n"
475 "Remove an added document observer.\n"
476 "\n"
477 "obj : object"},
478 {"addWorkbenchManipulator",
479 (PyCFunction)ApplicationPy::sAddWbManipulator,
480 METH_VARARGS,
481 "addWorkbenchManipulator(obj) -> None\n"
482 "\n"
483 "Add a workbench manipulator to modify a workbench when it is activated.\n"
484 "\n"
485 "obj : object"},
486 {"removeWorkbenchManipulator",
487 (PyCFunction)ApplicationPy::sRemoveWbManipulator,
488 METH_VARARGS,
489 "removeWorkbenchManipulator(obj) -> None\n"
490 "\n"
491 "Remove an added workbench manipulator.\n"
492 "\n"
493 "obj : object"},
494 {"listUserEditModes",
495 (PyCFunction)ApplicationPy::sListUserEditModes,
496 METH_VARARGS,
497 "listUserEditModes() -> list\n"
498 "\n"
499 "List available user edit modes."},
500 {"getUserEditMode",
501 (PyCFunction)ApplicationPy::sGetUserEditMode,
502 METH_VARARGS,
503 "getUserEditMode() -> str\n"
504 "\n"
505 "Get current user edit mode."},
506 {"setUserEditMode",
507 (PyCFunction)ApplicationPy::sSetUserEditMode,
508 METH_VARARGS,
509 "setUserEditMode(mode) -> bool\n"
510 "\n"
511 "Set user edit mode. Returns True if exists, False otherwise.\n"
512 "\n"
513 "mode : str"},
514 {"reload",
515 (PyCFunction)ApplicationPy::sReload,
516 METH_VARARGS,
517 "reload(name) -> App.Document or None\n"
518 "\n"
519 "Reload a partial opened document. If the document is not open,\n"
520 "return None.\n"
521 "\n"
522 "name : str\n `App.Document` name."},
523 {"loadFile",
524 (PyCFunction)ApplicationPy::sLoadFile,
525 METH_VARARGS,
526 "loadFile(fileName, module) -> None\n"
527 "\n"
528 "Loads an arbitrary file by delegating to the given Python module.\n"
529 "If no module is given it will be determined by the file extension.\n"
530 "If more than one module can load a file the first one will be taken.\n"
531 "If no module exists to load the file an exception will be raised.\n"
532 "\n"
533 "fileName : str\n"
534 "module : str"},
535 {"coinRemoveAllChildren",
536 (PyCFunction)ApplicationPy::sCoinRemoveAllChildren,
537 METH_VARARGS,
538 "coinRemoveAllChildren(node) -> None\n"
539 "\n"
540 "Remove all children from a group node.\n"
541 "\n"
542 "node : object"},
543 {"suspendWaitCursor",
544 (PyCFunction)ApplicationPy::sSuspendWaitCursor,
545 METH_VARARGS,
546 "suspendWaitCursor() -> None\n\n"
547 "Temporarily suspends the application's wait cursor and event filter."},
548 {"resumeWaitCursor",
549 (PyCFunction)ApplicationPy::sResumeWaitCursor,
550 METH_VARARGS,
551 "resumeWaitCursor() -> None\n\n"
552 "Resumes the application's wait cursor and event filter."},
553 {nullptr, nullptr, 0, nullptr} /* Sentinel */
554 };
555
556 PyObject* Gui::ApplicationPy::sEditDocument(PyObject* /*self*/, PyObject* args)
557 {
558 if (!PyArg_ParseTuple(args, "")) {
559 return nullptr;
560 }
561
562 Document* pcDoc = Application::Instance->editDocument();
563 if (pcDoc) {
564 return pcDoc->getPyObject();
565 }
566
567 Py_Return;
568 }
569
570 PyObject* Gui::ApplicationPy::sActiveDocument(PyObject* /*self*/, PyObject* args)
571 {
572 if (!PyArg_ParseTuple(args, "")) {
573 return nullptr;
574 }
575
576 Document* pcDoc = Application::Instance->activeDocument();
577 if (pcDoc) {
578 return pcDoc->getPyObject();
579 }
580
581 Py_Return;
582 }
583
584 PyObject* Gui::ApplicationPy::sActiveView(PyObject* /*self*/, PyObject* args)
585 {
586 const char* typeName = nullptr;
587 if (!PyArg_ParseTuple(args, "|s", &typeName)) {
588 return nullptr;
589 }
590
591 PY_TRY
592 {
593 Base::Type type;
594 if (typeName) {
595 type = Base::Type::fromName(typeName);
596 if (type.isBad()) {
597 PyErr_Format(PyExc_TypeError, "Invalid type '%s'", typeName);
598 return nullptr;
599 }
600 }
601
602 Gui::MDIView* mdiView = Application::Instance->activeView();
603 if (mdiView && (type.isBad() || mdiView->isDerivedFrom(type))) {
604 auto res = Py::asObject(mdiView->getPyObject());
605 if (!res.isNone() || !type.isBad()) {
606 return Py::new_reference_to(res);
607 }
608 }
609
610 if (type.isBad()) {
611 type = Gui::View3DInventor::getClassTypeId();
612 }
613 Application::Instance->activateView(type, true);
614 mdiView = Application::Instance->activeView();
615 if (mdiView) {
616 return mdiView->getPyObject();
617 }
618
619 Py_Return;
620 }
621 PY_CATCH
622 }
623
624 PyObject* Gui::ApplicationPy::sActivateView(PyObject* /*self*/, PyObject* args)
625 {
626 char* typeStr = nullptr;
627 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
628 PyObject* create = Py_False;
629 if (!PyArg_ParseTuple(args, "sO!", &typeStr, &PyBool_Type, &create)) {
630 return nullptr;
631 }
632
633 Base::Type type = Base::Type::fromName(typeStr);
634 Application::Instance->activateView(type, Base::asBoolean(create));
635
636 Py_Return;
637 }
638
639 PyObject* Gui::ApplicationPy::sSetActiveDocument(PyObject* /*self*/, PyObject* args)
640 {
641 Document* pcDoc = nullptr;
642
643 do {
644 char* pstr = nullptr;
645 if (PyArg_ParseTuple(args, "s", &pstr)) {
646 pcDoc = Application::Instance->getDocument(pstr);
647 if (!pcDoc) {
648 PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr);
649 return nullptr;
650 }
651 break;
652 }
653
654 PyErr_Clear();
655 PyObject* doc = nullptr;
656 if (PyArg_ParseTuple(args, "O!", &(App::DocumentPy::Type), &doc)) {
657 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
658 pcDoc = Application::Instance->getDocument(
659 static_cast<App::DocumentPy*>(doc)->getDocumentPtr()
660 );
661 if (!pcDoc) {
662 PyErr_Format(PyExc_KeyError, "Unknown document instance");
663 return nullptr;
664 }
665 break;
666 }
667 } while (false);
668
669 if (!pcDoc) {
670 PyErr_SetString(PyExc_TypeError, "Either string or App.Document expected");
671 return nullptr;
672 }
673
674 if (Application::Instance->activeDocument() != pcDoc) {
675 Gui::MDIView* view = pcDoc->getActiveView();
676 getMainWindow()->setActiveWindow(view);
677 }
678
679 Py_Return;
680 }
681
682 PyObject* ApplicationPy::sGetDocument(PyObject* /*self*/, PyObject* args)
683 {
684 char* pstr = nullptr;
685 if (PyArg_ParseTuple(args, "s", &pstr)) {
686 Document* pcDoc = Application::Instance->getDocument(pstr);
687 if (!pcDoc) {
688 PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr);
689 return nullptr;
690 }
691 return pcDoc->getPyObject();
692 }
693
694 PyErr_Clear();
695 PyObject* doc = nullptr;
696 if (PyArg_ParseTuple(args, "O!", &(App::DocumentPy::Type), &doc)) {
697 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
698 Document* pcDoc = Application::Instance->getDocument(
699 static_cast<App::DocumentPy*>(doc)->getDocumentPtr()
700 );
701 if (!pcDoc) {
702 PyErr_Format(PyExc_KeyError, "Unknown document instance");
703 return nullptr;
704 }
705 return pcDoc->getPyObject();
706 }
707
708 PyErr_SetString(PyExc_TypeError, "Either string or App.Document expected");
709 return nullptr;
710 }
711
712 PyObject* ApplicationPy::sHide(PyObject* /*self*/, PyObject* args)
713 {
714 char* psFeatStr = nullptr;
715 if (!PyArg_ParseTuple(args, "s;Name of the object to hide has to be given!", &psFeatStr)) {
716 return nullptr;
717 }
718
719 Document* pcDoc = Application::Instance->activeDocument();
720
721 if (pcDoc) {
722 pcDoc->setHide(psFeatStr);
723 }
724
725 Py_Return;
726 }
727
728 PyObject* ApplicationPy::sShow(PyObject* /*self*/, PyObject* args)
729 {
730 char* psFeatStr = nullptr;
731 if (!PyArg_ParseTuple(args, "s;Name of the object to show has to be given!", &psFeatStr)) {
732 return nullptr;
733 }
734
735 Document* pcDoc = Application::Instance->activeDocument();
736
737 if (pcDoc) {
738 pcDoc->setShow(psFeatStr);
739 }
740
741 Py_Return;
742 }
743
744 PyObject* ApplicationPy::sHideObject(PyObject* /*self*/, PyObject* args)
745 {
746 PyObject* object = nullptr;
747 if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &object)) {
748 return nullptr;
749 }
750
751 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
752 App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(object)->getDocumentObjectPtr();
753 Application::Instance->hideViewProvider(obj);
754
755 Py_Return;
756 }
757
758 PyObject* ApplicationPy::sShowObject(PyObject* /*self*/, PyObject* args)
759 {
760 PyObject* object = nullptr;
761 if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &object)) {
762 return nullptr;
763 }
764
765 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
766 App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(object)->getDocumentObjectPtr();
767 Application::Instance->showViewProvider(obj);
768
769 Py_Return;
770 }
771
772 PyObject* ApplicationPy::sOpen(PyObject* /*self*/, PyObject* args)
773 {
774 // only used to open Python files
775 char* Name = nullptr;
776 if (!PyArg_ParseTuple(args, "et", "utf-8", &Name)) {
777 return nullptr;
778 }
779
780 std::string Utf8Name = std::string(Name);
781 PyMem_Free(Name);
782 PY_TRY
783 {
784 QString fileName = QString::fromUtf8(Utf8Name.c_str());
785 FileHandler handler(fileName);
786 if (!handler.openFile()) {
787 QString ext = handler.extension();
788 Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData());
789 }
790 }
791 PY_CATCH;
792
793 Py_Return;
794 }
795
796 PyObject* ApplicationPy::sInsert(PyObject* /*self*/, PyObject* args)
797 {
798 char* Name = nullptr;
799 char* DocName = nullptr;
800 if (!PyArg_ParseTuple(args, "et|s", "utf-8", &Name, &DocName)) {
801 return nullptr;
802 }
803
804 std::string Utf8Name = std::string(Name);
805 PyMem_Free(Name);
806
807 PY_TRY
808 {
809 QString fileName = QString::fromUtf8(Utf8Name.c_str());
810 FileHandler handler(fileName);
811 if (!handler.importFile(std::string(DocName ? DocName : ""))) {
812 QString ext = handler.extension();
813 Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData());
814 }
815 }
816 PY_CATCH;
817
818 Py_Return;
819 }
820
821 PyObject* ApplicationPy::sExport(PyObject* /*self*/, PyObject* args)
822 {
823 PyObject* object = nullptr;
824 char* Name = nullptr;
825 if (!PyArg_ParseTuple(args, "Oet", &object, "utf-8", &Name)) {
826 return nullptr;
827 }
828
829 std::string Utf8Name = std::string(Name);
830 PyMem_Free(Name);
831
832 PY_TRY
833 {
834 App::Document* doc = nullptr;
835 Py::Sequence list(object);
836 for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
837 PyObject* item = (*it).ptr();
838 if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
839 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
840 App::DocumentObject* obj
841 = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
842 doc = obj->getDocument();
843 break;
844 }
845 }
846
847 QString fileName = QString::fromUtf8(Utf8Name.c_str());
848 QFileInfo fi;
849 fi.setFile(fileName);
850 QString ext = fi.suffix().toLower();
851 if (ext == QLatin1String("iv") || ext == QLatin1String("wrl") || ext == QLatin1String("vrml")
852 || ext == QLatin1String("wrz") || ext == QLatin1String("x3d")
853 || ext == QLatin1String("x3dz") || ext == QLatin1String("xhtml")) {
854
855 // build up the graph
856 auto sep = new SoSeparator();
857 sep->ref();
858
859 for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
860 PyObject* item = (*it).ptr();
861 if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
862 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
863 App::DocumentObject* obj
864 = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
865
866 Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(obj);
867 if (vp) {
868 sep->addChild(vp->getRoot());
869 }
870 }
871 }
872
873
874 SoGetPrimitiveCountAction action;
875 action.setCanApproximate(true);
876 action.apply(sep);
877
878 constexpr const int triangleLimit = 100000;
879 constexpr const int pointLimit = 30000;
880 constexpr const int lineLimit = 10000;
881
882 bool binary = false;
883 if (action.getTriangleCount() > triangleLimit || action.getPointCount() > pointLimit
884 || action.getLineCount() > lineLimit) {
885 binary = true;
886 }
887
888 SoFCDB::writeToFile(sep, Utf8Name.c_str(), binary);
889 sep->unref();
890 }
891 else if (ext == QLatin1String("pdf")) {
892 // get the view that belongs to the found document
893 Gui::Document* gui_doc = Application::Instance->getDocument(doc);
894 if (gui_doc) {
895 Gui::MDIView* view = gui_doc->getActiveView();
896 if (view) {
897 auto view3d = qobject_cast<View3DInventor*>(view);
898 if (view3d) {
899 view3d->viewAll();
900 }
901 QPrinter printer(QPrinter::ScreenResolution);
902 // setPdfVersion sets the printed PDF Version to what is chosen in
903 // Preferences/Import-Export/PDF more details under:
904 // https://www.kdab.com/creating-pdfa-documents-qt/
905 printer.setPdfVersion(Gui::Dialog::DlgSettingsPDF::evaluatePDFVersion());
906 printer.setOutputFormat(QPrinter::PdfFormat);
907 printer.setOutputFileName(fileName);
908 printer.setCreator(QString::fromStdString(App::Application::getNameWithVersion()));
909 view->print(&printer);
910 }
911 }
912 }
913 else {
914 Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData());
915 }
916 }
917 PY_CATCH;
918
919 Py_Return;
920 }
921
922 PyObject* ApplicationPy::sSendActiveView(PyObject* /*self*/, PyObject* args)
923 {
924 char* psCommandStr = nullptr;
925 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
926 PyObject* suppress = Py_False;
927 if (!PyArg_ParseTuple(args, "s|O!", &psCommandStr, &PyBool_Type, &suppress)) {
928 return nullptr;
929 }
930
931 const char* ppReturn = nullptr;
932 if (!Application::Instance->sendMsgToActiveView(psCommandStr, &ppReturn)) {
933 if (!Base::asBoolean(suppress)) {
934 Base::Console().warning("Unknown view command: %s\n", psCommandStr);
935 }
936 }
937
938 // Print the return value to the output
939 if (ppReturn) {
940 return Py_BuildValue("s", ppReturn);
941 }
942
943 Py_Return;
944 }
945
946 PyObject* ApplicationPy::sSendFocusView(PyObject* /*self*/, PyObject* args)
947 {
948 char* psCommandStr = nullptr;
949 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast)
950 PyObject* suppress = Py_False;
951 if (!PyArg_ParseTuple(args, "s|O!", &psCommandStr, &PyBool_Type, &suppress)) {
952 return nullptr;
953 }
954
955 const char* ppReturn = nullptr;
956 if (!Application::Instance->sendMsgToFocusView(psCommandStr, &ppReturn)) {
957 if (!Base::asBoolean(suppress)) {
958 Base::Console().warning("Unknown view command: %s\n", psCommandStr);
959 }
960 }
961
962 // Print the return value to the output
963 if (ppReturn) {
964 return Py_BuildValue("s", ppReturn);
965 }
966
967 Py_Return;
968 }
969
970 PyObject* ApplicationPy::sGetMainWindow(PyObject* /*self*/, PyObject* args)
971 {
972 if (!PyArg_ParseTuple(args, "")) {
973 return nullptr;
974 }
975
976 try {
977 return Py::new_reference_to(MainWindowPy::createWrapper(Gui::getMainWindow()));
978 }
979 catch (const Py::Exception&) {
980 return nullptr;
981 }
982 }
983
984 PyObject* ApplicationPy::sUpdateGui(PyObject* /*self*/, PyObject* args)
985 {
986 if (!PyArg_ParseTuple(args, "")) {
987 return nullptr;
988 }
989
990 qApp->processEvents();
991
992 Py_Return;
993 }
994
995 PyObject* ApplicationPy::sUpdateLocale(PyObject* /*self*/, PyObject* args)
996 {
997 if (!PyArg_ParseTuple(args, "")) {
998 return nullptr;
999 }
1000
1001 Translator::instance()->refresh();
1002
1003 Py_Return;
1004 }
1005
1006 PyObject* ApplicationPy::sGetLocale(PyObject* /*self*/, PyObject* args)
1007 {
1008 if (!PyArg_ParseTuple(args, "")) {
1009 return nullptr;
1010 }
1011
1012 std::string locale = Translator::instance()->activeLanguage();
1013 return PyUnicode_FromString(locale.c_str());
1014 }
1015
1016 PyObject* ApplicationPy::sSetLocale(PyObject* /*self*/, PyObject* args)
1017 {
1018 char* name = nullptr;
1019 if (!PyArg_ParseTuple(args, "s", &name)) {
1020 return nullptr;
1021 }
1022
1023 std::string cname(name);
1024 TStringMap map = Translator::instance()->supportedLocales();
1025 map["English"] = "en";
1026 for (const auto& it : map) {
1027 if (it.first == cname || it.second == cname) {
1028 Translator::instance()->activateLanguage(it.first.c_str());
1029 break;
1030 }
1031 }
1032
1033 Py_Return;
1034 }
1035
1036 PyObject* ApplicationPy::sSupportedLocales(PyObject* /*self*/, PyObject* args)
1037 {
1038 if (!PyArg_ParseTuple(args, "")) {
1039 return nullptr;
1040 }
1041
1042 TStringMap map = Translator::instance()->supportedLocales();
1043 Py::Dict dict;
1044 dict.setItem(Py::String("English"), Py::String("en"));
1045 for (const auto& it : map) {
1046 Py::String key(it.first);
1047 Py::String val(it.second);
1048 dict.setItem(key, val);
1049 }
1050 return Py::new_reference_to(dict);
1051 }
1052
1053 PyObject* ApplicationPy::sCreateDialog(PyObject* /*self*/, PyObject* args)
1054 {
1055 char* fn = nullptr;
1056 if (!PyArg_ParseTuple(args, "s", &fn)) {
1057 return nullptr;
1058 }
1059
1060 PyObject* pPyResource = nullptr;
1061 try {
1062 pPyResource = new PyResource();
1063 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast)
1064 static_cast<PyResource*>(pPyResource)->load(fn);
1065 }
1066 catch (const Base::Exception& e) {
1067 PyErr_SetString(PyExc_AssertionError, e.what());
1068 return nullptr;
1069 }
1070
1071 return pPyResource;
1072 }
1073
1074 PyObject* ApplicationPy::sAddPreferencePage(PyObject* /*self*/, PyObject* args)
1075 {
1076 char* fn = nullptr;
1077 char* grp = nullptr;
1078 if (PyArg_ParseTuple(args, "ss", &fn, &grp)) {
1079 QFileInfo fi(QString::fromUtf8(fn));
1080 if (!fi.exists()) {
1081 PyErr_SetString(PyExc_RuntimeError, "UI file does not exist");
1082 return nullptr;
1083 }
1084
1085 // add to the preferences dialog
1086 new PrefPageUiProducer(fn, grp);
1087 Py_Return;
1088 }
1089
1090 PyErr_Clear();
1091 PyObject* dlg = nullptr;
1092 // new style classes
1093 if (PyArg_ParseTuple(args, "O!s", &PyType_Type, &dlg, &grp)) {
1094 // add to the preferences dialog
1095 new PrefPagePyProducer(Py::Object(dlg), grp);
1096 Py_Return;
1097 }
1098
1099 return nullptr;
1100 }
1101
1102 PyObject* ApplicationPy::sActivateWorkbenchHandler(PyObject* /*self*/, PyObject* args)
1103 {
1104 char* psKey = nullptr;
1105 if (!PyArg_ParseTuple(args, "s", &psKey)) {
1106 return nullptr;
1107 }
1108
1109 // search for workbench handler from the dictionary
1110 PyObject* pcWorkbench = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, psKey);
1111 if (!pcWorkbench) {
1112 PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
1113 return nullptr;
1114 }
1115
1116 try {
1117 bool ok = Application::Instance->activateWorkbench(psKey);
1118 return Py::new_reference_to(Py::Boolean(ok));
1119 }
1120 catch (const Base::Exception& e) {
1121 std::stringstream err;
1122 err << psKey << ": " << e.what();
1123 PyErr_SetString(e.getPyExceptionType(), err.str().c_str());
1124 return nullptr;
1125 }
1126 catch (const XERCES_CPP_NAMESPACE_QUALIFIER TranscodingException& e) {
1127 std::stringstream err;
1128 char* pMsg = XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode(e.getMessage());
1129 err << "Transcoding exception in Xerces-c:\n\n"
1130 << "Transcoding exception raised in activateWorkbench.\n"
1131 << "Check if your user configuration file is valid.\n"
1132 << " Exception message:" << pMsg;
1133 XERCES_CPP_NAMESPACE_QUALIFIER XMLString::release(&pMsg);
1134 PyErr_SetString(PyExc_RuntimeError, err.str().c_str());
1135 return nullptr;
1136 }
1137 catch (...) {
1138 std::stringstream err;
1139 err << "Unknown C++ exception raised in activateWorkbench('" << psKey << "')";
1140 PyErr_SetString(Base::PyExc_FC_GeneralError, err.str().c_str());
1141 return nullptr;
1142 }
1143 }
1144
1145 PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject* /*self*/, PyObject* args)
1146 {
1147 PyObject* pcObject = nullptr;
1148 if (!PyArg_ParseTuple(args, "O", &pcObject)) {
1149 return nullptr;
1150 }
1151
1152 try {
1153 // get the class object 'Workbench' from the main module that is expected
1154 // to be base class for all workbench classes
1155 Py::Module module("__main__");
1156 Py::Object baseclass(module.getAttr(std::string("Workbench")));
1157
1158 // check whether it is an instance or class object
1159 Py::Object object(pcObject);
1160 Py::String name;
1161
1162 if (PyObject_IsSubclass(object.ptr(), baseclass.ptr()) == 1) {
1163 // create an instance of this class
1164 name = object.getAttr(std::string("__name__"));
1165 Py::Tuple arg;
1166 Py::Callable creation(object);
1167 object = creation.apply(arg);
1168 }
1169 else if (PyObject_IsInstance(object.ptr(), baseclass.ptr()) == 1) {
1170 // extract the class name of the instance
1171 PyErr_Clear(); // PyObject_IsSubclass set an exception
1172 Py::Object classobj = object.getAttr(std::string("__class__"));
1173 name = classobj.getAttr(std::string("__name__"));
1174 }
1175 else {
1176 PyErr_SetString(
1177 PyExc_TypeError,
1178 "arg must be a subclass or an instance of "
1179 "a subclass of 'Workbench'"
1180 );
1181 return nullptr;
1182 }
1183
1184 // NOLINTBEGIN(bugprone-unused-raii)
1185 // Search for some methods and members without invoking them
1186 Py::Callable(object.getAttr(std::string("Initialize")));
1187 Py::Callable(object.getAttr(std::string("GetClassName")));
1188 // NOLINTEND(bugprone-unused-raii)
1189
1190 std::string item = name.as_std_string("ascii");
1191 PyObject* wb
1192 = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, item.c_str());
1193 if (wb) {
1194 PyErr_Format(PyExc_KeyError, "'%s' already exists.", item.c_str());
1195 return nullptr;
1196 }
1197
1198 PyDict_SetItemString(Application::Instance->_pcWorkbenchDictionary, item.c_str(), object.ptr());
1199 Application::Instance->signalRefreshWorkbenches();
1200 }
1201 catch (const Py::Exception&) {
1202 return nullptr;
1203 }
1204
1205 Py_Return;
1206 }
1207
1208 PyObject* ApplicationPy::sRemoveWorkbenchHandler(PyObject* /*self*/, PyObject* args)
1209 {
1210 char* psKey = nullptr;
1211 if (!PyArg_ParseTuple(args, "s", &psKey)) {
1212 return nullptr;
1213 }
1214
1215 PyObject* wb = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, psKey);
1216 if (!wb) {
1217 PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
1218 return nullptr;
1219 }
1220
1221 WorkbenchManager::instance()->removeWorkbench(psKey);
1222 PyDict_DelItemString(Application::Instance->_pcWorkbenchDictionary, psKey);
1223 Application::Instance->signalRefreshWorkbenches();
1224
1225 Py_Return;
1226 }
1227
1228 PyObject* ApplicationPy::sGetWorkbenchHandler(PyObject* /*self*/, PyObject* args)
1229 {
1230 char* psKey = nullptr;
1231 if (!PyArg_ParseTuple(args, "s", &psKey)) {
1232 return nullptr;
1233 }
1234
1235 // get the python workbench object from the dictionary
1236 PyObject* pcWorkbench = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, psKey);
1237 if (!pcWorkbench) {
1238 PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey);
1239 return nullptr;
1240 }
1241
1242 Py_INCREF(pcWorkbench);
1243 return pcWorkbench;
1244 }
1245
1246 PyObject* ApplicationPy::sListWorkbenchHandlers(PyObject* /*self*/, PyObject* args)
1247 {
1248 if (!PyArg_ParseTuple(args, "")) {
1249 return nullptr;
1250 }
1251
1252 Py_INCREF(Application::Instance->_pcWorkbenchDictionary);
1253 return Application::Instance->_pcWorkbenchDictionary;
1254 }
1255
1256 PyObject* ApplicationPy::sActiveWorkbenchHandler(PyObject* /*self*/, PyObject* args)
1257 {
1258 if (!PyArg_ParseTuple(args, "")) {
1259 return nullptr;
1260 }
1261
1262 Workbench* actWb = WorkbenchManager::instance()->active();
1263 if (!actWb) {
1264 PyErr_SetString(PyExc_AssertionError, "No active workbench\n");
1265 return nullptr;
1266 }
1267
1268 // get the python workbench object from the dictionary
1269 std::string key = actWb->name();
1270 PyObject* pcWorkbench
1271 = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, key.c_str());
1272 if (!pcWorkbench) {
1273 PyErr_Format(PyExc_KeyError, "No such workbench '%s'", key.c_str());
1274 return nullptr;
1275 }
1276
1277 // object get incremented
1278 Py_INCREF(pcWorkbench);
1279 return pcWorkbench;
1280 }
1281
1282 PyObject* ApplicationPy::sAddResPath(PyObject* /*self*/, PyObject* args)
1283 {
1284 char* filePath = nullptr;
1285 if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) {
1286 return nullptr;
1287 }
1288
1289 QString path = QString::fromUtf8(filePath);
1290 PyMem_Free(filePath);
1291 if (QDir::isRelativePath(path)) {
1292 // Home path ends with '/'
1293 QString home = QString::fromStdString(App::Application::getHomePath());
1294 path = home + path;
1295 }
1296
1297 BitmapFactory().addPath(path);
1298 Translator::instance()->addPath(path);
1299
1300 Py_Return;
1301 }
1302
1303 PyObject* ApplicationPy::sAddLangPath(PyObject* /*self*/, PyObject* args)
1304 {
1305 char* filePath = nullptr;
1306 if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) {
1307 return nullptr;
1308 }
1309
1310 QString path = QString::fromUtf8(filePath);
1311 PyMem_Free(filePath);
1312 if (QDir::isRelativePath(path)) {
1313 // Home path ends with '/'
1314 QString home = QString::fromStdString(App::Application::getHomePath());
1315 path = home + path;
1316 }
1317
1318 Translator::instance()->addPath(path);
1319
1320 Py_Return;
1321 }
1322
1323 PyObject* ApplicationPy::sAddIconPath(PyObject* /*self*/, PyObject* args)
1324 {
1325 char* filePath = nullptr;
1326 if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) {
1327 return nullptr;
1328 }
1329
1330 QString path = QString::fromUtf8(filePath);
1331 PyMem_Free(filePath);
1332 if (QDir::isRelativePath(path)) {
1333 // Home path ends with '/'
1334 QString home = QString::fromStdString(App::Application::getHomePath());
1335 path = home + path;
1336 }
1337
1338 BitmapFactory().addPath(path);
1339
1340 Py_Return;
1341 }
1342
1343 PyObject* ApplicationPy::sAddIcon(PyObject* /*self*/, PyObject* args)
1344 {
1345 const char* iconName = nullptr;
1346 Py_buffer content;
1347 const char* format = "XPM";
1348 if (!PyArg_ParseTuple(args, "ss*|s", &iconName, &content, &format)) {
1349 return nullptr;
1350 }
1351
1352 QPixmap icon;
1353 if (BitmapFactory().findPixmapInCache(iconName, icon)) {
1354 PyErr_SetString(PyExc_AssertionError, "Icon with this name already registered");
1355 PyBuffer_Release(&content);
1356 return nullptr;
1357 }
1358
1359 const char* contentStr = static_cast<const char*>(content.buf);
1360 QByteArray ary(contentStr, static_cast<int>(content.len));
1361 icon.loadFromData(ary, format);
1362
1363 if (icon.isNull()) {
1364 QString file = QString::fromUtf8(contentStr, static_cast<int>(content.len));
1365 icon.load(file);
1366 }
1367
1368 PyBuffer_Release(&content);
1369
1370 if (icon.isNull()) {
1371 PyErr_SetString(Base::PyExc_FC_GeneralError, "Invalid icon added to application");
1372 return nullptr;
1373 }
1374
1375 BitmapFactory().addPixmapToCache(iconName, icon);
1376
1377 Py_Return;
1378 }
1379
1380 PyObject* ApplicationPy::sGetIcon(PyObject* /*self*/, PyObject* args)
1381 {
1382 char* iconName = nullptr;
1383 if (!PyArg_ParseTuple(args, "s", &iconName)) {
1384 return nullptr;
1385 }
1386
1387 PythonWrapper wrap;
1388 wrap.loadGuiModule();
1389 wrap.loadWidgetsModule();
1390 auto pixmap = BitmapFactory().pixmap(iconName);
1391 if (!pixmap.isNull()) {
1392 return Py::new_reference_to(wrap.fromQIcon(new QIcon(pixmap)));
1393 }
1394
1395 Py_Return;
1396 }
1397
1398 PyObject* ApplicationPy::sIsIconCached(PyObject* /*self*/, PyObject* args)
1399 {
1400 char* iconName = nullptr;
1401 if (!PyArg_ParseTuple(args, "s", &iconName)) {
1402 return nullptr;
1403 }
1404
1405 QPixmap icon;
1406
1407 return Py::new_reference_to(Py::Boolean(BitmapFactory().findPixmapInCache(iconName, icon)));
1408 }
1409
1410 PyObject* ApplicationPy::sAddCommand(PyObject* /*self*/, PyObject* args)
1411 {
1412 char* pName = nullptr;
1413 char* pSource = nullptr;
1414 PyObject* pcCmdObj = nullptr;
1415 if (!PyArg_ParseTuple(args, "sO|s", &pName, &pcCmdObj, &pSource)) {
1416 return nullptr;
1417 }
1418
1419 // get the call stack to find the Python module name
1420 //
1421 std::string module;
1422 std::string group;
1423 try {
1424 Base::PyGILStateLocker lock;
1425
1426 // Get the filename of the running code by using the low-level sys._getframe() method.
1427 // We use this instead of the `inspect` module (which may actually cause imports to execute
1428 // and can result in a circular import if sAddCommand is being called as part of an import
1429 // statement itself), and the `traceback` module (which cannot access the filename of code
1430 // that is being run through the C interface).
1431
1432 Py::Module sysMod(PyImport_ImportModule("sys"), /*owned=*/true);
1433 Py::Callable getFrame(sysMod.getAttr("_getframe"));
1434
1435 Py::Object callerFrame;
1436 Py::Tuple getFrameArgs(1);
1437 getFrameArgs[0] = Py::Long(0);
1438 callerFrame = getFrame.apply(getFrameArgs);
1439
1440 Py::Object codeObj(callerFrame.getAttr("f_code"));
1441
1442 Py::Object filenameObj(codeObj.getAttr("co_filename"));
1443 std::string filename(Py::String(filenameObj).as_std_string());
1444
1445 Base::FileInfo fi(filename);
1446 // convert backslashes to slashes
1447 filename = fi.filePath();
1448 module = fi.fileNamePure();
1449 // for the group name get the directory name after 'Mod'
1450 boost::regex rx("/Mod/(\\w+)/");
1451 boost::smatch what;
1452 if (boost::regex_search(filename, what, rx)) {
1453 group = what[1];
1454 }
1455 else {
1456 rx = "/Ext/freecad/(\\w+)/";
1457 if (boost::regex_search(filename, what, rx)) {
1458 group = what[1];
1459 }
1460 else {
1461 group = module;
1462 }
1463 }
1464 }
1465 catch (Py::Exception& e) {
1466 e.clear();
1467 }
1468 try {
1469 Base::PyGILStateLocker lock;
1470
1471 Py::Object cmd(pcCmdObj);
1472 if (cmd.hasAttr("GetCommands")) {
1473 Command* cmd = new PythonGroupCommand(pName, pcCmdObj);
1474 if (!module.empty()) {
1475 cmd->setAppModuleName(module.c_str());
1476 }
1477 if (!group.empty()) {
1478 cmd->setGroupName(group.c_str());
1479 }
1480 Application::Instance->commandManager().addCommand(cmd);
1481 }
1482 else {
1483 Command* cmd = new PythonCommand(pName, pcCmdObj, pSource);
1484 if (!module.empty()) {
1485 cmd->setAppModuleName(module.c_str());
1486 }
1487 if (!group.empty()) {
1488 cmd->setGroupName(group.c_str());
1489 }
1490 Application::Instance->commandManager().addCommand(cmd);
1491 }
1492 }
1493 catch (const Base::Exception& e) {
1494 e.setPyException();
1495 return nullptr;
1496 }
1497 catch (...) {
1498 PyErr_SetString(
1499 Base::PyExc_FC_GeneralError,
1500 "Unknown C++ exception raised in ApplicationPy::sAddCommand()"
1501 );
1502 return nullptr;
1503 }
1504
1505 Py_Return;
1506 }
1507
1508 PyObject* ApplicationPy::sRunCommand(PyObject* /*self*/, PyObject* args)
1509 {
1510 char* pName = nullptr;
1511 int item = 0;
1512 if (!PyArg_ParseTuple(args, "s|i", &pName, &item)) {
1513 return nullptr;
1514 }
1515
1516 Gui::Command::LogDisabler d1;
1517 Gui::SelectionLogDisabler d2;
1518
1519 Command* cmd = Application::Instance->commandManager().getCommandByName(pName);
1520 if (cmd) {
1521 cmd->invoke(item);
1522 Py_Return;
1523 }
1524
1525 PyErr_Format(Base::PyExc_FC_GeneralError, "No such command '%s'", pName);
1526 return nullptr;
1527 }
1528
1529 PyObject* ApplicationPy::sDoCommand(PyObject* /*self*/, PyObject* args)
1530 {
1531 char* sCmd = nullptr;
1532 if (!PyArg_ParseTuple(args, "s", &sCmd)) {
1533 return nullptr;
1534 }
1535
1536 Gui::Command::LogDisabler d1;
1537 Gui::SelectionLogDisabler d2;
1538
1539 Gui::Command::printPyCaller();
1540 Gui::Application::Instance->macroManager()->addLine(MacroManager::App, sCmd);
1541
1542 PyObject* module = nullptr;
1543 PyObject* dict = nullptr;
1544
1545 Base::PyGILStateLocker locker;
1546 module = PyImport_AddModule("__main__");
1547 if (!module) {
1548 return nullptr;
1549 }
1550
1551 dict = PyModule_GetDict(module);
1552 if (!dict) {
1553 return nullptr;
1554 }
1555
1556 return PyRun_String(sCmd, Py_file_input, dict, dict);
1557 }
1558
1559 PyObject* ApplicationPy::sDoCommandGui(PyObject* /*self*/, PyObject* args)
1560 {
1561 char* sCmd = nullptr;
1562 if (!PyArg_ParseTuple(args, "s", &sCmd)) {
1563 return nullptr;
1564 }
1565
1566 Gui::Command::LogDisabler d1;
1567 Gui::SelectionLogDisabler d2;
1568
1569 Gui::Command::printPyCaller();
1570 Gui::Application::Instance->macroManager()->addLine(MacroManager::Gui, sCmd);
1571
1572 PyObject* module = nullptr;
1573 PyObject* dict = nullptr;
1574
1575 Base::PyGILStateLocker locker;
1576 module = PyImport_AddModule("__main__");
1577 if (!module) {
1578 return nullptr;
1579 }
1580
1581 dict = PyModule_GetDict(module);
1582 if (!dict) {
1583 return nullptr;
1584 }
1585
1586 return PyRun_String(sCmd, Py_file_input, dict, dict);
1587 }
1588
1589 PyObject* ApplicationPy::sDoCommandEval(PyObject* /*self*/, PyObject* args)
1590 {
1591 char* sCmd = nullptr;
1592 if (!PyArg_ParseTuple(args, "s", &sCmd)) {
1593 return nullptr;
1594 }
1595
1596 Gui::Command::LogDisabler d1;
1597 Gui::SelectionLogDisabler d2;
1598
1599 PyObject* module = nullptr;
1600 PyObject* dict = nullptr;
1601
1602 Base::PyGILStateLocker locker;
1603 module = PyImport_AddModule("__main__");
1604 if (!module) {
1605 return nullptr;
1606 }
1607
1608 dict = PyModule_GetDict(module);
1609 if (!dict) {
1610 return nullptr;
1611 }
1612
1613 return PyRun_String(sCmd, Py_eval_input, dict, dict);
1614 }
1615
1616 PyObject* ApplicationPy::sDoCommandSkip(PyObject* /*self*/, PyObject* args)
1617 {
1618 char* sCmd = nullptr;
1619 if (!PyArg_ParseTuple(args, "s", &sCmd)) {
1620 return nullptr;
1621 }
1622
1623 Gui::Command::LogDisabler d1;
1624 Gui::SelectionLogDisabler d2;
1625
1626 Gui::Command::printPyCaller();
1627 Gui::Application::Instance->macroManager()->addLine(MacroManager::App, sCmd);
1628 return Py::None().ptr();
1629 }
1630
1631 PyObject* ApplicationPy::sAddModule(PyObject* /*self*/, PyObject* args)
1632 {
1633 char* pstr = nullptr;
1634 if (!PyArg_ParseTuple(args, "s", &pstr)) {
1635 return nullptr;
1636 }
1637
1638 try {
1639 Command::addModule(Command::Doc, pstr);
1640 Py_Return;
1641 }
1642 catch (const Base::Exception& e) {
1643 PyErr_SetString(PyExc_ImportError, e.what());
1644 return nullptr;
1645 }
1646 }
1647
1648 PyObject* ApplicationPy::sShowDownloads(PyObject* /*self*/, PyObject* args)
1649 {
1650 if (!PyArg_ParseTuple(args, "")) {
1651 return nullptr;
1652 }
1653
1654 Gui::Dialog::DownloadManager::getInstance();
1655
1656 Py_Return;
1657 }
1658
1659 PyObject* ApplicationPy::sShowPreferences(PyObject* /*self*/, PyObject* args)
1660 {
1661 char* pstr = nullptr;
1662 int idx = 0;
1663 if (!PyArg_ParseTuple(args, "|si", &pstr, &idx)) {
1664 return nullptr;
1665 }
1666
1667 Gui::Dialog::DlgPreferencesImp cDlg(getMainWindow());
1668 if (pstr) {
1669 cDlg.activateGroupPage(QString::fromUtf8(pstr), idx);
1670 }
1671
1672 WaitCursor wc;
1673 wc.restoreCursor();
1674 cDlg.exec();
1675 wc.setWaitCursor();
1676
1677 Py_Return;
1678 }
1679
1680 PyObject* ApplicationPy::sShowPreferencesByName(PyObject* /*self*/, PyObject* args)
1681 {
1682 char* pstr = nullptr;
1683 const char* prefType = "";
1684 if (!PyArg_ParseTuple(args, "s|s", &pstr, &prefType)) {
1685 return nullptr;
1686 }
1687
1688 Gui::Dialog::DlgPreferencesImp cDlg(getMainWindow());
1689 if (pstr && prefType) {
1690 cDlg.activateGroupPageByPageName(QString::fromUtf8(pstr), QString::fromUtf8(prefType));
1691 }
1692
1693 WaitCursor wc;
1694 wc.restoreCursor();
1695 cDlg.exec();
1696 wc.setWaitCursor();
1697
1698 Py_Return;
1699 }
1700
1701 PyObject* ApplicationPy::sCreateViewer(PyObject* /*self*/, PyObject* args)
1702 {
1703 int num_of_views = 1;
1704 char* title = nullptr;
1705 // if one argument (int) is given
1706 if (!PyArg_ParseTuple(args, "|is", &num_of_views, &title)) {
1707 return nullptr;
1708 }
1709
1710 if (num_of_views <= 0) {
1711 PyErr_Format(PyExc_ValueError, "views must be > 0");
1712 return nullptr;
1713 }
1714 if (num_of_views == 1) {
1715 auto viewer = new View3DInventor(nullptr, nullptr);
1716 if (title) {
1717 viewer->setWindowTitle(QString::fromUtf8(title));
1718 }
1719 Gui::getMainWindow()->addWindow(viewer);
1720 return viewer->getPyObject();
1721 }
1722 else {
1723 auto viewer = new SplitView3DInventor(num_of_views, nullptr, nullptr);
1724 if (title) {
1725 viewer->setWindowTitle(QString::fromUtf8(title));
1726 }
1727 Gui::getMainWindow()->addWindow(viewer);
1728 return viewer->getPyObject();
1729 }
1730 }
1731
1732 PyObject* ApplicationPy::sGetMarkerIndex(PyObject* /*self*/, PyObject* args)
1733 {
1734 constexpr const int defaultSize = 9;
1735 char* pstr {};
1736 int defSize = defaultSize;
1737 if (!PyArg_ParseTuple(args, "s|i", &pstr, &defSize)) {
1738 return nullptr;
1739 }
1740
1741 PY_TRY
1742 {
1743 ParameterGrp::handle const hGrp = App::GetApplication().GetParameterGroupByPath(
1744 "User parameter:BaseApp/Preferences/View"
1745 );
1746
1747 // find the appropriate marker style string token
1748 std::string marker_arg = pstr;
1749
1750 std::list<std::pair<std::string, std::string>> markerList = {
1751 {"square", "DIAMOND_FILLED"},
1752 {"cross", "CROSS"},
1753 {"hourglass", "HOURGLASS_FILLED"},
1754 {"plus", "PLUS"},
1755 {"empty", "SQUARE_LINE"},
1756 {"quad", "SQUARE_FILLED"},
1757 {"circle", "CIRCLE_LINE"},
1758 {"default", "CIRCLE_FILLED"}
1759 };
1760
1761 auto findIt = std::find_if(markerList.begin(), markerList.end(), [&marker_arg](const auto& it) {
1762 return marker_arg == it.first || marker_arg == it.second;
1763 });
1764
1765 marker_arg = (findIt != markerList.end() ? findIt->second : "CIRCLE_FILLED");
1766
1767
1768 // get the marker size
1769 auto sizeList = Gui::Inventor::MarkerBitmaps::getSupportedSizes(marker_arg);
1770
1771 if (std::ranges::find(sizeList, defSize) == std::end(sizeList)) {
1772 defSize = defaultSize;
1773 }
1774
1775 return Py_BuildValue("i", Gui::Inventor::MarkerBitmaps::getMarkerIndex(marker_arg, defSize));
1776 }
1777 PY_CATCH;
1778 }
1779
1780 PyObject* ApplicationPy::sReload(PyObject* /*self*/, PyObject* args)
1781 {
1782 const char* name = nullptr;
1783 if (!PyArg_ParseTuple(args, "s", &name)) {
1784 return nullptr;
1785 }
1786
1787 PY_TRY
1788 {
1789 auto doc = Application::Instance->reopen(App::GetApplication().getDocument(name));
1790 if (doc) {
1791 return doc->getPyObject();
1792 }
1793 Py_Return;
1794 }
1795 PY_CATCH;
1796 }
1797
1798 PyObject* ApplicationPy::sLoadFile(PyObject* /*self*/, PyObject* args)
1799 {
1800 const char* path = "";
1801 const char* mod = "";
1802 if (!PyArg_ParseTuple(args, "s|s", &path, &mod)) {
1803 return nullptr;
1804 }
1805
1806 PY_TRY
1807 {
1808 Base::FileInfo fi(path);
1809 if (!fi.isFile() || !fi.exists()) {
1810 PyErr_Format(PyExc_IOError, "File %s doesn't exist.", path);
1811 return nullptr;
1812 }
1813
1814 std::string module = mod;
1815 if (module.empty()) {
1816 std::string ext = fi.extension();
1817 std::vector<std::string> modules = App::GetApplication().getImportModules(ext.c_str());
1818 if (modules.empty()) {
1819 PyErr_Format(PyExc_IOError, "Filetype %s is not supported.", ext.c_str());
1820 return nullptr;
1821 }
1822
1823 module = modules.front();
1824 }
1825
1826 Application::Instance->open(path, module.c_str());
1827
1828 Py_Return;
1829 }
1830 PY_CATCH
1831 }
1832
1833 PyObject* ApplicationPy::sAddDocObserver(PyObject* /*self*/, PyObject* args)
1834 {
1835 PyObject* o = nullptr;
1836 if (!PyArg_ParseTuple(args, "O", &o)) {
1837 return nullptr;
1838 }
1839
1840 PY_TRY
1841 {
1842 DocumentObserverPython::addObserver(Py::Object(o));
1843 Py_Return;
1844 }
1845 PY_CATCH;
1846 }
1847
1848 PyObject* ApplicationPy::sRemoveDocObserver(PyObject* /*self*/, PyObject* args)
1849 {
1850 PyObject* o = nullptr;
1851 if (!PyArg_ParseTuple(args, "O", &o)) {
1852 return nullptr;
1853 }
1854
1855 PY_TRY
1856 {
1857 DocumentObserverPython::removeObserver(Py::Object(o));
1858 Py_Return;
1859 }
1860 PY_CATCH;
1861 }
1862
1863 PyObject* ApplicationPy::sAddWbManipulator(PyObject* /*self*/, PyObject* args)
1864 {
1865 PyObject* o = nullptr;
1866 if (!PyArg_ParseTuple(args, "O", &o)) {
1867 return nullptr;
1868 }
1869
1870 PY_TRY
1871 {
1872 WorkbenchManipulatorPython::installManipulator(Py::Object(o));
1873 Py_Return;
1874 }
1875 PY_CATCH;
1876 }
1877
1878 PyObject* ApplicationPy::sRemoveWbManipulator(PyObject* /*self*/, PyObject* args)
1879 {
1880 PyObject* o = nullptr;
1881 if (!PyArg_ParseTuple(args, "O", &o)) {
1882 return nullptr;
1883 }
1884
1885 PY_TRY
1886 {
1887 WorkbenchManipulatorPython::removeManipulator(Py::Object(o));
1888 Py_Return;
1889 }
1890 PY_CATCH;
1891 }
1892
1893 PyObject* ApplicationPy::sCoinRemoveAllChildren(PyObject* /*self*/, PyObject* args)
1894 {
1895 PyObject* pynode = nullptr;
1896 if (!PyArg_ParseTuple(args, "O", &pynode)) {
1897 return nullptr;
1898 }
1899
1900 PY_TRY
1901 {
1902 void* ptr = nullptr;
1903 Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoGroup", pynode, &ptr, 0);
1904 if (!ptr) {
1905 PyErr_SetString(PyExc_RuntimeError, "Conversion of coin.SoGroup failed");
1906 return nullptr;
1907 }
1908
1909 coinRemoveAllChildren(static_cast<SoGroup*>(ptr));
1910 Py_Return;
1911 }
1912 PY_CATCH;
1913 }
1914
1915 PyObject* ApplicationPy::sListUserEditModes(PyObject* /*self*/, PyObject* args)
1916 {
1917 Py::List ret;
1918 if (!PyArg_ParseTuple(args, "")) {
1919 return nullptr;
1920 }
1921
1922 for (auto const& uem : Application::Instance->listUserEditModes()) {
1923 ret.append(Py::String(uem.second.first));
1924 }
1925
1926 return Py::new_reference_to(ret);
1927 }
1928
1929 PyObject* ApplicationPy::sGetUserEditMode(PyObject* /*self*/, PyObject* args)
1930 {
1931 if (!PyArg_ParseTuple(args, "")) {
1932 return nullptr;
1933 }
1934
1935 return Py::new_reference_to(Py::String(Application::Instance->getUserEditModeUIStrings().first));
1936 }
1937
1938 PyObject* ApplicationPy::sSetUserEditMode(PyObject* /*self*/, PyObject* args)
1939 {
1940 const char* mode = "";
1941 if (!PyArg_ParseTuple(args, "s", &mode)) {
1942 return nullptr;
1943 }
1944
1945 bool ok = Application::Instance->setUserEditMode(std::string(mode));
1946
1947 return Py::new_reference_to(Py::Boolean(ok));
1948 }
1949
1950 PyObject* ApplicationPy::sSuspendWaitCursor(PyObject* /*self*/, PyObject* args)
1951 {
1952 if (!PyArg_ParseTuple(args, "")) {
1953 return nullptr;
1954 }
1955
1956 WaitCursor::suspend();
1957 Py_RETURN_NONE;
1958 }
1959
1960 PyObject* ApplicationPy::sResumeWaitCursor(PyObject* /*self*/, PyObject* args)
1961 {
1962 if (!PyArg_ParseTuple(args, "")) {
1963 return nullptr;
1964 }
1965
1966 WaitCursor::resume();
1967 Py_RETURN_NONE;
1968 }