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