diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 3629898fad..f80ed08a02 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -24,4 +24,4 @@ jobs: - name: 'Checkout Repository' uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: 'Dependency Review' - uses: actions/dependency-review-action@67d4f4bd7a9b17a0db54d2a7519187c65e339de8 # v4 + uses: actions/dependency-review-action@8805179dc9a63c54224914839d370dd93bd37b2e # v4 diff --git a/.github/workflows/issue-metrics.yml b/.github/workflows/issue-metrics.yml index 9cb9f0eacc..f89d4c4233 100644 --- a/.github/workflows/issue-metrics.yml +++ b/.github/workflows/issue-metrics.yml @@ -35,7 +35,7 @@ jobs: echo "last_month=$first_day..$last_day" >> "$GITHUB_ENV" - name: Run issue-metrics tool - uses: github/issue-metrics@ed6e4b2b46f44ec7cdd2f6c145757a67a07ecf5b # v3.18.4 + uses: github/issue-metrics@6a0f49b4e14363b63e65ec698b43715b69d21f6d # v3.20.0 env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} SEARCH_QUERY: 'repo:FreeCAD/FreeCAD is:issue created:${{ env.last_month }}' diff --git a/.github/workflows/sub_lint.yml b/.github/workflows/sub_lint.yml index 913f8b50fa..afd485fd12 100644 --- a/.github/workflows/sub_lint.yml +++ b/.github/workflows/sub_lint.yml @@ -208,7 +208,7 @@ jobs: # Generic lints steps - name: Check File Case Sensitivity - uses: credfeto/action-case-checker@v1.3.0 + uses: credfeto/action-case-checker@cb652aeab29ed363bbdb7d9ee1bfcc010c46cac5 # v1.3.0 - name: Check for non Unix line ending if: inputs.checkLineendings && always() diff --git a/.github/workflows/sub_weeklyBuild.yml b/.github/workflows/sub_weeklyBuild.yml index eed068c6d8..7a78b7a024 100644 --- a/.github/workflows/sub_weeklyBuild.yml +++ b/.github/workflows/sub_weeklyBuild.yml @@ -2,6 +2,7 @@ name: Weekly Build on: schedule: - cron: "42 18 * * 1" + workflow_dispatch: permissions: contents: write @@ -25,6 +26,8 @@ jobs: - name: Tag Build id: tag_build shell: bash -l {0} + env: + GH_TOKEN: ${{ github.token }} run: | export BUILD_TAG=weekly-$(date "+%Y.%m.%d") echo "BUILD_TAG=${BUILD_TAG}" >> "$GITHUB_ENV" @@ -32,6 +35,7 @@ jobs: gh release create ${BUILD_TAG} --title "Development Build ${BUILD_TAG}" -F .github/workflows/weekly-build-notes.md --prerelease || true - name: Upload Source + shell: bash -l {0} env: GH_TOKEN: ${{ github.token }} run: | @@ -67,7 +71,7 @@ jobs: # prevent running out of disk space on Ubuntu runners. - name: Maximize build space if: runner.os == 'Linux' - uses: AdityaGarg8/remove-unwanted-software@v5 + uses: AdityaGarg8/remove-unwanted-software@90e01b21170618765a73370fcc3abbd1684a7793 # v5 with: verbose: 'true' remove-android: 'true' # (frees ~9 GB) diff --git a/.github/workflows/weekly-build-notes.md b/.github/workflows/weekly-build-notes.md index 17e55cbfc1..35175110fd 100644 --- a/.github/workflows/weekly-build-notes.md +++ b/.github/workflows/weekly-build-notes.md @@ -1,21 +1,15 @@ -# Weekly Development Build +> [!IMPORTANT] +> Bleeding edge FreeCAD development builds for testing bugfixes, regressions, and recently implemented features. Do not use in a production environment. -## How-to use -Download the appropriate asset for your OS below - -Unpack the bundle to any folder on your system - -Launch the application - -* **Windows** +### How-to use +1. Download the appropriate asset for your OS below +2. Unpack the bundle to any folder on your system +3. Launch the application + - **Windows** Run `\bin\FreeCAD.exe` in the extracted directory - -* **macOS** - + - **macOS** Launch `/FreeCAD.app` in the extracted directory - -* **Linux** - - Open the *.AppImage + - **Linux** + Open the `*.AppImage` diff --git a/.gitmodules b/.gitmodules index e6a738fdf5..9bad1a2147 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "src/3rdParty/OndselSolver"] path = src/3rdParty/OndselSolver - url = https://github.com/Ondsel-Development/OndselSolver.git + url = https://github.com/FreeCAD/OndselSolver.git [submodule "tests/lib"] path = tests/lib url = https://github.com/google/googletest diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 36430fd6c0..46b5656e67 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -67,6 +67,6 @@ repos: - id: black args: ['--line-length', '100'] - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 458d954d175f16d216d7d04d5c182e3b10ddfbb4 # frozen: v20.1.0 + rev: 7ec07eeb4135dc6ecf410d24ac4ead986a5d413d # frozen: v20.1.3 hooks: - id: clang-format diff --git a/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake b/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake index dfb29f1e56..9165be9771 100644 --- a/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake +++ b/cMake/FreeCAD_Helpers/InitializeFreeCADBuildOptions.cmake @@ -11,6 +11,7 @@ macro(InitializeFreeCADBuildOptions) option(FREECAD_USE_EXTERNAL_FMT "Use system installed fmt library if available instead of fetching the source." ON) option(FREECAD_USE_EXTERNAL_ONDSELSOLVER "Use system installed OndselSolver instead of git submodule." OFF) option(FREECAD_USE_EXTERNAL_E57FORMAT "Use system installed libE57Format instead of the bundled." OFF) + option(FREECAD_USE_EXTERNAL_GTEST "Use system installed Google Test and Google Mock" OFF) option(FREECAD_USE_FREETYPE "Builds the features using FreeType libs" ON) option(FREECAD_BUILD_DEBIAN "Prepare for a build of a Debian package" OFF) option(FREECAD_CHECK_PIVY "Check for pivy version using Python at build time" ON) @@ -180,7 +181,7 @@ macro(InitializeFreeCADBuildOptions) endif(MSVC) if(NOT MSVC) option(BUILD_FEM_NETGEN "Build the FreeCAD FEM module with the NETGEN mesher" OFF) - option(FREECAD_USE_PCL "Build the features that use PCL libs" ON) + option(FREECAD_USE_PCL "Build the features that use PCL libs" OFF) endif(NOT MSVC) # if this is set override some options diff --git a/cMake/FreeCAD_Helpers/SetupSalomeSMESH.cmake b/cMake/FreeCAD_Helpers/SetupSalomeSMESH.cmake index 8db55febb1..fa7a20daf3 100644 --- a/cMake/FreeCAD_Helpers/SetupSalomeSMESH.cmake +++ b/cMake/FreeCAD_Helpers/SetupSalomeSMESH.cmake @@ -42,7 +42,7 @@ macro(SetupSalomeSMESH) endif() endforeach() else() - set(VTK_COMPONENTS "CommonCore;CommonDataModel;FiltersVerdict;IOXML;FiltersCore;FiltersGeneral;IOLegacy;FiltersExtraction;FiltersSources;FiltersGeometry") + set(VTK_COMPONENTS "CommonCore;CommonDataModel;FiltersVerdict;IOXML;FiltersCore;FiltersGeneral;IOLegacy;FiltersExtraction;FiltersSources;FiltersGeometry;WrappingPythonCore") list(APPEND VTK_COMPONENTS "IOMPIParallel;ParallelMPI;hdf5;FiltersParallelDIY2;RenderingCore;InteractionStyle;RenderingFreeType;RenderingOpenGL2") foreach(_module ${VTK_COMPONENTS}) list (FIND VTK_AVAILABLE_COMPONENTS ${_module} _index) @@ -63,6 +63,17 @@ macro(SetupSalomeSMESH) endif() set(BUILD_FEM_VTK ON) + + # Check if PythonWrapperCore was found + # Note: VTK 9 only, as the implementations use the VTK modules introduced in 8.1 + # VTK_WrappingPythonCore_FOUND is named differently for versions <9.0 + if (${VTK_WrappingPythonCore_FOUND}) + set(BUILD_FEM_VTK_PYTHON 1) + message(STATUS "VTK python wrapper: available") + else() + message(STATUS "VTK python wrapper: NOT available") + endif() + if(${VTK_MAJOR_VERSION} LESS 6) message( FATAL_ERROR "Found VTK version is <6, this is not compatible" ) endif() diff --git a/package/rattler-build/linux/AppDir/AppRun b/package/rattler-build/linux/AppDir/AppRun index 2389a99b76..f118738801 100755 --- a/package/rattler-build/linux/AppDir/AppRun +++ b/package/rattler-build/linux/AppDir/AppRun @@ -9,6 +9,9 @@ export PATH_TO_FREECAD_LIBDIR=${HERE}/usr/lib export FONTCONFIG_FILE=/etc/fonts/fonts.conf export FONTCONFIG_PATH=/etc/fonts +# Fix: Use X to run on Wayland +export QT_QPA_PLATFORM=xcb + # Show packages info if DEBUG env variable is set if [ "$DEBUG" = 1 ]; then cat ${HERE}/packages.txt diff --git a/package/rattler-build/osx/launcher/FreeCAD.cpp b/package/rattler-build/osx/launcher/FreeCAD.cpp index 562acac4c3..8d0d45b7d0 100644 --- a/package/rattler-build/osx/launcher/FreeCAD.cpp +++ b/package/rattler-build/osx/launcher/FreeCAD.cpp @@ -28,10 +28,8 @@ int main(int argc, char *argv[], char *const *envp) { env["PYTHONHOME"] = prefix; env["FONTCONFIG_FILE"] = "/etc/fonts/fonts.conf"; env["FONTCONFIG_PATH"] = "/etc/fonts"; - env["LANG"] = "UTF-8"; // https://forum.freecad.org/viewtopic.php?f=22&t=42644 env["SSL_CERT_FILE"] = prefix + "/ssl/cacert.pem"; // https://forum.freecad.org/viewtopic.php?f=3&t=42825 env["GIT_SSL_CAINFO"] = prefix + "/ssl/cacert.pem"; - env["QT_MAC_WANTS_LAYER"] = "1"; char **new_env = new char*[env.size() + 1]; int i = 0; diff --git a/src/App/Application.cpp b/src/App/Application.cpp index 3e7d942e29..94ca4236a2 100644 --- a/src/App/Application.cpp +++ b/src/App/Application.cpp @@ -662,7 +662,7 @@ public: } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("~DocOpenGuard: Unexpected boost exception\n"); + Base::Console().warning("~DocOpenGuard: Unexpected boost exception\n"); } } } @@ -793,13 +793,13 @@ std::vector Application::openDocuments(const std::vector _objCount = -1; } catch (const Base::Exception &e) { - e.ReportException(); + e.reportException(); if (!errs && isMainDoc) throw; if (errs && isMainDoc) (*errs)[count] = e.what(); else - Base::Console().Error("Exception opening file: %s [%s]\n", name.c_str(), e.what()); + Base::Console().error("Exception opening file: %s [%s]\n", name.c_str(), e.what()); } catch (const std::exception &e) { if (!errs && isMainDoc) @@ -807,7 +807,7 @@ std::vector Application::openDocuments(const std::vector if (errs && isMainDoc) (*errs)[count] = e.what(); else - Base::Console().Error("Exception opening file: %s [%s]\n", name.c_str(), e.what()); + Base::Console().error("Exception opening file: %s [%s]\n", name.c_str(), e.what()); } catch (...) { if (errs) { @@ -857,7 +857,7 @@ std::vector Application::openDocuments(const std::vector try { docs = Document::getDependentDocuments(docs, true); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } for(auto it=docs.begin(); it!=docs.end();) { auto doc = *it; @@ -865,7 +865,7 @@ std::vector Application::openDocuments(const std::vector // It is possible that the newly opened document depends on an existing // document, which will be included with the above call to // Document::getDependentDocuments(). Make sure to exclude that. - if(!newDocs.count(doc)) { + if(!newDocs.contains(doc)) { it = docs.erase(it); continue; } @@ -1091,7 +1091,7 @@ Application::TransactionSignaller::~TransactionSignaller() { } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("~TransactionSignaller: Unexpected boost exception\n"); + Base::Console().warning("~TransactionSignaller: Unexpected boost exception\n"); } } } @@ -1701,21 +1701,21 @@ void Application::destruct() { // saving system parameter if (_pcSysParamMngr->IgnoreSave()) { - Base::Console().Warning("Discard system parameter\n"); + Base::Console().warning("Discard system parameter\n"); } else { - Base::Console().Log("Saving system parameter...\n"); + Base::Console().log("Saving system parameter...\n"); _pcSysParamMngr->SaveDocument(); - Base::Console().Log("Saving system parameter...done\n"); + Base::Console().log("Saving system parameter...done\n"); } // saving the User parameter if (_pcUserParamMngr->IgnoreSave()) { - Base::Console().Warning("Discard user parameter\n"); + Base::Console().warning("Discard user parameter\n"); } else { - Base::Console().Log("Saving user parameter...\n"); + Base::Console().log("Saving user parameter...\n"); _pcUserParamMngr->SaveDocument(); - Base::Console().Log("Saving user parameter...done\n"); + Base::Console().log("Saving user parameter...done\n"); } // now save all other parameter files @@ -1723,9 +1723,9 @@ void Application::destruct() for (const auto &it : paramMgr) { if ((it.second != _pcSysParamMngr) && (it.second != _pcUserParamMngr)) { if (it.second->HasSerializer() && !it.second->IgnoreSave()) { - Base::Console().Log("Saving %s...\n", it.first.c_str()); + Base::Console().log("Saving %s...\n", it.first.c_str()); it.second->SaveDocument(); - Base::Console().Log("Saving %s...done\n", it.first.c_str()); + Base::Console().log("Saving %s...done\n", it.first.c_str()); } } } @@ -1760,12 +1760,12 @@ void Application::destruct() void Application::destructObserver() { if ( _pConsoleObserverFile ) { - Base::Console().DetachObserver(_pConsoleObserverFile); + Base::Console().detachObserver(_pConsoleObserverFile); delete _pConsoleObserverFile; _pConsoleObserverFile = nullptr; } if ( _pConsoleObserverStd ) { - Base::Console().DetachObserver(_pConsoleObserverStd); + Base::Console().detachObserver(_pConsoleObserverStd); delete _pConsoleObserverStd; _pConsoleObserverStd = nullptr; } @@ -1902,7 +1902,7 @@ void my_se_translator_filter(unsigned int code, EXCEPTION_POINTERS* pExp) throw Base::AccessViolation(); case EXCEPTION_FLT_DIVIDE_BY_ZERO: case EXCEPTION_INT_DIVIDE_BY_ZERO: - Base::Console().Error("SEH exception (%u): Division by zero\n", code); + Base::Console().error("SEH exception (%u): Division by zero\n", code); return; } @@ -2352,7 +2352,7 @@ void parseProgramOptions(int ac, char ** av, const std::string& exe, boost::prog throw Base::UnknownProgramOption(str.str()); } - if (vm.count("help")) { + if (vm.contains("help")) { std::stringstream str; str << exe << '\n' << '\n'; str << "For a detailed description see https://www.freecad.org/wiki/Start_up_and_Configuration" << '\n'<<'\n'; @@ -2361,11 +2361,11 @@ void parseProgramOptions(int ac, char ** av, const std::string& exe, boost::prog throw Base::ProgramInformation(str.str()); } - if (vm.count("response-file")) { + if (vm.contains("response-file")) { // Load the file and tokenize it std::ifstream ifs(vm["response-file"].as().c_str()); if (!ifs) { - Base::Console().Error("Could no open the response file\n"); + Base::Console().error("Could no open the response file\n"); std::stringstream str; str << "Could no open the response file: '" << vm["response-file"].as() << "'" << '\n'; @@ -2387,14 +2387,14 @@ void parseProgramOptions(int ac, char ** av, const std::string& exe, boost::prog void processProgramOptions(const boost::program_options::variables_map& vm, std::map& mConfig) { - if (vm.count("version") && !vm.count("verbose")) { + if (vm.contains("version") && !vm.contains("verbose")) { std::stringstream str; str << mConfig["ExeName"] << " " << mConfig["ExeVersion"] << " Revision: " << mConfig["BuildRevision"] << '\n'; throw Base::ProgramInformation(str.str()); } - if (vm.count("module-path")) { + if (vm.contains("module-path")) { auto Mods = vm["module-path"].as< std::vector >(); std::string temp; for (const auto & It : Mods) @@ -2403,7 +2403,7 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: mConfig["AdditionalModulePaths"] = temp; } - if (vm.count("macro-path")) { + if (vm.contains("macro-path")) { std::vector Macros = vm["macro-path"].as< std::vector >(); std::string temp; for (const auto & It : Macros) @@ -2412,13 +2412,13 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: mConfig["AdditionalMacroPaths"] = std::move(temp); } - if (vm.count("python-path")) { + if (vm.contains("python-path")) { auto Paths = vm["python-path"].as< std::vector >(); for (const auto & It : Paths) Base::Interpreter().addPythonPath(It.c_str()); } - if (vm.count("disable-addon")) { + if (vm.contains("disable-addon")) { auto Addons = vm["disable-addon"].as< std::vector >(); std::string temp; for (const auto & It : Addons) { @@ -2428,7 +2428,7 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: mConfig["DisabledAddons"] = temp; } - if (vm.count("input-file")) { + if (vm.contains("input-file")) { auto files(vm["input-file"].as< std::vector >()); int OpenFileCount=0; for (const auto & It : files) { @@ -2443,34 +2443,34 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: mConfig["OpenFileCount"] = buffer.str(); } - if (vm.count("output")) { + if (vm.contains("output")) { mConfig["SaveFile"] = vm["output"].as(); } - if (vm.count("hidden")) { + if (vm.contains("hidden")) { mConfig["StartHidden"] = "1"; } - if (vm.count("write-log")) { + if (vm.contains("write-log")) { mConfig["LoggingFile"] = "1"; mConfig["LoggingFileName"] = mConfig["UserAppData"] + mConfig["ExeName"] + ".log"; } - if (vm.count("log-file")) { + if (vm.contains("log-file")) { mConfig["LoggingFile"] = "1"; mConfig["LoggingFileName"] = vm["log-file"].as(); } - if (vm.count("user-cfg")) { + if (vm.contains("user-cfg")) { mConfig["UserParameter"] = vm["user-cfg"].as(); } - if (vm.count("system-cfg")) { + if (vm.contains("system-cfg")) { mConfig["SystemParameter"] = vm["system-cfg"].as(); } - if (vm.count("run-test") || vm.count("run-open")) { - std::string testCase = vm.count("run-open") ? vm["run-open"].as() : vm["run-test"].as(); + if (vm.contains("run-test") || vm.contains("run-open")) { + std::string testCase = vm.contains("run-open") ? vm["run-open"].as() : vm["run-test"].as(); if ( "0" == testCase) { testCase = "TestApp.All"; @@ -2481,14 +2481,14 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: mConfig["TestCase"] = std::move(testCase); mConfig["RunMode"] = "Internal"; mConfig["ScriptFileName"] = "FreeCADTest"; - mConfig["ExitTests"] = vm.count("run-open") == 0 ? "yes" : "no"; + mConfig["ExitTests"] = vm.contains("run-open") ? "no" : "yes"; } - if (vm.count("single-instance")) { + if (vm.contains("single-instance")) { mConfig["SingleInstance"] = "1"; } - if (vm.count("dump-config")) { + if (vm.contains("dump-config")) { std::stringstream str; for (const auto & it : mConfig) { str << it.first << "=" << it.second << '\n'; @@ -2496,7 +2496,7 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: throw Base::ProgramInformation(str.str()); } - if (vm.count("get-config")) { + if (vm.contains("get-config")) { auto configKey = vm["get-config"].as(); std::stringstream str; std::map::iterator pos; @@ -2508,7 +2508,7 @@ void processProgramOptions(const boost::program_options::variables_map& vm, std: throw Base::ProgramInformation(str.str()); } - if (vm.count("set-config")) { + if (vm.contains("set-config")) { auto configKeyValue = vm["set-config"].as< std::vector >(); for (const auto& it : configKeyValue) { auto pos = it.find('='); @@ -2572,7 +2572,7 @@ void Application::initConfig(int argc, char ** argv) BOOST_SCOPE_EXIT_ALL(&) { // console-mode needs to be set (if possible) also in case parseProgramOptions // throws, as it's needed when reporting such exceptions - if (vm.count("console")) { + if (vm.contains("console")) { mConfig["Console"] = "1"; mConfig["RunMode"] = "Cmd"; } @@ -2580,14 +2580,14 @@ void Application::initConfig(int argc, char ** argv) parseProgramOptions(argc, argv, mConfig["ExeName"], vm); } - if (vm.count("keep-deprecated-paths")) { + if (vm.contains("keep-deprecated-paths")) { mConfig["KeepDeprecatedPaths"] = "1"; } // extract home paths ExtractUserPath(); - if (vm.count("safe-mode")) { + if (vm.contains("safe-mode")) { SafeMode::StartSafeMode(); } @@ -2629,7 +2629,7 @@ void Application::initConfig(int argc, char ** argv) if (!pythonpath.empty()) mConfig["PythonSearchPath"] = pythonpath; else - Base::Console().Warning("Encoding of Python paths failed\n"); + Base::Console().warning("Encoding of Python paths failed\n"); // Handle the options that have impact on the init process processProgramOptions(vm, mConfig); @@ -2637,7 +2637,7 @@ void Application::initConfig(int argc, char ** argv) // Init console =========================================================== Base::PyGILStateLocker lock; _pConsoleObserverStd = new Base::ConsoleObserverStd(); - Base::Console().AttachObserver(_pConsoleObserverStd); + Base::Console().attachObserver(_pConsoleObserverStd); if (mConfig["LoggingConsole"] != "1") { _pConsoleObserverStd->bMsg = false; _pConsoleObserverStd->bLog = false; @@ -2648,17 +2648,17 @@ void Application::initConfig(int argc, char ** argv) // file logging Init =========================================================== if (mConfig["LoggingFile"] == "1") { _pConsoleObserverFile = new Base::ConsoleObserverFile(mConfig["LoggingFileName"].c_str()); - Base::Console().AttachObserver(_pConsoleObserverFile); + Base::Console().attachObserver(_pConsoleObserverFile); } else _pConsoleObserverFile = nullptr; // Banner =========================================================== - if (mConfig["RunMode"] != "Cmd" && !(vm.count("verbose") && vm.count("version"))) { + if (mConfig["RunMode"] != "Cmd" && !(vm.contains("verbose") && vm.contains("version"))) { // Remove banner if FreeCAD is invoked via the -c command as regular // Python interpreter if (mConfig["Verbose"] != "Strict") - Base::Console().Message("%s %s, Libs: %s.%s.%s%sR%s\n%s", + Base::Console().message("%s %s, Libs: %s.%s.%s%sR%s\n%s", mConfig["ExeName"].c_str(), mConfig["ExeVersion"].c_str(), mConfig["BuildVersionMajor"].c_str(), @@ -2668,7 +2668,7 @@ void Application::initConfig(int argc, char ** argv) mConfig["BuildRevision"].c_str(), mConfig["CopyrightInfo"].c_str()); else - Base::Console().Message("%s %s, Libs: %s.%s.%s%sR%s\n", + Base::Console().message("%s %s, Libs: %s.%s.%s%sR%s\n", mConfig["ExeName"].c_str(), mConfig["ExeVersion"].c_str(), mConfig["BuildVersionMajor"].c_str(), @@ -2678,7 +2678,7 @@ void Application::initConfig(int argc, char ** argv) mConfig["BuildRevision"].c_str()); if (SafeMode::SafeModeEnabled()) { - Base::Console().Message("FreeCAD is running in _SAFE_MODE_.\n" + Base::Console().message("FreeCAD is running in _SAFE_MODE_.\n" "Safe mode temporarily disables your configurations and " "addons. Restart the application to exit safe mode.\n\n"); } @@ -2693,7 +2693,7 @@ void Application::initConfig(int argc, char ** argv) #ifndef FC_DEBUG if (v.second>=0) { hasDefault = true; - Base::Console().SetDefaultLogLevel(v.second); + Base::Console().setDefaultLogLevel(v.second); } #endif } @@ -2701,20 +2701,20 @@ void Application::initConfig(int argc, char ** argv) #ifdef FC_DEBUG if (v.second>=0) { hasDefault = true; - Base::Console().SetDefaultLogLevel(static_cast(v.second)); + Base::Console().setDefaultLogLevel(static_cast(v.second)); } #endif } else { - *Base::Console().GetLogLevel(v.first.c_str()) = static_cast(v.second); + *Base::Console().getLogLevel(v.first.c_str()) = static_cast(v.second); } } if (!hasDefault) { #ifdef FC_DEBUG - loglevelParam->SetInt("DebugDefault", Base::Console().LogLevel(-1)); + loglevelParam->SetInt("DebugDefault", Base::Console().logLevel(-1)); #else - loglevelParam->SetInt("Default", Base::Console().LogLevel(-1)); + loglevelParam->SetInt("Default", Base::Console().logLevel(-1)); #endif } @@ -2766,7 +2766,7 @@ void Application::initConfig(int argc, char ** argv) logStatus(); - if (vm.count("verbose") && vm.count("version")) { + if (vm.contains("verbose") && vm.contains("version")) { Application::_pcSingleton = new Application(mConfig); throw Base::ProgramInformation(Application::verboseVersionEmitMessage); } @@ -2789,31 +2789,29 @@ void Application::initApplication() // creating the application if (mConfig["Verbose"] != "Strict") - Base::Console().Log("Create Application\n"); + Base::Console().log("Create Application\n"); Application::_pcSingleton = new Application(mConfig); // set up Unit system default const ParameterGrp::handle hGrp = GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Units"); - Base::UnitsApi::setSchema(static_cast(hGrp->GetInt("UserSchema", 0))); - Base::UnitsApi::setDecimals(static_cast(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals()))); - - // In case we are using fractional inches, get user setting for min unit - const int denom = static_cast(hGrp->GetInt("FracInch", Base::QuantityFormat::getDefaultDenominator())); - Base::QuantityFormat::setDefaultDenominator(denom); + Base::UnitsApi::setSchema(hGrp->GetInt("UserSchema", Base::UnitsApi::getDefSchemaNum())); + Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); + Base::QuantityFormat::setDefaultDenominator( + hGrp->GetInt("FracInch", Base::QuantityFormat::getDefaultDenominator())); #if defined (_DEBUG) - Base::Console().Log("Application is built with debug information\n"); + Base::Console().log("Application is built with debug information\n"); #endif // starting the init script - Base::Console().Log("Run App init script\n"); + Base::Console().log("Run App init script\n"); try { Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("CMakeVariables")); Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADInit")); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } // seed randomizer @@ -2842,11 +2840,11 @@ std::list Application::getCmdLineFiles() std::list Application::processFiles(const std::list& files) { std::list processed; - Base::Console().Log("Init: Processing command line files\n"); + Base::Console().log("Init: Processing command line files\n"); for (const auto & it : files) { Base::FileInfo file(it); - Base::Console().Log("Init: Processing file: %s\n",file.filePath().c_str()); + Base::Console().log("Init: Processing file: %s\n",file.filePath().c_str()); try { if (file.hasExtension("fcstd") || file.hasExtension("std")) { @@ -2882,10 +2880,10 @@ std::list Application::processFiles(const std::list& f Base::Interpreter().runStringArg("%s.open(u\"%s\")",mods.front().c_str(), escapedstr.c_str()); processed.push_back(it); - Base::Console().Log("Command line open: %s.open(u\"%s\")\n",mods.front().c_str(),escapedstr.c_str()); + Base::Console().log("Command line open: %s.open(u\"%s\")\n",mods.front().c_str(),escapedstr.c_str()); } else if (file.exists()) { - Base::Console().Warning("File format not supported: %s \n", file.filePath().c_str()); + Base::Console().warning("File format not supported: %s \n", file.filePath().c_str()); } } } @@ -2893,10 +2891,10 @@ std::list Application::processFiles(const std::list& f throw; // re-throw to main() function } catch (const Base::Exception& e) { - Base::Console().Error("Exception while processing file: %s [%s]\n", file.filePath().c_str(), e.what()); + Base::Console().error("Exception while processing file: %s [%s]\n", file.filePath().c_str(), e.what()); } catch (...) { - Base::Console().Error("Unknown exception while processing file: %s \n", file.filePath().c_str()); + Base::Console().error("Unknown exception while processing file: %s \n", file.filePath().c_str()); } } @@ -2940,14 +2938,14 @@ void Application::processCmdLineFiles() ,mods.front().c_str(),output.c_str()); } else { - Base::Console().Warning("File format not supported: %s \n", output.c_str()); + Base::Console().warning("File format not supported: %s \n", output.c_str()); } } catch (const Base::Exception& e) { - Base::Console().Error("Exception while saving to file: %s [%s]\n", output.c_str(), e.what()); + Base::Console().error("Exception while saving to file: %s [%s]\n", output.c_str(), e.what()); } catch (...) { - Base::Console().Error("Unknown exception while saving to file: %s \n", output.c_str()); + Base::Console().error("Unknown exception while saving to file: %s \n", output.c_str()); } } } @@ -2963,15 +2961,15 @@ void Application::runApplication() } else if (mConfig["RunMode"] == "Internal") { // run internal script - Base::Console().Log("Running internal script:\n"); + Base::Console().log("Running internal script:\n"); Base::Interpreter().runString(Base::ScriptFactory().ProduceScript(mConfig["ScriptFileName"].c_str())); } else if (mConfig["RunMode"] == "Exit") { // getting out - Base::Console().Log("Exiting on purpose\n"); + Base::Console().log("Exiting on purpose\n"); } else { - Base::Console().Log("Unknown Run mode (%d) in main()?!?\n\n", mConfig["RunMode"].c_str()); + Base::Console().log("Unknown Run mode (%d) in main()?!?\n\n", mConfig["RunMode"].c_str()); } } @@ -2979,10 +2977,10 @@ void Application::logStatus() { const std::string time_str = boost::posix_time::to_simple_string( boost::posix_time::second_clock::local_time()); - Base::Console().Log("Time = %s\n", time_str.c_str()); + Base::Console().log("Time = %s\n", time_str.c_str()); for (const auto & It : mConfig) { - Base::Console().Log("%s = %s\n", It.first.c_str(), It.second.c_str()); + Base::Console().log("%s = %s\n", It.first.c_str(), It.second.c_str()); } } @@ -3006,8 +3004,8 @@ void Application::LoadParameters() if (_pcSysParamMngr->LoadOrCreateDocument() && mConfig["Verbose"] != "Strict") { // Configuration file optional when using as Python module if (!Py_IsInitialized()) { - Base::Console().Warning(" Parameter does not exist, writing initial one\n"); - Base::Console().Message(" This warning normally means that FreeCAD is running for the first time\n" + Base::Console().warning(" Parameter does not exist, writing initial one\n"); + Base::Console().message(" This warning normally means that FreeCAD is running for the first time\n" " or the configuration was deleted or moved. FreeCAD is generating the standard\n" " configuration.\n"); } @@ -3015,7 +3013,7 @@ void Application::LoadParameters() } catch (const Base::Exception& e) { // try to proceed with an empty XML document - Base::Console().Error("%s in file %s.\n" + Base::Console().error("%s in file %s.\n" "Continue with an empty configuration.\n", e.what(), mConfig["SystemParameter"].c_str()); _pcSysParamMngr->CreateDocument(); @@ -3040,8 +3038,8 @@ void Application::LoadParameters() // Configuration file optional when using as Python module if (!Py_IsInitialized()) { - Base::Console().Warning(" User settings do not exist, writing initial one\n"); - Base::Console().Message(" This warning normally means that FreeCAD is running for the first time\n" + Base::Console().warning(" User settings do not exist, writing initial one\n"); + Base::Console().message(" This warning normally means that FreeCAD is running for the first time\n" " or your configuration was deleted or moved. The system defaults\n" " will be automatically generated for you.\n"); } @@ -3049,7 +3047,7 @@ void Application::LoadParameters() } catch (const Base::Exception& e) { // try to proceed with an empty XML document - Base::Console().Error("%s in file %s.\n" + Base::Console().error("%s in file %s.\n" "Continue with an empty configuration.\n", e.what(), mConfig["UserParameter"].c_str()); _pcUserParamMngr->CreateDocument(); @@ -3290,7 +3288,7 @@ std::tuple getStandardPaths() void Application::ExtractUserPath() { - bool keepDeprecatedPaths = mConfig.count("KeepDeprecatedPaths") > 0; + bool keepDeprecatedPaths = mConfig.contains("KeepDeprecatedPaths"); // std paths mConfig["BinPath"] = mConfig["AppHomePath"] + "bin" + PATHSEP; @@ -3735,7 +3733,7 @@ void Application::getVerboseCommonInfo(QTextStream& str, const std::map= 0) { - Base::Console().SetDefaultLogLevel(l); + Base::Console().setDefaultLogLevel(l); } #endif } else if (strcmp(tag, "DebugDefault") == 0) { #ifdef FC_DEBUG if (l >= 0) { - Base::Console().SetDefaultLogLevel(l); + Base::Console().setDefaultLogLevel(l); } #endif } else { - *Base::Console().GetLogLevel(tag) = l; + *Base::Console().getLogLevel(tag) = l; } Py_INCREF(Py_None); return Py_None; @@ -1025,11 +1025,11 @@ PyObject* Application::sGetLogLevel(PyObject* /*self*/, PyObject* args) #endif } else { - int* pl = Base::Console().GetLogLevel(tag, false); + 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)); + return Py_BuildValue("i", Base::Console().logLevel(l)); } PY_CATCH; } diff --git a/src/App/AutoTransaction.cpp b/src/App/AutoTransaction.cpp index b70a4d5797..ccb42c111e 100644 --- a/src/App/AutoTransaction.cpp +++ b/src/App/AutoTransaction.cpp @@ -88,7 +88,7 @@ AutoTransaction::~AutoTransaction() app.closeActiveTransaction(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { } @@ -241,11 +241,11 @@ TransactionLocker::~TransactionLocker() return; } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } catch (std::exception& e) { FC_ERR(e.what()); diff --git a/src/App/Branding.cpp b/src/App/Branding.cpp index cea0497e0f..a319615b74 100644 --- a/src/App/Branding.cpp +++ b/src/App/Branding.cpp @@ -92,7 +92,7 @@ Branding::XmlConfig Branding::getUserDefines() const while (!child.isNull()) { std::string name = child.localName().toLatin1().constData(); std::string value = child.text().toUtf8().constData(); - if (std::ranges::find(filter, name) != filter.end()) { + if (filter.contains(name)) { cfg[name] = std::move(value); } child = child.nextSiblingElement(); diff --git a/src/App/ComplexGeoData.cpp b/src/App/ComplexGeoData.cpp index 02c02d1bb6..80e7e2f741 100644 --- a/src/App/ComplexGeoData.cpp +++ b/src/App/ComplexGeoData.cpp @@ -624,7 +624,7 @@ void ComplexGeoData::restoreStream(std::istream& stream, std::size_t count) } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); _restoreFailed = true; _elementMap.reset(); } diff --git a/src/App/Datums.cpp b/src/App/Datums.cpp index f4cce14b0f..cb8bbeb865 100644 --- a/src/App/Datums.cpp +++ b/src/App/Datums.cpp @@ -388,7 +388,7 @@ bool LocalCoordinateSystem::extensionGetSubObject(DocumentObject*& ret, return true; } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); return false; } } diff --git a/src/App/Document.cpp b/src/App/Document.cpp index 01d1e3c3ac..594977da1c 100644 --- a/src/App/Document.cpp +++ b/src/App/Document.cpp @@ -765,7 +765,7 @@ void Document::onChanged(const Property* prop) if (!TransDirNew.exists()) { if (TransDirOld.exists()) { if (!TransDirOld.renameFile(new_dir.c_str())) { - Base::Console().Warning("Failed to rename '%s' to '%s'\n", + Base::Console().warning("Failed to rename '%s' to '%s'\n", old_dir.c_str(), new_dir.c_str()); } @@ -775,7 +775,7 @@ void Document::onChanged(const Property* prop) } else { if (!TransDirNew.createDirectories()) { - Base::Console().Warning("Failed to create '%s'\n", new_dir.c_str()); + Base::Console().warning("Failed to create '%s'\n", new_dir.c_str()); } else { this->TransientDir.setValue(new_dir); @@ -788,7 +788,7 @@ void Document::onChanged(const Property* prop) // make sure that the uuid is unique std::string uuid = this->Uid.getValueStr(); Base::Uuid id; - Base::Console().Warning("Document with the UUID '%s' already exists, change to '%s'\n", + Base::Console().warning("Document with the UUID '%s' already exists, change to '%s'\n", uuid.c_str(), id.getValue().c_str()); // recursive call of onChanged() @@ -846,7 +846,7 @@ Document::Document(const char* documentName) d->DocumentPythonObject = Py::Object(new DocumentPy(this), true); #ifdef FC_LOGUPDATECHAIN - Console().Log("+App::Document: %p\n", this); + Console().log("+App::Document: %p\n", this); #endif std::string CreationDateString = Base::Tools::currentDateTimeString(); std::string Author = App::GetApplication() @@ -877,13 +877,8 @@ Document::Document(const char* documentName) "Additional tag to save the name of the company"); ADD_PROPERTY_TYPE(UnitSystem, (""), 0, Prop_None, "Unit system to use in this project"); // Set up the possible enum values for the unit system - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - std::vector enumValsAsVector; - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - enumValsAsVector.emplace_back(item.toStdString()); - } - UnitSystem.setEnums(enumValsAsVector); + + UnitSystem.setEnums(Base::UnitsApi::getDescriptions()); // Get the preferences/General unit system as the default for a new document ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); @@ -947,7 +942,7 @@ Document::Document(const char* documentName) Document::~Document() { #ifdef FC_LOGUPDATECHAIN - Console().Log("-App::Document: %s %p\n", getName(), this); + Console().log("-App::Document: %s %p\n", getName(), this); #endif try { @@ -957,7 +952,7 @@ Document::~Document() } #ifdef FC_LOGUPDATECHAIN - Console().Log("-Delete Features of %s \n", getName()); + Console().log("-Delete Features of %s \n", getName()); #endif d->clearDocument(); @@ -1097,7 +1092,7 @@ void Document::Restore(Base::XMLReader& reader) addObject(type.c_str(), name.c_str(), /*isNew=*/false); } catch (Base::Exception&) { - Base::Console().Message("Cannot create object '%s'\n", name.c_str()); + Base::Console().message("Cannot create object '%s'\n", name.c_str()); } } reader.readEndElement("Features"); @@ -1133,7 +1128,7 @@ void Document::Restore(Base::XMLReader& reader) void DocumentP::checkStringHasher(const Base::XMLReader& reader) { if (reader.hasReadFailed("StringHasher.Table.txt")) { - Base::Console().Error(QT_TRANSLATE_NOOP( + Base::Console().error(QT_TRANSLATE_NOOP( "Notifications", "\nIt is recommended that the user right-click the root of " "the document and select Mark to recompute.\n" @@ -1533,7 +1528,7 @@ std::vector Document::readObjects(Base::XMLReader& reader) } } catch (const Base::Exception& e) { - Base::Console().Error("Cannot create object '%s': (%s)\n", name.c_str(), e.what()); + Base::Console().error("Cannot create object '%s': (%s)\n", name.c_str(), e.what()); } } if (!testStatus(Status::Importing)) { @@ -1562,25 +1557,25 @@ std::vector Document::readObjects(Base::XMLReader& reader) // Try to continue only for certain exception types if not handled // by the feature type. For all other exception types abort the process. catch (const Base::UnicodeError& e) { - e.ReportException(); + e.reportException(); } catch (const Base::ValueError& e) { - e.ReportException(); + e.reportException(); } catch (const Base::IndexError& e) { - e.ReportException(); + e.reportException(); } catch (const Base::RuntimeError& e) { - e.ReportException(); + e.reportException(); } catch (const Base::XMLAttributeError& e) { - e.ReportException(); + e.reportException(); } pObj->setStatus(ObjectStatus::Restore, false); if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInDocumentObject)) { - Base::Console().Error("Object \"%s\" was subject to a partial restore. As a result " + Base::Console().error("Object \"%s\" was subject to a partial restore. As a result " "geometry may have changed or be incomplete.\n", name.c_str()); reader.clearPartialRestoreDocumentObject(); @@ -1866,7 +1861,7 @@ private: } if (!fi.renameFile(fn.c_str())) { - Base::Console().Warning("Cannot rename project file to backup file\n"); + Base::Console().warning("Cannot rename project file to backup file\n"); } } else { @@ -1946,13 +1941,13 @@ private: try { if (!it.deleteFile()) { backupManagementError = true; - Base::Console().Warning("Cannot remove backup file : %s\n", + Base::Console().warning("Cannot remove backup file : %s\n", it.fileName().c_str()); } } catch (...) { backupManagementError = true; - Base::Console().Warning("Cannot remove backup file : %s\n", + Base::Console().warning("Cannot remove backup file : %s\n", it.fileName().c_str()); } } @@ -2014,7 +2009,7 @@ private: } if (ext >= numberOfFiles + 10) { - Base::Console().Error( + Base::Console().error( "File not saved: Cannot rename project file to backup file\n"); // throw Base::FileException("File not saved: Cannot rename project file to // backup file", fi); @@ -2026,7 +2021,7 @@ private: fi.deleteFile(); } catch (...) { - Base::Console().Warning("Cannot remove backup file: %s\n", + Base::Console().warning("Cannot remove backup file: %s\n", fi.fileName().c_str()); backupManagementError = true; } @@ -2325,7 +2320,7 @@ void Document::restore(const char* filename, Document::Restore(reader); } catch (const Base::Exception& e) { - Base::Console().Error("Invalid Document.xml: %s\n", e.what()); + Base::Console().error("Invalid Document.xml: %s\n", e.what()); setStatus(Document::RestoreError, true); } @@ -2343,7 +2338,7 @@ void Document::restore(const char* filename, if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestore)) { setStatus(Document::PartialRestore, true); - Base::Console().Error("There were errors while loading the file. Some data might have been " + Base::Console().error("There were errors while loading the file. Some data might have been " "modified or not recovered at all. Look above for more specific " "information about the objects involved.\n"); } @@ -2465,7 +2460,7 @@ bool Document::afterRestore(const std::vector& objArray, bool c // partial document touched, signal full reload return false; } - else if (!d->touchedObjs.count(obj)) { + else if (!d->touchedObjs.contains(obj)) { obj->purgeTouched(); } @@ -3065,7 +3060,7 @@ int Document::recompute(const std::vector& objs, for (size_t i = 0; i < topoSortedObjects.size(); ++i) { auto obj = topoSortedObjects[i]; obj->setStatus(ObjectStatus::Recompute2, false); - if (!filter.count(obj) && obj->isTouched()) { + if (!filter.contains(obj) && obj->isTouched()) { if (passes > 0) { FC_ERR(obj->getFullName() << " still touched after recompute"); } @@ -3082,7 +3077,7 @@ int Document::recompute(const std::vector& objs, } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } FC_TIME_LOG(t2, "Recompute"); @@ -3105,7 +3100,7 @@ int Document::recompute(const std::vector& objs, if (it->isError()) { const char* text = getErrorDescription(it); if (text) { - Base::Console().Error("%s: %s\n", it->Label.getValue(), text); + Base::Console().error("%s: %s\n", it->Label.getValue(), text); } } } @@ -3122,7 +3117,7 @@ int Document::recompute(const std::vector& objs, } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("error when removing object " << o.getDocumentName() << '#' << o.getObjectName()); } @@ -3331,7 +3326,7 @@ int Document::_recomputeFeature(DocumentObject* Feat) } } catch (Base::AbortException& e) { - e.ReportException(); + e.reportException(); FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what()); d->addRecomputeLog("User abort", Feat); return -1; @@ -3342,7 +3337,7 @@ int Document::_recomputeFeature(DocumentObject* Feat) return 1; } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_LOG("Failed to recompute " << Feat->getFullName() << ": " << e.what()); d->addRecomputeLog(e.what(), Feat); return 1; diff --git a/src/App/DocumentObject.cpp b/src/App/DocumentObject.cpp index cfa8fe077f..daa1e4fe6c 100644 --- a/src/App/DocumentObject.cpp +++ b/src/App/DocumentObject.cpp @@ -140,7 +140,7 @@ void DocumentObject::printInvalidLinks() const scopenames.pop_back(); } - Base::Console().Warning("%s: Link(s) to object(s) '%s' go out of the allowed scope '%s'. " + Base::Console().warning("%s: Link(s) to object(s) '%s' go out of the allowed scope '%s'. " "Instead, the linked object(s) reside within '%s'.\n", getTypeId().getName(), objnames.c_str(), @@ -148,7 +148,7 @@ void DocumentObject::printInvalidLinks() const scopenames.c_str()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -581,7 +581,7 @@ bool _isInInListRecursive(const DocumentObject* act, const DocumentObject* check bool DocumentObject::isInInListRecursive(DocumentObject* linkTo) const { - return this == linkTo || getInListEx(true).count(linkTo); + return this == linkTo || getInListEx(true).contains(linkTo); } bool DocumentObject::isInInList(DocumentObject* linkTo) const @@ -644,7 +644,7 @@ bool DocumentObject::testIfLinkDAGCompatible(const std::vector& auto inLists = getInListEx(true); inLists.emplace(const_cast(this)); for (auto obj : linksTo) { - if (inLists.count(obj)) { + if (inLists.contains(obj)) { return false; } } @@ -1215,6 +1215,20 @@ void DocumentObject::onDocumentRestored() } } +void DocumentObject::restoreFinished() +{ + // some link type property cannot restore link information until other + // objects has been restored. For example, PropertyExpressionEngine and + // PropertySheet with expression containing label reference. + // So on document load they are handled in Document::afterRestore, but if the user + // use dumpContent and restoreContent then they need to be handled here. + std::vector props; + getPropertyList(props); + for (auto prop : props) { + prop->afterRestore(); + } +} + void DocumentObject::onUndoRedoFinished() {} diff --git a/src/App/DocumentObject.h b/src/App/DocumentObject.h index bd62977774..6eefea054a 100644 --- a/src/App/DocumentObject.h +++ b/src/App/DocumentObject.h @@ -752,6 +752,8 @@ protected: void onEarlyChange(const Property* prop) override; /// get called after a document has been fully restored virtual void onDocumentRestored(); + /// get called after an object finishes restoreContent. + void restoreFinished() override; /// get called after an undo/redo transaction is finished virtual void onUndoRedoFinished(); /// get called after setting the document diff --git a/src/App/DocumentObserverPython.cpp b/src/App/DocumentObserverPython.cpp index f36515dd8a..22a61ecdb1 100644 --- a/src/App/DocumentObserverPython.cpp +++ b/src/App/DocumentObserverPython.cpp @@ -133,7 +133,7 @@ void DocumentObserverPython::slotCreatedDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -147,7 +147,7 @@ void DocumentObserverPython::slotDeletedDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -161,7 +161,7 @@ void DocumentObserverPython::slotRelabelDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -175,7 +175,7 @@ void DocumentObserverPython::slotActivateDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -189,7 +189,7 @@ void DocumentObserverPython::slotUndoDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -204,7 +204,7 @@ void DocumentObserverPython::slotRedoDocument(const App::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -216,7 +216,7 @@ void DocumentObserverPython::slotUndo() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -228,7 +228,7 @@ void DocumentObserverPython::slotRedo() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -242,7 +242,7 @@ void DocumentObserverPython::slotBeforeCloseTransaction(bool abort) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -256,7 +256,7 @@ void DocumentObserverPython::slotCloseTransaction(bool abort) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -277,7 +277,7 @@ void DocumentObserverPython::slotBeforeChangeDocument(const App::Document& Doc, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -298,7 +298,7 @@ void DocumentObserverPython::slotChangedDocument(const App::Document& Doc, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -312,7 +312,7 @@ void DocumentObserverPython::slotCreatedObject(const App::DocumentObject& Obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -326,7 +326,7 @@ void DocumentObserverPython::slotDeletedObject(const App::DocumentObject& Obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -347,7 +347,7 @@ void DocumentObserverPython::slotBeforeChangeObject(const App::DocumentObject& O } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -368,7 +368,7 @@ void DocumentObserverPython::slotChangedObject(const App::DocumentObject& Obj, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -382,7 +382,7 @@ void DocumentObserverPython::slotRecomputedObject(const App::DocumentObject& Obj } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -396,7 +396,7 @@ void DocumentObserverPython::slotRecomputedDocument(const App::Document& doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -410,7 +410,7 @@ void DocumentObserverPython::slotBeforeRecomputeDocument(const App::Document& do } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -425,7 +425,7 @@ void DocumentObserverPython::slotOpenTransaction(const App::Document& doc, std:: } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -439,7 +439,7 @@ void DocumentObserverPython::slotCommitTransaction(const App::Document& doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -453,7 +453,7 @@ void DocumentObserverPython::slotAbortTransaction(const App::Document& doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -474,7 +474,7 @@ void DocumentObserverPython::slotAppendDynamicProperty(const App::Property& Prop } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -495,7 +495,7 @@ void DocumentObserverPython::slotRemoveDynamicProperty(const App::Property& Prop } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -517,7 +517,7 @@ void DocumentObserverPython::slotChangePropertyEditor(const App::Document&, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -533,7 +533,7 @@ void DocumentObserverPython::slotStartSaveDocument(const App::Document& doc, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -549,7 +549,7 @@ void DocumentObserverPython::slotFinishSaveDocument(const App::Document& doc, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -566,7 +566,7 @@ void DocumentObserverPython::slotBeforeAddingDynamicExtension( } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -582,6 +582,6 @@ void DocumentObserverPython::slotAddedDynamicExtension(const App::ExtensionConta } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/App/DocumentPyImp.cpp b/src/App/DocumentPyImp.cpp index 37c9829f8b..22df71f1f5 100644 --- a/src/App/DocumentPyImp.cpp +++ b/src/App/DocumentPyImp.cpp @@ -381,7 +381,7 @@ PyObject* DocumentPy::addObject(PyObject* args, PyObject* kwd) } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } } diff --git a/src/App/DynamicProperty.cpp b/src/App/DynamicProperty.cpp index 07921e87f4..461bfee3f4 100644 --- a/src/App/DynamicProperty.cpp +++ b/src/App/DynamicProperty.cpp @@ -256,9 +256,15 @@ bool DynamicProperty::addProperty(Property* prop) return false; } auto& index = props.get<0>(); +#if BOOST_VERSION < 107500 if (index.count(prop->getName())) { return false; } +#else + if (index.contains(prop->getName())) { + return false; + } +#endif index.emplace(prop, std::string(), prop->getName(), diff --git a/src/App/Expression.cpp b/src/App/Expression.cpp index 90ae19d2b0..6e9db2bc83 100644 --- a/src/App/Expression.cpp +++ b/src/App/Expression.cpp @@ -619,7 +619,7 @@ bool isAnyEqual(const App::any &v1, const App::any &v2) { return false; int res = PyObject_RichCompareBool(o1.ptr(),o2.ptr(),Py_EQ); if(res<0) - PyException::ThrowException(); + PyException::throwException(); return !!res; } @@ -997,7 +997,7 @@ ExpressionPtr Expression::importSubNames(const std::map if(it!=nameMap.end()) subNameMap.emplace(std::make_pair(obj,std::string()),it->second); auto key = std::make_pair(obj,path.getSubObjectName()); - if(key.second.empty() || subNameMap.count(key)) + if(key.second.empty() || subNameMap.contains(key)) continue; std::string imported = PropertyLinkBase::tryImportSubName( obj,key.second.c_str(),owner->getDocument(), nameMap); diff --git a/src/App/Extension.h b/src/App/Extension.h index 80fadace14..e47be2aa37 100644 --- a/src/App/Extension.h +++ b/src/App/Extension.h @@ -126,70 +126,88 @@ template<> void _class_::init(void){\ // clang-format on /** - * @brief Base class for all extension that can be added to a DocumentObject + * @brief A base class for extensions for a DocumentObject. * - * For general documentation on why extension system exists and how to use it see the ExtensionContainer - * documentation. Following is a description howto create custom extensions. + * For general documentation on why extension system exists and how to use it, + * see the ExtensionContainer documentation. Below is a description on how to + * create custom extensions. + * + * An Extension is like every other FreeCAD object and is based on properties. + * All information storage and persistence should be achieved by use of these + * properties. Additionally, any number of methods can be added to provide + * functionality related to the properties. There are three small differences + * to normal objects: + * + * 1. They must be derived from this Extension class, + * 2. Properties must be handled with special extension macros. + * 3. Extensions must be initialised. + * + * The following code illustrates the basic setup of an extension: * - * Extensions are like every other FreeCAD object and based on properties. All information storage - * and persistence should be achieved by use of those. Additional any number of methods can be - * added to provide functionality around the properties. There are 3 small difference to normal objects: - * 1. They must be derived from Extension class - * 2. Properties must be handled with special extension macros - * 3. Extensions must be initialised - * This works as simple as * @code - * class MyExtension : public Extension { + * class MyExtension : public Extension + * { * EXTENSION_PROPERTY_HEADER(MyExtension); * PropertyInt MyProp; * virtual bool overridableMethod(DocumentObject* obj) {}; * }; * * EXTENSION_PROPERTY_SOURCE(App::MyExtension, App::Extension) - * MyExtension::MyExtension() { - * - * EXTENSION_ADD_PROPERTY(MyProp, (0)) * - * initExtension(MyExtension::getExtensionClassTypeId()); + * MyExtension::MyExtension() + * { + * EXTENSION_ADD_PROPERTY(MyProp, (0)) + * initExtensionType(MyExtension::getExtensionClassTypeId()); * } + * * using MyExtensionPython = ExtensionPythonT; * @endcode * - * The special python extension type created above is important, as only those python extensions - * can be added to an object from python. It does not work to add the c++ version directly there. + * The special Python extension type created above is important, as only those Python extensions + * can be added to an object from Python. It does not work to add the C++ version directly there. * - * Note that every method of the extension becomes part of the extended object when added from c++. + * Note that every method of the extension becomes part of the extended object when added from C++. * This means one should carefully design the API and make only necessary methods public or protected. * Every internal method should be private. * - * The automatic availability of methods in the class does not hold for the python interface, only - * for c++ classes. This is like every where else in FreeCAD, there is no automatic creation of python - * API from c++ classes. Hence the extension creator must also create a custom python object of its - * extension, which works exactly like the normal FreeCAD python object workflow. There is nothing - * special at all for extension python objects, the normal xml + imp.cpp approach is used. It must - * only be taken care that the objects father is the correct extension base class. Of course also - * make sure your extension returns the correct python object in its "getPyObject" call. - * Every method you create in the extensions python will be later added to an extended object. This - * happens automatically for both, c++ and python extension, if "getPyObject" returns the correct - * python object. No extra work needs to be done. + * The automatic availability of methods in the class does not hold for the + * Python interface, only for C++ classes. This is common in the rest of + * FreeCAD as well: there is no automatic creation of Python API from C++ + * classes. * - * A special case that needs to be handled for extensions is the possibility of overridden methods. - * Often it is desired to customise extension behaviour by allowing the user to override methods - * provided by the extension. On c++ side this is trivial, such methods are simply marked as "virtual" - * and can than be overridden in any derived class. This is more involved for the python interface and - * here special care needs to be taken. + * Hence, the extension creator must also create a custom Python object of its + * extension, which is the same for the normal FreeCAD Python object workflow. + * There is nothing special at all for Python extension objects: the normal + * `.pyi` and `PyImp.cpp` approach is used but note that it is important that + * the object's father is the correct extension base class. Additionally, make + * sure the extension returns the correct Python object in its + * getExtensionPyObject() call. + * + * Every method that is created in the extension's Python counterpart will be + * later added to the extended object. This happens automatically for both the + * C++ and Python extension if getExtensionPyObject() returns the correct + * Python object. This does not require extra work. + * + * A special case that needs to be handled for extensions is the possibility of + * overridden methods. Often, it is desired to customise extension behaviour + * by allowing the user to override methods provided by the extension. On the + * C++ side, this is trivial: such methods are simply marked as "virtual" and + * can then be overridden in any derived class. This is more involved for the + * Python interface and here special care needs to be taken. + * + * As already shown above, one needs to create a special `ExtensionPythonT<>` + * object for extension from Python. This is done exactly for the purpose of + * allowing to have overridable methods. The ExtensionPythonT wrapper adds a + * proxy property that holds a PyObject which itself will contain the + * implementations for the overridden methods. This design is equal to the + * ObjectPythonT<> design of normal document objects. As this wrapper inherits + * the C++ extension class it, can also override the virtual functions the user + * designed to be overridden. What it should do at a call of the virtual + * method is to check if this method is implemented in the proxy object and if + * so, call it, and if not, call the normal C++ version. It is the extension + * creator's responsibility to implement this check and call behaviour for + * every overridable method. This is done by creating a custom wrapper just + * like ExtensionPythonT<> and overriding all virtual methods. * - * As already seen above one needs to create a special ExtensionPythonT<> object for extension from - * python. This is done exactly for the purpose of allowing to have overridable methods. The - * ExtensionPythonT wrapper adds a proxy property which holds a PyObject which itself will contain - * the implementations for the overridden methods. This design is equal to the ObjectPythonT<> design - * of normal document objects. - * As this wrapper inherits the c++ extension class it can also override the virtual functions the - * user designed to be overridden. What it should do at a call of the virtual method is to check if - * this method is implemented in the proxy object and if so call it, and if not call the normal - * c++ version. It is the extensions creators responsibility to implement this check and call behaviour - * for every overridable method. - * This is done by creating a custom wrapper just like ExtensionPythonT<> and overriding all virtual - * methods. * @code * template class MyExtensionPythonT : public ExtensionT { * public: @@ -211,18 +229,21 @@ template<> void _class_::init(void){\ * }; * }; * @endcode - * @Note As seen in the code there are multiple helper macros to ease the repetitive work of querying - * and calling methods of the proxy object. See the macro documentation for how to use them. * - * To ensure that your wrapper is used when a extension is created from python the extension type must - * be exposed as follows: + * @note As seen in the code there are multiple helper macros to ease the + * repetitive work of querying and calling methods of the proxy object. See the + * macro documentation for how to use them. + * + * To ensure that your wrapper is used when a extension is created from Python + * the extension type must be exposed as follows: + * * @code * using MyExtensionPython = ExtensionPythonT>; * @endcode * - * This boilerplate is absolutely necessary to allow overridable methods in python and it is the - * extension creator's responsibility to ensure full implementation. - * + * This boilerplate is absolutely necessary to allow overridable methods in + * Python and it is the extension creator's responsibility to ensure full + * implementation. */ class AppExport Extension { @@ -232,76 +253,199 @@ class AppExport Extension EXTENSION_PROPERTY_HEADER(App::Extension); public: - + /// Construct an extension object. Extension() = default; + /// Destruct an extension object. virtual ~Extension(); + /** + * @brief Initialize the extension. + * + * This function is called by the ExtensionContainer to initialize the + * extension. + * + * @param[in,out] obj The ExtensionContainer object to which this extension + * is attached. + * + * @throw Base::RuntimeError If the extension type is not set. + */ virtual void initExtension(App::ExtensionContainer* obj); + /** + * @brief Get the container of the extension. + * + * @return The ExtensionContainer object to which this extension belongs. + */ App::ExtensionContainer* getExtendedContainer() {return m_base;} + + /** + * @brief Get the container of the extension. + * + * @return The ExtensionContainer object to which this extension belongs. + */ const App::ExtensionContainer* getExtendedContainer() const {return m_base;} - //get extension name without namespace + /** + * @brief Get the name of the extension. + * + * The name is the class name of the extension without the namespace. + * + * @return The name of the extension. + */ std::string name() const; + /** + * @brief Whether the extension is a Python extension. + * + * @return True if the extension is a Python extension, false otherwise. + */ bool isPythonExtension() {return m_isPythonExtension;} + /** + * @brief Get the PyObject of the extension. + * + * @return The PyObject of the extension. + */ virtual PyObject* getExtensionPyObject(); - /** @name Access properties */ - //@{ - /// find a property by its name + /** @name Access properties + * + * @{ + */ + + /** + * @copydoc PropertyContainer::getPropertyByName() + */ virtual Property *extensionGetPropertyByName(const char* name) const; - /// get the name of a property + + /** + * @copydoc PropertyContainer::getPropertyName() + */ virtual const char* extensionGetPropertyName(const Property* prop) const; - /// get all properties of the class (including properties of the parent) - virtual void extensionGetPropertyMap(std::map &Map) const; - /// See PropertyContainer::visitProperties for semantics + + /** + * @copydoc PropertyContainer::getPropertyMap() + */ + virtual void extensionGetPropertyMap(std::map &map) const; + + /** + * @copydoc PropertyContainer::visitProperties() + */ virtual void extensionVisitProperties(const std::function& visitor) const; - /// get all properties of the class (including properties of the parent) + + /** + * @copydoc PropertyContainer::getPropertyList() + */ virtual void extensionGetPropertyList(std::vector &List) const; - /// get the Type of a Property + /** + * @copydoc PropertyContainer::getPropertyType(const Property*) const + */ virtual short extensionGetPropertyType(const Property* prop) const; - /// get the Type of a named Property + + /** + * @copydoc PropertyContainer::getPropertyType(const char*) const + */ virtual short extensionGetPropertyType(const char *name) const; - /// get the Group of a Property + + /** + * @copydoc PropertyContainer::getPropertyGroup(const Property*) const + */ virtual const char* extensionGetPropertyGroup(const Property* prop) const; - /// get the Group of a named Property + + /** + * @copydoc PropertyContainer::getPropertyGroup(const char*) const + */ virtual const char* extensionGetPropertyGroup(const char *name) const; - /// get the Group of a Property + + /** + * @copydoc PropertyContainer::getPropertyDocumentation(const Property*) const + */ virtual const char* extensionGetPropertyDocumentation(const Property* prop) const; - /// get the Group of a named Property + + /** + * @copydoc PropertyContainer::getPropertyDocumentation(const char*) const + */ virtual const char* extensionGetPropertyDocumentation(const char *name) const; - //@} + /// @} - /** @name Persistence */ - //@{ + /** @name Persistence + * @{ + */ + + /** + * @copydoc Base::Persistence::Save + */ virtual void extensionSave(Base::Writer&) const {} - virtual void extensionRestore(Base::XMLReader&) {} - //@} - /** @name TypeHandling */ - //@{ + /** + * @copydoc Base::Persistence::Restore + */ + virtual void extensionRestore(Base::XMLReader&) {} + /// @} + + /** + * @copydoc Base::Type::isDerivedFrom() + */ bool extensionIsDerivedFrom(const Base::Type type) const {return getExtensionTypeId().isDerivedFrom(type);} + protected: + /** + * @brief Helper function to register the parent. + * + * This is used in the macros. It creates a new type in @p toInit based on + * the parent. @p toInit should be an uninitialized type. + * + * @param[out] toInit The type to initialize. + * @param[in] ClassName The name of the class. + * @param[in] ParentName The name of the parent class. + * @param[in] method The instantiation method. + */ static void initExtensionSubclass(Base::Type &toInit,const char* ClassName, const char *ParentName, Base::Type::instantiationMethod method=nullptr); - //@} - virtual void extensionOnChanged(const Property* p) {(void)(p);} + /** + * @copydoc PropertyContainer::onChanged() + */ + virtual void extensionOnChanged([[maybe_unused]] const Property* prop) {} - /// returns true if the property name change was handled by the extension. - virtual bool extensionHandleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName); - /// returns true if the property type change was handled by the extension. - virtual bool extensionHandleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, Property * prop); + /** + * @copydoc PropertyContainer::handleChangedPropertyName() + * + * @return True if the property name change was handled by the extension, + * false otherwise. + */ + virtual bool extensionHandleChangedPropertyName(Base::XMLReader &reader, const char * typeName, const char *propName); + /** + * @copydoc PropertyContainer::handleChangedPropertyType() + * + * @return True if the property type change was handled by the extension, + * false otherwise. + */ + virtual bool extensionHandleChangedPropertyType(Base::XMLReader &reader, const char * typeName, Property * prop); + + /// Provide access to the ExtensionContainer. friend class App::ExtensionContainer; protected: + /** + * @brief Initialize the extension type. + * + * This function is to be called by the constructor to initialize the + * extension type. + * + * @param[in] type The type of the extension. + * + * @throw Base::RuntimeError If the extension type is not set. + */ void initExtensionType(Base::Type type); + + /// Whether the extension is a Python extension. bool m_isPythonExtension = false; + + /// The Python object of the extension. Py::SmartPtr ExtensionPythonObject; private: diff --git a/src/App/ExtensionContainer.cpp b/src/App/ExtensionContainer.cpp index 9a002e576b..c41c2b3167 100644 --- a/src/App/ExtensionContainer.cpp +++ b/src/App/ExtensionContainer.cpp @@ -74,15 +74,15 @@ void ExtensionContainer::registerExtension(Base::Type extension, Extension* ext) _extensions[extension] = ext; } -bool ExtensionContainer::hasExtension(Base::Type t, bool derived) const +bool ExtensionContainer::hasExtension(Base::Type type, bool derived) const { // check for the exact type - bool found = _extensions.find(t) != _extensions.end(); + bool found = _extensions.find(type) != _extensions.end(); if (!found && derived) { // and for types derived from it, as they can be cast to the extension for (const auto& entry : _extensions) { - if (entry.first.isDerivedFrom(t)) { + if (entry.first.isDerivedFrom(type)) { return true; } } @@ -397,17 +397,17 @@ void ExtensionContainer::saveExtensions(Base::Writer& writer) const ext->extensionSave(writer); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const std::exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const char* e) { - Base::Console().Error("%s\n", e); + Base::Console().error("%s\n", e); } #ifndef FC_DEBUG catch (...) { - Base::Console().Error( + Base::Console().error( "ExtensionContainer::Save: Unknown C++ exception thrown. Try to continue...\n"); } #endif @@ -469,17 +469,17 @@ void ExtensionContainer::restoreExtensions(Base::XMLReader& reader) throw; // re-throw } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const std::exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const char* e) { - Base::Console().Error("%s\n", e); + Base::Console().error("%s\n", e); } #ifndef FC_DEBUG catch (...) { - Base::Console().Error("ExtensionContainer::Restore: Unknown C++ exception thrown\n"); + Base::Console().error("ExtensionContainer::Restore: Unknown C++ exception thrown\n"); } #endif diff --git a/src/App/ExtensionContainer.h b/src/App/ExtensionContainer.h index 646ef77ab6..c3f56699bd 100644 --- a/src/App/ExtensionContainer.h +++ b/src/App/ExtensionContainer.h @@ -35,33 +35,41 @@ namespace App { class Extension; + /** - * @brief Container which can hold extensions + * @brief A container that can hold extensions. * - * In FreeCAD normally inheritance is a chain, it is not possible to use multiple inheritance. - * The reason for this is that all objects need to be exposed to python, and it is basically - * impossible to handle multiple inheritance in the C-API for python extensions. Also using multiple - * parent classes in python is currently not possible with the default object approach. + * The concept of extensions provides a way to extend the functionality of + * objects in FreeCAD despite Python's limitations with multiple inheritance + * (see below for an explanation). Extensions are FreeCAD objects that act + * like regular objects in the sense that they have properties and class + * methods to define their functionality. However, extensions are not exposed + * as individual usable entities but are used to extend other objects. An + * extended object obtains all the properties and methods of the extension. * - * The concept of extensions allows one to circumvent those problems. Extensions are FreeCAD objects - * which work like normal objects in the sense that they use properties and class methods to define - * their functionality. However, they are not exposed as individual usable entities but are used to - * extend other objects. A extended object gets all the properties and methods of the extension. - * Therefore it is like c++ multiple inheritance, which is indeed used to achieve this on c++ side, - * but provides a few important additional functionalities: - * - Property persistence is handled, save and restore work out of the box - * - The objects python API gets extended too with the extension python API - * - Extensions can be added from c++ and python, even from both together + * As such, it is like C++ multiple inheritance, which is indeed used to + * achieve this on C++ side, but it provides a few important additional + * functionalities as well: + * + * - Property persistence is handled: save and restore work out of the box. + * - The objects Python API gets extended too with the extension Python API. + * - Extensions can be added from C++ and Python, even from both together. + * + * The interoperability with Python is highly important since in FreeCAD, all + * functionality should be easily accessible from both Python and C++. To + * ensure this -- as already noted -- extensions can be added to an object from + * Python. + * + * However, this means that it is not clear from the C++ object type whether an + * extension was added or not: If added from C++, it becomes clear in the type + * due to the use of multiple inheritance. If added from Python, it is a + * runtime extension and not visible from the type. Hence, querying existing + * extensions of an object and accessing its methods works not by type casting + * but by the interface provided in ExtensionContainer. The default workflow + * is to query whether an extension exists and then to get the extension + * object. This interface always works the same, no matter if added from + * Python or C++. * - * The interoperability with python is highly important, as in FreeCAD all functionality should be - * as easily accessible from python as from c++. To ensure this, and as already noted, extensions - * can be added to a object from python. However, this means that it is not clear from the c++ - * object type if an extension was added or not. If added from c++ it becomes clear in the type due - * to the use of multiple inheritance. If added from python it is a runtime extension and not - * visible from type. Hence querying existing extensions of an object and accessing its methods - * works not by type casting but by the interface provided in ExtensionContainer. The default - * workflow is to query if an extension exists and then get the extension object. No matter if added - * from python or c++ this interface works always the same. * @code * if (object->hasExtension(GroupExtension::getClassTypeId())) { * App::GroupExtension* group = object->getExtensionByType(); @@ -69,33 +77,43 @@ class Extension; * } * @endcode * - * To add a extension to an object, it must comply to a single restriction: it must be derived - * from ExtensionContainer. This is important to allow adding extensions from python and also to - * access the universal extension API. As DocumentObject itself derives from ExtensionContainer this - * should be the case automatically in most circumstances. + * To add a extension to an object, it must comply to a single restriction: it + * must be derived from ExtensionContainer. This is important to allow adding + * extensions from Python and also to access the universal extension API. As + * DocumentObject itself derives from ExtensionContainer, this should be the + * case automatically in most circumstances. + * + * Note that two small boilerplate changes are needed in addition to the + * multiple inheritance when adding extensions from C++. * - * Note that two small boilerplate changes are needed next to the multiple inheritance when adding - * extensions from c++. * 1. It must be ensured that the property and type registration is aware of the extensions by using * special macros. - * 2. The extensions need to be initialised in the constructor + * 2. The extensions need to be initialised in the constructor. * * Here is a working example: - * @code - * class AppExport Part : public App::DocumentObject, public App::FirstExtension, public - * App::SecondExtension { PROPERTY_HEADER_WITH_EXTENSIONS(App::Part); + * @code{.cpp} + * class AppExport Part : public App::DocumentObject + * , public App::FirstExtension + * , public App::SecondExtension + * { + * PROPERTY_HEADER_WITH_EXTENSIONS(App::Part); * }; + * * PROPERTY_SOURCE_WITH_EXTENSIONS(App::Part, App::DocumentObject) - * Part::Part(void) { + * + * Part::Part(void) + * { * FirstExtension::initExtension(this); * SecondExtension::initExtension(this); * } * @endcode * - * From python adding an extension is easier, it must be simply registered to a document object - * at object initialisation like done with properties. Note that the special python extension - * objects need to be added, not the c++ objects. Normally the only difference in name is the - * additional "Python" at the end of the extension name. + * From Python, adding an extension is easier: It must be simply registered to + * a document object at object initialisation like done with properties. Note + * that the special Python extension objects need to be added, not the C++ + * objects. Normally the only difference in name is the additional "Python" at + * the end of the extension name. + * * @code{.py} * class Test(): * __init(self)__: @@ -103,15 +121,28 @@ class Extension; * registerExtension("App::SecondExtensionPython", self) * @endcode * - * Extensions can provide methods that should be overridden by the extended object for customisation - * of the extension behaviour. In c++ this is as simple as overriding the provided virtual - * functions. In python a class method must be provided which has the same name as the method to - * override. This method must not necessarily be in the object that is extended, it must be in the - * object which is provided to the "registerExtension" call as second argument. This second argument - * is used as a proxy and enqueired if the method to override exists in this proxy before calling - * it. + * Extensions can provide methods that should be overridden by the extended + * object for customisation of the extension behaviour. In C++ this is as + * simple as overriding the provided virtual functions. In Python a class + * method must be provided which has the same name as the method to override. + * This method must not necessarily be in the object that is extended, it must + * be in the object which is provided to the "registerExtension" call as second + * argument. This second argument is used as a proxy and queried if the method + * to override exists in this proxy before calling it. * - * For information on howto create extension see the documentation of Extension + * For information on how to create extension see the documentation of + * Extension. + * + * @section Limitations of Python + * + * Without this extension system, it would be challenging to use extending + * functionality in FreeCAD. Although C++ supports multiple inheritance, it is + * not possible to use it in FreeCAD because it should be possible to expose + * all objects to Python. + * + * However, using multiple parent classes in Python is currently not possible + * with the default object approach. Moreover, it is basically impossible to + * handle multiple inheritance in the C-API for Python extensions. */ class AppExport ExtensionContainer: public App::PropertyContainer { @@ -119,21 +150,96 @@ class AppExport ExtensionContainer: public App::PropertyContainer TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: + /// A type alias for iterating extensions. using ExtensionIterator = std::map::iterator; + /// Construct an extension container. ExtensionContainer(); + /// Destruct an extension container. ~ExtensionContainer() override; + /** + * @brief Register an extension. + * + * @param[in] extension The type of the extension to register. + * @param[in] ext The extension to register. + */ void registerExtension(Base::Type extension, App::Extension* ext); - // returns first of type (or derived from if set to true) and throws otherwise - bool hasExtension(Base::Type, bool derived = true) const; - // this version does not check derived classes + + /** + * @brief Whether this container has an extension of the given type. + * + * This version checks for derived types. It returns the first extension + * of the given type or the first extension that is derived from the type + * if @p derived is true. + * + * @param[in] type The type of the extension to check for. + * @param[in] derived (Optionally) Whether to check for derived types, true by default. + * + * @return True if the container has the (derived) extension, false otherwise. + */ + bool hasExtension(Base::Type type, bool derived = true) const; + + /** + * @brief Whether this container has an extension of the given type. + * + * This version checks for derived types. It returns the first extension + * of the given type. Note that this function does not check for derived + * types. + * + * @param[in] name The name of the extension to check for. + * @return True if the container has the extension, false otherwise. + */ bool hasExtension(const std::string& name) const; + + /** + * @brief Whether this container has extensions. + * + * @return True if the container has extensions, false otherwise. + */ bool hasExtensions() const; - App::Extension* getExtension(Base::Type, bool derived = true, bool no_except = false) const; - // this version does not check derived classes + + /** + * @brief Get the extension of the given type. + * + * This version checks for derived types. It returns the first extension + * of the given type or the first extension that is derived from the type + * if @p derived is true. If @p no_except is true, it returns nullptr, + *otherwise it throws an exception if no extension of the given type is + * found. + * + * @param[in] type The type of the extension to get. + * @param[in] derived (Optionally) Whether to check for derived types, true by default. + * @param[in] no_except (Optionally) Whether to throw an exception if no extension is found, + * false by default. + * + * @return The extension of the given type or `nullptr` if not found. + * @throws Base::TypeError if no extension of the given type is found and + * @p no_except is false. + */ + App::Extension* getExtension(Base::Type type, bool derived = true, bool no_except = false) const; + + /** + * @brief Get the extension with the given name. + * + * This version does not check for derived types. + * + * @param[in] name The name of the extension to get. + * + * @return The extension with the given name or `nullptr` if not found. + */ App::Extension* getExtension(const std::string& name) const; - // this version checks for derived types and doesn't throw + + /** + * @brief Get the extension of the given type. + * + * This version checks for derived types. It returns the first extension + * of the given type or the first extension that is derived from the type. + * It doesn't throw an exception but returns `nullptr` if not found. + * + * @tparam ExtensionT The type of the extension to get. + * @return The extension of the given type or `nullptr` if not found. + */ template ExtensionT* getExtension() const { @@ -141,7 +247,24 @@ public: getExtension(ExtensionT::getExtensionClassTypeId(), true, true)); } - // returns first of type (or derived from) and throws otherwise + /** + * @brief Get the extension with the given type. + * + * This version checks for derived types if @p derived is true. It returns the first + * extension of the given type or the first extension that is derived from the type + * if @p derived is true. If not found, it returns `nullptr` if @p no_except is true, + * otherwise it throws an exception. + * + * @tparam ExtensionT The type of the extension to get. + * + * @param[in] no_except (Optionally) Whether to throw an exception if no extension is found, + * false by default. + * @param[in] derived (Optionally) Whether to check for derived types, true by default. + * + * @return The extension of the given type or `nullptr` if not found if @p no_except is true. + * @throws Base::TypeError if no extension of the given type is found and + * @p no_except is false. + */ template ExtensionT* getExtensionByType(bool no_except = false, bool derived = true) const { @@ -149,8 +272,20 @@ public: getExtension(ExtensionT::getExtensionClassTypeId(), derived, no_except)); } - // get all extensions which have the given base class + /** + * @brief Get all extensions with the given type as base class. + * + * @param[in] type The type of the extension to get. + * @return A vector of extensions of the given type. + */ std::vector getExtensionsDerivedFrom(Base::Type type) const; + + /** + * @brief Get all extensions with the given type as base class. + * + * @tparam ExtensionT The type of the extension to get. + * @return A vector of extensions of the given type. + */ template std::vector getExtensionsDerivedFromType() const { @@ -163,78 +298,138 @@ public: return typevec; } + /** + * @brief Get the begin iterator for the extensions. + * + * @return The begin iterator for the extensions. + */ ExtensionIterator extensionBegin() { return _extensions.begin(); } + + /** + * @brief Get the end iterator for the extensions. + * + * @return The end iterator for the extensions. + */ ExtensionIterator extensionEnd() { return _extensions.end(); } - /** @name Access properties */ - //@{ - /// find a property by its name + /** @name Access properties + * + * @{ + */ + Property* getPropertyByName(const char* name) const override; - /// find a property by its name, dynamic cased to specified type + + /** + * @brief Find a property by its name and cast it to the specified type. + * + * This method finds a property by its name and casts it to the specified + * type with a `freecad_cast`. + * + * @tparam T The property type to which the property is cast. + * @param[in] name The name of the property to find. + * @return The property if found cast to the specified type, or `nullptr` if not found. + */ template T* getPropertyByName(const char* name) const { return freecad_cast(this->getPropertyByName(name)); } - /// get the name of a property + const char* getPropertyName(const Property* prop) const override; - /// get all properties of the class (including properties of the parent) + void getPropertyMap(std::map& Map) const override; - /// See PropertyContainer::visitProperties for semantics + void visitProperties(const std::function& visitor) const override; - /// get all properties of the class (including properties of the parent) + void getPropertyList(std::vector& List) const override; - /// get the Type of a Property short getPropertyType(const Property* prop) const override; - /// get the Type of a named Property + short getPropertyType(const char* name) const override; - /// get the Group of a Property + const char* getPropertyGroup(const Property* prop) const override; - /// get the Group of a named Property + const char* getPropertyGroup(const char* name) const override; - /// get the Group of a Property + const char* getPropertyDocumentation(const Property* prop) const override; - /// get the Group of a named Property + const char* getPropertyDocumentation(const char* name) const override; - //@} + ///@} void onChanged(const Property*) override; void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; // those methods save/restore the dynamic extensions without handling properties, which is // something done by the default Save/Restore methods. + /** + * @brief Save the extensions to the given writer. + * + * This method saves the dynamic extensions to the given writer without + * handling properties, which is something done by the default Save/Restore + * methods. + * + * @param[in,out] writer The writer to save the extensions to. + */ void saveExtensions(Base::Writer& writer) const; + + /** + * @brief Restore the extensions from the given reader. + * + * This method restores the dynamic extensions from the given reader + * without handling properties, which is something done by the default + * Save/Restore methods. + * + * @param[in,out] reader The reader to restore the extensions from. + */ void restoreExtensions(Base::XMLReader& reader); - /** Extends the rules for handling property name changed, so that extensions are given an - * opportunity to handle it. If an extension handles a change, neither the rest of the - * extensions, nor the container itself get to handle it. + /** + * @brief Handle a changed property name during restore. * - * Extensions get their extensionHandleChangedPropertyName() called. + * This method extends the rules for handling property name changed, so + * that extensions are given an opportunity to handle it. If an extension + * handles a change, neither the rest of the extensions, nor the container + * itself get to handle it. * - * If no extension handles the request, then the containers handleChangedPropertyName() is + * Extensions get their Extension::extensionHandleChangedPropertyName() * called. + * + * If no extension handles the request, then + * PropertyContainer::handleChangedPropertyName() is called. + * + * @param[in,out] reader The reader to restore the extensions from. + * @param[in] TypeName The name of the type of the property to handle. + * @param[in] PropName The name of the property to handle. */ void handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) override; - /** Extends the rules for handling property type changed, so that extensions are given an - * opportunity to handle it. If an extension handles a change, neither the rest of the - * extensions, nor the container itself get to handle it. + + /** + * @brief Handle a changed property type during restore. * - * Extensions get their extensionHandleChangedPropertyType() called. + * This method extends the rules for handling property type changed, so + * that extensions are given an opportunity to handle it. If an extension + * handles a change, neither the rest of the extensions, nor the container + * itself get to handle it. * - * If no extension handles the request, then the containers handleChangedPropertyType() is - * called. + * Extensions get their Extension::extensionHandleChangedPropertyType() called. + * + * If no extension handles the request, then + * PropertyContainer::handleChangedPropertyType() is called. + * + * @param[in,out] reader The reader to restore the extensions from. + * @param[in] TypeName The name of the type of the property to handle. + * @param[in] prop The property that needs to be restored. Its type differs from `TypeName`. */ void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, diff --git a/src/App/ExtensionPython.h b/src/App/ExtensionPython.h index 6ba59bd548..a4d8e7428b 100644 --- a/src/App/ExtensionPython.h +++ b/src/App/ExtensionPython.h @@ -87,7 +87,7 @@ using ExtensionPython = ExtensionPythonT; catch (Py::Exception&) \ { \ Base::PyException e; \ - e.ReportException(); \ + e.reportException(); \ } #define EXTENSION_PROXY_NOARG(function) \ diff --git a/src/App/FeaturePython.cpp b/src/App/FeaturePython.cpp index c4188223c9..433289fc08 100644 --- a/src/App/FeaturePython.cpp +++ b/src/App/FeaturePython.cpp @@ -99,7 +99,7 @@ bool FeaturePythonImp::execute() PyErr_Clear(); return false; } - Base::PyException::ThrowException(); // extract the Python error text + Base::PyException::throwException(); // extract the Python error text } return false; @@ -123,7 +123,7 @@ bool FeaturePythonImp::mustExecute() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return false; } @@ -156,7 +156,7 @@ void FeaturePythonImp::onBeforeChange(const Property* prop) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -183,7 +183,7 @@ bool FeaturePythonImp::onBeforeChangeLabel(std::string& newLabel) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return false; } @@ -214,7 +214,7 @@ void FeaturePythonImp::onChanged(const Property* prop) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -236,7 +236,7 @@ void FeaturePythonImp::onDocumentRestored() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -258,7 +258,7 @@ void FeaturePythonImp::unsetupObject() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -330,7 +330,7 @@ bool FeaturePythonImp::getSubObject(DocumentObject*& ret, return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); ret = nullptr; return true; } @@ -367,7 +367,7 @@ bool FeaturePythonImp::getSubObjects(std::vector& ret, int reason) return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return true; } } @@ -424,7 +424,7 @@ bool FeaturePythonImp::getLinkedObject(DocumentObject*& ret, return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); ret = nullptr; return true; } @@ -453,7 +453,7 @@ FeaturePythonImp::ValueT FeaturePythonImp::hasChildElement() const } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -474,7 +474,7 @@ int FeaturePythonImp::isElementVisible(const char* element) const return -2; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return -1; } } @@ -496,7 +496,7 @@ int FeaturePythonImp::setElementVisible(const char* element, bool visible) return -2; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return -1; } } @@ -512,7 +512,7 @@ std::string FeaturePythonImp::getViewProviderName() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return {}; @@ -534,7 +534,7 @@ FeaturePythonImp::ValueT FeaturePythonImp::canLinkProperties() const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -556,7 +556,7 @@ FeaturePythonImp::ValueT FeaturePythonImp::allowDuplicateLabel() const } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -577,7 +577,7 @@ int FeaturePythonImp::canLoadPartial() const return -1; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return 0; } } @@ -609,7 +609,7 @@ FeaturePythonImp::ValueT FeaturePythonImp::redirectSubName(std::ostringstream& s } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -631,7 +631,7 @@ bool FeaturePythonImp::editProperty(const char* name) } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return false; } diff --git a/src/App/FeatureTest.cpp b/src/App/FeatureTest.cpp index 1a2ab12c21..e645193844 100644 --- a/src/App/FeatureTest.cpp +++ b/src/App/FeatureTest.cpp @@ -346,7 +346,7 @@ FeatureTestAttribute::~FeatureTestAttribute() } catch (Py::Exception& e) { e.clear(); - Base::Console().Error("Unexpected exception in ~FeatureTestRemoval()\n"); + Base::Console().error("Unexpected exception in ~FeatureTestRemoval()\n"); } } diff --git a/src/App/GeoFeatureGroupExtension.cpp b/src/App/GeoFeatureGroupExtension.cpp index 2828430ff4..0d0fd7c76a 100644 --- a/src/App/GeoFeatureGroupExtension.cpp +++ b/src/App/GeoFeatureGroupExtension.cpp @@ -134,7 +134,7 @@ Base::Placement GeoFeatureGroupExtension::recursiveGroupPlacement( auto parent = link->getExtensionByType(true); if (parent && parent->hasObject(group->getExtendedObject())) { // Cyclic dependencies detected - if (history.count(parent) > 0) { + if (history.contains(parent)) { break; } return recursiveGroupPlacement(parent, history) * group->placement().getValue(); diff --git a/src/App/Graphviz.cpp b/src/App/Graphviz.cpp index 9ab33c173b..aca3509cfc 100644 --- a/src/App/Graphviz.cpp +++ b/src/App/Graphviz.cpp @@ -290,7 +290,7 @@ void Document::exportGraphviz(std::ostream& out) const { // don't add objects twice - if (std::ranges::find(objects, docObj) != objects.end()) { + if (objects.contains(docObj)) { return; } diff --git a/src/App/GroupExtension.cpp b/src/App/GroupExtension.cpp index 3eccb53232..35b89da49b 100644 --- a/src/App/GroupExtension.cpp +++ b/src/App/GroupExtension.cpp @@ -236,7 +236,7 @@ bool GroupExtension::hasObject(const DocumentObject* obj, bool recursive) const return false; } catch (const Base::RuntimeError& e) { - e.ReportException(); + e.reportException(); return false; } } diff --git a/src/App/Link.cpp b/src/App/Link.cpp index 36506e8259..4d515298be 100644 --- a/src/App/Link.cpp +++ b/src/App/Link.cpp @@ -429,11 +429,11 @@ App::DocumentObjectExecReturn* LinkBaseExtension::extensionExecute() } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return new App::DocumentObjectExecReturn(errMsg); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); return new App::DocumentObjectExecReturn(errMsg); } } @@ -451,7 +451,7 @@ App::DocumentObjectExecReturn* LinkBaseExtension::extensionExecute() parent->removeDynamicProperty(prop->getName()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { } @@ -538,7 +538,7 @@ void LinkBaseExtension::setOnChangeCopyObject(App::DocumentObject* obj, OnChange obj->addDynamicProperty("App::PropertyMap", "_CopyOnChangeControl")); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } if (!prop) { FC_ERR("Failed to setup copy on change object " << obj->getFullName()); @@ -880,7 +880,7 @@ bool LinkBaseExtension::setupCopyOnChange( if (!gname || !boost::starts_with(gname, _GroupPrefix)) { continue; } - if (!newProps.count(prop)) { + if (!newProps.contains(prop)) { parent->removeDynamicProperty(prop->getName()); } } @@ -1833,7 +1833,7 @@ void LinkBaseExtension::updateGroup() } } for (auto it = plainGroupConns.begin(); it != plainGroupConns.end();) { - if (!groupSet.count(it->first)) { + if (!groupSet.contains(it->first)) { it = plainGroupConns.erase(it); } else { diff --git a/src/App/MeasureManager.cpp b/src/App/MeasureManager.cpp index d6b4c07a81..1047aad850 100644 --- a/src/App/MeasureManager.cpp +++ b/src/App/MeasureManager.cpp @@ -186,7 +186,7 @@ std::vector MeasureManager::getValidMeasureTypes(App::MeasureSelec } catch (const Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); isValid = Py::False(); } @@ -199,7 +199,7 @@ std::vector MeasureManager::getValidMeasureTypes(App::MeasureSelec } catch (const Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); isPriority = Py::False(); } diff --git a/src/App/ObjectIdentifier.cpp b/src/App/ObjectIdentifier.cpp index 8dc4797ed4..b650897073 100644 --- a/src/App/ObjectIdentifier.cpp +++ b/src/App/ObjectIdentifier.cpp @@ -51,16 +51,6 @@ FC_LOG_LEVEL_INIT("Expression", true, true) using namespace App; using namespace Base; -// Path class - -/** - * @brief Quote input string according to quoting rules for an expression: because " and ' are - * used to designate inch and foot units, strings are quoted as <>. - * - * @param input - * @return - */ - std::string App::quote(const std::string& input, bool toPython) { std::stringstream output; @@ -103,12 +93,6 @@ std::string App::quote(const std::string& input, bool toPython) } -/** - * @brief Construct an ObjectIdentifier object, given an owner and a single-value property. - * @param _owner Owner of property. - * @param property Name of property. - */ - ObjectIdentifier::ObjectIdentifier(const App::PropertyContainer* _owner, const std::string& property, int index) @@ -153,12 +137,6 @@ ObjectIdentifier::ObjectIdentifier(const App::PropertyContainer* _owner, bool lo } } -/** - * @brief Construct an ObjectIdentifier object given a property. The property is assumed to be - * single-valued. - * @param prop Property to construct object identifier for. - */ - ObjectIdentifier::ObjectIdentifier(const Property& prop, int index) : owner(nullptr) , documentNameSet(false) @@ -185,11 +163,6 @@ ObjectIdentifier::ObjectIdentifier(const Property& prop, int index) } } -/** - * @brief Get the name of the property. - * @return Name - */ - std::string App::ObjectIdentifier::getPropertyName() const { ResolveResults result(*this); @@ -200,13 +173,6 @@ std::string App::ObjectIdentifier::getPropertyName() const return components[result.propertyIndex].getName(); } -/** - * @brief Get Component at given index \a i. - * @param i: Index to get - * @param idx: optional return of adjusted component index - * @return A component. - */ - const App::ObjectIdentifier::Component& App::ObjectIdentifier::getPropertyComponent(int i, int* idx) const { @@ -252,34 +218,16 @@ std::vector ObjectIdentifier::getPropertyComponents return res; } -/** - * @brief Compare object identifier with \a other. - * @param other Other object identifier. - * @return true if they are equal. - */ - bool ObjectIdentifier::operator==(const ObjectIdentifier& other) const { return owner == other.owner && toString() == other.toString(); } -/** - * @brief Compare object identifier with \a other. - * @param other Other object identifier - * @return true if they differ from each other. - */ - bool ObjectIdentifier::operator!=(const ObjectIdentifier& other) const { return !(operator==)(other); } -/** - * @brief Compare object identifier with other. - * @param other Other object identifier. - * @return true if this object is less than the other. - */ - bool ObjectIdentifier::operator<(const ObjectIdentifier& other) const { if (owner < other.owner) { @@ -291,21 +239,11 @@ bool ObjectIdentifier::operator<(const ObjectIdentifier& other) const return toString() < other.toString(); } -/** - * @brief Return number of components. - * @return Number of components in this identifier. - */ - int ObjectIdentifier::numComponents() const { return components.size(); } -/** - * @brief Compute number of sub components, i.e excluding the property. - * @return Number of components. - */ - int ObjectIdentifier::numSubComponents() const { ResolveResults result(*this); @@ -341,17 +279,6 @@ bool ObjectIdentifier::verify(const App::Property& prop, bool silent) const return true; } -/** - * @brief Create a string representation of this object identifier. - * - * An identifier is written as document#documentobject.property.subproperty1...subpropertyN - * document# may be dropped; it is assumed to be within owner's document. If documentobject is - * dropped, the property is assumed to be owned by the owner specified in the object identifiers - * constructor. - * - * @return A string - */ - const std::string& ObjectIdentifier::toString() const { if (!_cache.empty() || !owner) { @@ -510,17 +437,12 @@ bool ObjectIdentifier::replaceObject(ObjectIdentifier& res, return true; } -/** - * @brief Escape toString representation so it is suitable for being embedded in a python command. - * @return Escaped string. - */ - std::string ObjectIdentifier::toEscapedString() const { return Base::Tools::escapedUnicodeFromUtf8(toString().c_str()); } -bool ObjectIdentifier::updateLabelReference(App::DocumentObject* obj, +bool ObjectIdentifier::updateLabelReference(const App::DocumentObject* obj, const std::string& ref, const char* newLabel) { @@ -606,11 +528,6 @@ bool ObjectIdentifier::relabeledDocument(ExpressionVisitor& v, return false; } -/** - * @brief Get sub field part of a property as a string. - * @return String representation of path. - */ - void ObjectIdentifier::getSubPathStr(std::ostream& s, const ResolveResults& result, bool toPython) const @@ -633,14 +550,6 @@ std::string ObjectIdentifier::getSubPathStr(bool toPython) const } -/** - * @brief Construct a Component part - * @param _name Name of component - * @param _type Type; simple, array, range or map - * @param _begin Array index or beginning of a Range, or INT_MAX for other type. - * @param _end ending of a Range, or INT_MAX for other type. - */ - ObjectIdentifier::Component::Component(const String& _name, ObjectIdentifier::Component::typeEnum _type, int _begin, @@ -665,7 +574,6 @@ ObjectIdentifier::Component::Component(String&& _name, , step(_step) {} - size_t ObjectIdentifier::Component::getIndex(size_t count) const { if (begin >= 0) { @@ -711,12 +619,12 @@ Py::Object ObjectIdentifier::Component::get(const Py::Object& pyobj) const true); PyObject* r = PyObject_GetItem(pyobj.ptr(), slice.ptr()); if (!r) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } res = Py::asObject(r); } if (!res.ptr()) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } if (PyModule_Check(res.ptr()) && !ExpressionParser::isModuleImported(res.ptr())) { FC_THROWM(Base::RuntimeError, "Module '" << getName() << "' access denied."); @@ -728,7 +636,7 @@ void ObjectIdentifier::Component::set(Py::Object& pyobj, const Py::Object& value { if (isSimple()) { if (PyObject_SetAttrString(*pyobj, getName().c_str(), *value) == -1) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } } else if (isArray()) { @@ -750,7 +658,7 @@ void ObjectIdentifier::Component::set(Py::Object& pyobj, const Py::Object& value step != 1 ? Py::Long(step).ptr() : nullptr), true); if (PyObject_SetItem(pyobj.ptr(), slice.ptr(), value.ptr()) < 0) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } } } @@ -779,28 +687,16 @@ void ObjectIdentifier::Component::del(Py::Object& pyobj) const step != 1 ? Py::Long(step).ptr() : nullptr), true); if (PyObject_DelItem(pyobj.ptr(), slice.ptr()) < 0) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } } } -/** - * @brief Create a simple component part with the given name - * @param _component Name of component. - * @return A new Component object. - */ - ObjectIdentifier::Component ObjectIdentifier::Component::SimpleComponent(const char* _component) { return Component(String(_component)); } -/** - * @brief Create a simple component part with the given name - * @param _component Name of component. - * @return A new Component object. - */ - ObjectIdentifier::Component ObjectIdentifier::Component::SimpleComponent(const ObjectIdentifier::String& _component) { @@ -813,25 +709,11 @@ ObjectIdentifier::Component::SimpleComponent(ObjectIdentifier::String&& _compone return Component(std::move(_component)); } -/** - * @brief Create an array component with given name and index. - * @param _component Name of component - * @param _index Index of component - * @return A new Component object. - */ - ObjectIdentifier::Component ObjectIdentifier::Component::ArrayComponent(int _index) { return Component(String(), Component::ARRAY, _index); } -/** - * @brief Create a map component with given name and key. - * @param _component Name of component - * @param _key Key of component - * @return A new Component object. - */ - ObjectIdentifier::Component ObjectIdentifier::Component::MapComponent(const String& _key) { return Component(_key, Component::MAP); @@ -842,26 +724,12 @@ ObjectIdentifier::Component ObjectIdentifier::Component::MapComponent(String&& _ return Component(std::move(_key), Component::MAP); } - -/** - * @brief Create a range component with given begin and end. - * @param _begin beginning index of the range - * @param _end ending index of the range - * @return A new Component object. - */ - ObjectIdentifier::Component ObjectIdentifier::Component::RangeComponent(int _begin, int _end, int _step) { return Component(String(), Component::RANGE, _begin, _end, _step); } -/** - * @brief Comparison operator for Component objects. - * @param other The object we want to compare to. - * @return true if they are equal, false if not. - */ - bool ObjectIdentifier::Component::operator==(const ObjectIdentifier::Component& other) const { if (type != other.type) { @@ -882,11 +750,6 @@ bool ObjectIdentifier::Component::operator==(const ObjectIdentifier::Component& } } -/** - * @brief Create a string representation of a component. - * @return A string representing the component. - */ - void ObjectIdentifier::Component::toString(std::ostream& ss, bool toPython) const { switch (type) { @@ -925,17 +788,6 @@ enum ResolveFlags ResolveAmbiguous, }; -/** - * @brief Search for the document object given by name in doc. - * - * Name might be the internal name or a label. In any case, it must uniquely define - * the document object. - * - * @param doc Document to search - * @param name Name to search for. - * @return Pointer to document object if a unique pointer is found, 0 otherwise. - */ - App::DocumentObject* ObjectIdentifier::getDocumentObject(const App::Document* doc, const String& name, std::bitset<32>& flags) @@ -991,13 +843,6 @@ App::DocumentObject* ObjectIdentifier::getDocumentObject(const App::Document* do } } -/** - * @brief Resolve the object identifier to a concrete document, documentobject, and property. - * - * This method is a helper method that fills out data in the given ResolveResults object. - * - */ - void ObjectIdentifier::resolve(ResolveResults& results) const { if (!owner) { @@ -1128,12 +973,6 @@ void ObjectIdentifier::resolve(ResolveResults& results) const } } -/** - * @brief Find a document with the given name. - * @param name Name of document - * @return Pointer to document, or 0 if it is not found or not uniquely defined by name. - */ - Document* ObjectIdentifier::getDocument(String name, bool* ambiguous) const { if (name.getString().empty()) { @@ -1186,11 +1025,6 @@ Document* ObjectIdentifier::getDocument(String name, bool* ambiguous) const } } -/** - * @brief Get the document object for the object identifier. - * @return Pointer to document object, or 0 if not found or uniquely defined. - */ - DocumentObject* ObjectIdentifier::getDocumentObject() const { const App::Document* doc = getDocument(); @@ -1290,11 +1124,6 @@ void ObjectIdentifier::getDep(Dependencies& deps, } } -/** - * @brief Get components as a string list. - * @return List of strings. - */ - std::vector ObjectIdentifier::getStringList() const { std::vector l; @@ -1323,12 +1152,6 @@ std::vector ObjectIdentifier::getStringList() const return l; } -/** - * @brief Construct the simplest possible object identifier relative to another. - * @param other The other object identifier. - * @return A new simplified object identifier. - */ - ObjectIdentifier ObjectIdentifier::relativeTo(const ObjectIdentifier& other) const { ObjectIdentifier result(other.getOwner()); @@ -1351,16 +1174,6 @@ ObjectIdentifier ObjectIdentifier::relativeTo(const ObjectIdentifier& other) con return result; } -/** - * @brief Parse a string to create an object identifier. - * - * This method throws an exception if the string is invalid. - * - * @param docObj Document object that will own this object identifier. - * @param str String to parse - * @return A new object identifier. - */ - ObjectIdentifier ObjectIdentifier::parse(const DocumentObject* docObj, const std::string& str) { std::unique_ptr expr(ExpressionParser::parse(docObj, str.c_str())); @@ -1381,12 +1194,6 @@ std::string ObjectIdentifier::resolveErrorString() const return result.resolveErrorString(); } -/** - * @brief << operator, used to add a component to the object identifier. - * @param value Component object - * @return Reference to itself. - */ - ObjectIdentifier& ObjectIdentifier::operator<<(const ObjectIdentifier::Component& value) { components.push_back(value); @@ -1402,11 +1209,6 @@ ObjectIdentifier& ObjectIdentifier::operator<<(ObjectIdentifier::Component&& val } -/** - * @brief Get pointer to property pointed to by this object identifier. - * @return Point to property if it is uniquely defined, or 0 otherwise. - */ - Property* ObjectIdentifier::getProperty(int* ptype) const { ResolveResults result(*this); @@ -1462,15 +1264,6 @@ Property* ObjectIdentifier::resolveProperty(const App::DocumentObject* obj, } -/** - * @brief Create a canonical representation of an object identifier. - * - * The main work is actually done by the property's virtual canonicalPath(...) method, - * which is invoked by this call. - * - * @return A new object identifier. - */ - ObjectIdentifier ObjectIdentifier::canonicalPath() const { ObjectIdentifier res(*this); @@ -1498,15 +1291,6 @@ ObjectIdentifier::DocumentMapper::~DocumentMapper() _DocumentMap = nullptr; } -/** - * @brief Set the document name for this object identifier. - * - * If force is true, the document name will always be included in the string representation. - * - * @param name Name of document object. - * @param force Force name to be set - */ - void ObjectIdentifier::setDocumentName(ObjectIdentifier::String&& name, bool force) { if (name.getString().empty()) { @@ -1533,12 +1317,6 @@ void ObjectIdentifier::setDocumentName(ObjectIdentifier::String&& name, bool for documentName = std::move(name); } -/** - * @brief Get the document name from this object identifier - * - * @return Document name as a String object. - */ - ObjectIdentifier::String ObjectIdentifier::getDocumentName() const { ResolveResults result(*this); @@ -1546,16 +1324,6 @@ ObjectIdentifier::String ObjectIdentifier::getDocumentName() const return result.resolvedDocumentName; } -/** - * @brief Set the document object name of this object identifier. - * - * If force is true, the document object will not be resolved dynamically from the - * object identifier's components, but used as given by this method. - * - * @param name Name of document object. - * @param force Force name to be set. - */ - void ObjectIdentifier::setDocumentObjectName(ObjectIdentifier::String&& name, bool force, ObjectIdentifier::String&& subname, @@ -1619,11 +1387,6 @@ void ObjectIdentifier::setDocumentObjectName(const App::DocumentObject* obj, } -/** - * @brief Get the document object name - * @return String with name of document object as resolved by object identifier. - */ - ObjectIdentifier::String ObjectIdentifier::getDocumentObjectName() const { ResolveResults result(*this); @@ -1636,11 +1399,6 @@ bool ObjectIdentifier::hasDocumentObjectName(bool forced) const return !documentObjectName.getString().empty() && (!forced || documentObjectNameSet); } -/** - * @brief Get a string representation of this object identifier. - * @return String representation. - */ - std::string ObjectIdentifier::String::toString(bool toPython) const { if (isRealString()) { @@ -1653,7 +1411,7 @@ std::string ObjectIdentifier::String::toString(bool toPython) const void ObjectIdentifier::String::checkImport(const App::DocumentObject* owner, const App::DocumentObject* obj, - String* objName) + const String* objName) { if (owner && owner->getDocument() && !str.empty() && ExpressionParser::ExpressionImporter::reader()) { @@ -1695,7 +1453,7 @@ void ObjectIdentifier::String::checkImport(const App::DocumentObject* owner, } Py::Object -ObjectIdentifier::access(const ResolveResults& result, Py::Object* value, Dependencies* deps) const +ObjectIdentifier::access(const ResolveResults& result, const Py::Object* value, Dependencies* deps) const { if (!result.resolvedDocumentObject || !result.resolvedProperty || (!subObjectName.getString().empty() && !result.resolvedSubObject)) { @@ -1714,7 +1472,7 @@ ObjectIdentifier::access(const ResolveResults& result, Py::Object* value, Depend if (!pymod) { \ pymod = PyImport_ImportModule(#_name); \ if (!pymod) \ - Base::PyException::ThrowException(); \ + Base::PyException::throwException(); \ else \ Py_DECREF(pymod); \ } \ @@ -1924,19 +1682,6 @@ ObjectIdentifier::access(const ResolveResults& result, Py::Object* value, Depend return pyobj; } -/** - * @brief Get the value of the property or field pointed to by this object identifier. - * - * All type of objects are supported. Some types are casted to FC native - * type, including: Int, Float, String, Unicode String, and Quantities. Others - * are just kept as Python object wrapped by App::any. - * - * @param pathValue: if true, calls the property's getPathValue(), which is - * necessary for Qunatities to work. - * - * @return The value of the property or field. - */ - App::any ObjectIdentifier::getValue(bool pathValue, bool* isPseudoProperty) const { ResolveResults rs(*this); @@ -1959,7 +1704,7 @@ App::any ObjectIdentifier::getValue(bool pathValue, bool* isPseudoProperty) cons return pyObjectToAny(access(rs)); } catch (Py::Exception&) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } return {}; } @@ -1988,21 +1733,11 @@ Py::Object ObjectIdentifier::getPyValue(bool pathValue, bool* isPseudoProperty) return access(rs); } catch (Py::Exception&) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } return Py::Object(); } -/** - * @brief Set value of a property or field pointed to by this object identifier. - * - * This method uses Python to do the actual work. and a limited set of types that - * can be in the App::any variable is supported: Base::Quantity, double, - * char*, const char*, int, unsigned int, short, unsigned short, char, and unsigned char. - * - * @param value Value to set - */ - void ObjectIdentifier::setValue(const App::any& value) const { std::stringstream ss; @@ -2017,7 +1752,7 @@ void ObjectIdentifier::setValue(const App::any& value) const access(rs, &pyvalue); } catch (Py::Exception&) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } } @@ -2150,7 +1885,7 @@ void ObjectIdentifier::resolveAmbiguity() resolveAmbiguity(result); } -void ObjectIdentifier::resolveAmbiguity(ResolveResults& result) +void ObjectIdentifier::resolveAmbiguity(const ResolveResults& result) { if (!result.resolvedDocumentObject) { @@ -2180,12 +1915,6 @@ void ObjectIdentifier::resolveAmbiguity(ResolveResults& result) } } -/** Construct and initialize a ResolveResults object, given an ObjectIdentifier instance. - * - * The constructor will invoke the ObjectIdentifier's resolve() method to initialize the object's - * data. - */ - ObjectIdentifier::ResolveResults::ResolveResults(const ObjectIdentifier& oi) : propertyType(PseudoNone) { diff --git a/src/App/ObjectIdentifier.h b/src/App/ObjectIdentifier.h index 60cb5e19c6..3484331d81 100644 --- a/src/App/ObjectIdentifier.h +++ b/src/App/ObjectIdentifier.h @@ -44,12 +44,38 @@ namespace App using any = boost::any; +/** + * @brief Extract a const reference from a boost::any object. + * + * This function is a wrapper around boost::any_cast that allows + * to extract a const reference from a boost::any object. + * + * @tparam T The type to extract. + * + * @param[in] value The boost::any object to extract from. + * + * @return A const reference to the extracted value. + * @throws boost::bad_any_cast if the type of the value does not match T. + */ template inline const T& any_cast(const boost::any& value) { return boost::any_cast(value); } +/** + * @brief Extract a mutable reference from a boost::any object. + * + * This function is a wrapper around boost::any_cast that allows + * to extract a mutable reference from a boost::any object. + * + * @tparam T The type to extract. + * + * @param[in] value The boost::any object to extract from. + * + * @return A const reference to the extracted value. + * @throws boost::bad_any_cast if the type of the value does not match T. + */ template inline T& any_cast(boost::any& value) { @@ -62,6 +88,19 @@ class PropertyContainer; class DocumentObject; class ExpressionVisitor; +/** + * @brief Quote a string. + * + * Quote an input string according to quoting rules for an expression: because + * " and ' are used to designate inch and foot units, strings are quoted as + * `<>`. + * + * @param[in] input The string to quote. + * @param[in] toPython If true, use Python quoting rules. Otherwise, use + * FreeCAD quoting rules. + * + * @return The string quoted. + */ AppExport std::string quote(const std::string& input, bool toPython = false); // Unfortunately VS2013 does not support default move constructor, so we have @@ -75,28 +114,81 @@ AppExport std::string quote(const std::string& input, bool toPython = false); } \ _t& operator=(_t&& other) + +/** + * @brief A class that identifies properties in document objects. + * + * An object identifier is a data structure that identifies a (sub)properties + * in a document or document objects, or documents or document objects + * themselves. + */ class AppExport ObjectIdentifier { public: + /** + * @brief A helper class to maintain a mapping between document names. + * + * This class maps old document names to new document names and is used to + * provide a scope in which calls to setDocumentName() make use of the + * mapping stored here. + */ class AppExport DocumentMapper { public: + /** + * @brief Construct a DocumentMapper object. + * + * The constructor takes a map of document names and stores a pointer + * to it in a variable local to the compilation unit. The idea is to + * create a %DocumentMapper on the stack and when it goes out of scope, + * all is reset. During that time calls to setDocumentName() can be + * done, making use of the mapping provided with this constructor. + */ explicit DocumentMapper(const std::map&); + + /** + * @brief Destroy the DocumentMapper object. + * + * When the DocumentMapper goes out of scope, the pointer to the + * variable local to the compilation unit is set to `nullptr`. + */ ~DocumentMapper(); }; + /** + * @brief A class that represents a string in an ObjectIdentifier. + */ class String { friend class ObjectIdentifier; public: + /** + * @brief Construct a String object for object identifiers. + * + * @param[in] s The string to be used. + * @param[in] _isRealString If true, the string is a real string and should be + * quoted. Otherwise, it is a simple identifier. + * @param[in] _forceIdentifier If true, the string is a forced identifier. + */ String(const std::string& s = "", bool _isRealString = false, bool _forceIdentifier = false) : str(s) , isString(_isRealString) , forceIdentifier(_forceIdentifier) {} // explicit bombs + /** + * @brief Explicit move‐construct a String object for object identifiers. + * + * This constructor takes ownership of the provided string via move semantics, + * preventing an implicit conversion from temporary std::string. + * + * @param[in,out] s The string to be used (will be moved-from). + * @param[in] _isRealString If true, the string is a real string and should be + * quoted. Otherwise, it is a simple identifier. + * @param[in] _forceIdentifier If true, the string is a forced identifier. + */ explicit String(std::string&& s, bool _isRealString = false, bool _forceIdentifier = false) : str(std::move(s)) , isString(_isRealString) @@ -113,66 +205,166 @@ public: // Accessors - /** Returns the string */ + /** + * @brief Get the string as a `std::string`. + * + * @return The string as a `std::string`. + */ const std::string& getString() const { return str; } - /** Return true is string need to be quoted */ + /** + * @brief Test whether the string is a real string. + * + * A real string is a string that should be quoted. A simple identifier + * is a string that should not be quoted. + * + * @return True if the string is a real string, false otherwise. + */ bool isRealString() const { return isString; } + /** + * @brief Test whether the string is a forced identifier. + * + * A forced identifier is a string that should be treated as an + * identifier. + * + * @return True if the string is a forced identifier, false otherwise. + */ bool isForceIdentifier() const { return forceIdentifier; } - /** Returns a possibly quoted string */ + /** + * @brief Get a string representation of this object identifier. + * + * @param[in] toPython If true, use Python quoting rules. Otherwise, use + * FreeCAD quoting rules. + * @return The string representation. + */ std::string toString(bool toPython = false) const; // Operators + /** + * @brief Explicitly convert to `std::string`. + * + * Returns a copy of the internal std::string. Because this operator is + * marked explicit, it is required to use a cast: + * `static_cast(myString)`. + * + * @return A copy of the string as `std::string`. + */ explicit operator std::string() const { return str; } + /** + * @brief Explicitly convert to C-style string. + * + * Returns a pointer to the internal null-terminated character array. + * The pointer remains valid as long as the String object is alive and + * unmodified. This operator is explicit, so it is required to use: + * `static_cast(myString)`. + * + * @return A const char* pointing at the internal string buffer. + */ explicit operator const char*() const { return str.c_str(); } + /** + * @brief Test for equality. + * + * Compares the underlying string values for exact equality. + * + * @param[in] other The %String to compare against. + * @return true if both strings have identical content; false otherwise. + */ bool operator==(const String& other) const { return str == other.str; } + /** + * @brief Test for inequality. + * + * Compares the underlying string values for inequality. + * + * @param[in] other The %String we want to compare to. + * @return true if this string does not have identical content to the + * other string; false otherwise. + */ bool operator!=(const String& other) const { return str != other.str; } + /** + * @brief Lexicographical greater-than-or-equal-to comparison. + * + * Determines if this string is lexicographically greater than or equal + * to the other string. + * + * @param[in] other The %String to compare against. + * @return true if this string is lexicographically greater than or + * equal to `other`; false otherwise. + */ bool operator>=(const String& other) const { return str >= other.str; } + /** + * @brief Lexicographical less-than comparison. + * + * Determines if this string precedes `other` in lexicographical order. + * + * @param[in] other The %String to compare against. + * @return true if this string is lexicographically less than `other`; false otherwise. + */ bool operator<(const String& other) const { return str < other.str; } + /** + * @brief Lexicographical greater-than comparison. + * + * Determines if this string follows `other` in lexicographical order. + * + * @param[in] other The %String to compare against. + * @return true if this string is lexicographically greater than `other`; false otherwise. + */ bool operator>(const String& other) const { return str > other.str; } + /** + * @brief Remaps and resolves identifier strings during import. + * + * Applies name mapping and, if “@” markers are present, defers label + * substitution to import-time via PropertyLinkBase::importSubName() and + * PropertyLinkBase::restoreLabelReference(). + * + * @param[in] owner The importing document’s owner object. + * @param[in] obj (Optional) Direct pointer to the target object. + * @param[in] objName (Optional) Name to look up the object if @p obj is null. + * + * @sa importSubName(), restoreLabelReference() + */ void checkImport(const App::DocumentObject* owner, const App::DocumentObject* obj = nullptr, - String* objName = nullptr); + const String* objName = nullptr); private: std::string str; @@ -181,11 +373,12 @@ public: }; /** - * @brief A component is a part of a Path object, and is used to either - * name a property or a field within a property. A component can be either - * a single entry, and array, or a map to other sub-fields. + * @brief A component is a part of an ObjectIdentifier. + * + * It is used to either name a property or a field within a property. A + * component can be either a single entry, and array, or a map to other + * sub-fields. */ - class AppExport Component { @@ -210,48 +403,135 @@ public: return *this; } + /** + * @brief Construct a Component part. + * + * @param[in] _name The name of the component. + * @param[in] _type The type: `SIMPLE`, `ARRAY`, `RANGE` or `MAP`. + * @param[in] begin The array index or beginning of a range, or `INT_MAX` for other types. + * @param[in] end The ending of a range, or `INT_MAX` for other types. + * @param[in] step The step of a range, or `1` for other types. + */ Component(const String& _name = String(), typeEnum _type = SIMPLE, int begin = std::numeric_limits::max(), int end = std::numeric_limits::max(), int step = 1); // explicit bombs + + /** + * @brief Construct a Component with move semantics. + * + * @param[in,out] _name The name of the component. + * @param[in] _type The type: `SIMPLE`, `ARRAY`, `RANGE` or `MAP`. + * @param[in] begin The array index or beginning of a range, or `INT_MAX` for other types. + * @param[in] end The ending of a range, or `INT_MAX` for other types. + * @param[in] step The step of a range, or `1` for other types. + */ Component(String&& _name, typeEnum _type = SIMPLE, int begin = std::numeric_limits::max(), int end = std::numeric_limits::max(), int step = 1); // explicit bombs + /** + * @brief Create a simple component with the given name. + * + * @param[in] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(const char* _component); + /** + * @brief Create a simple component with the given name. + * + * @param[in] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(const String& _component); + + /** + * @brief Create a simple component with move semantics. + * + * @param[in,out] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(String&& _component); + /** + * @brief Create an array component an index. + * + * @param[in] _index The index of the component. + * @return A new Component object. + */ static Component ArrayComponent(int _index); + /** + * @brief Create a range component with given begin and end. + * + * @param[in] _begin The begin index of the range. + * @param[in] _end The end index of the range. + * @param[in] _step The step of the range. + * @return A new Component object. + */ static Component RangeComponent(int _begin, int _end = std::numeric_limits::max(), int _step = 1); + /** + * @brief Create a map component with a given key. + * + * @param[in] _key The key of the component. + * @return A new Component object. + */ static Component MapComponent(const String& _key); + + /** + * @brief Create a map component with move semantics. + * + * Create a map component with a given key. + * + * @param[in] _key The key of the component. + * @return A new Component object. + */ static Component MapComponent(String&& _key); // Type queries + /** + * @brief Check if the component is a simple component. + * + * @return true if the component is a simple component, false otherwise. + */ bool isSimple() const { return type == SIMPLE; } + /** + * @brief Check if the component is a map component. + * + *@return true if the component is a map component, false otherwise. + */ bool isMap() const { return type == MAP; } + /** + * @brief Check if the component is an array component. + * + * @return true if the component is an array component, false otherwise. + */ bool isArray() const { return type == ARRAY; } + /** + * @brief Check if the component is a range component. + * + * @return true if the component is a range component, false otherwise. + */ bool isRange() const { return type == RANGE; @@ -259,27 +539,75 @@ public: // Accessors + /** + * @brief Create a string representation of a component. + * + * The string is appended to the output stream. + * + * @param[in,out] ss The output stream to write to. + * @param[in] toPython If true, use Python quoting rules. Otherwise, use + * FreeCAD quoting rules. + */ void toString(std::ostream& ss, bool toPython = false) const; + /** + * @brief Get the name of the component. + * + * @return The name of the component. + */ const std::string& getName() const { return name.getString(); } + /** + * @brief Get the index of the component. + * + * @return The index of the component. + */ int getIndex() const { return begin; } + + /** + * @brief Get the index given a maximum count. + * + * This method interprets the member `begin` as a Python-style index + * that may be negative. Given the maximum count it returns a valid + * index. + * + * @param[in] count The number of elements in the target collection. + * @return The index in the range [0, count). + * @throws Base::IndexError If `begin` is out of bounds. + */ size_t getIndex(size_t count) const; + /** + * @brief Get the begin index of the component. + * + * @return The begin index of the component. + */ int getBegin() const { return begin; } + + /** + * @brief Get the end index of the component. + * + * @return The end index of the component. + */ int getEnd() const { return end; } + + /** + * @brief Get the step of the component. + * + * @return The step of the component. + */ int getStep() const { return step; @@ -287,11 +615,43 @@ public: // Operators + /** + * @brief Test the component for equality. + * + * @param[in] other The object we want to compare to. + * @return true if the components are equal, false if not. + */ bool operator==(const Component& other) const; + + /** + * @brief Lexicographical less-than comparison. + * + * @param[in] other The object we want to compare to. + * @return true if this component is lexicographically less than the other. + */ bool operator<(const Component& other) const; + /** + * @brief Get the value of the component given a Python object. + * + * @param[in] pyobj The Python object to get the value from. + * @return The value of the component. + */ Py::Object get(const Py::Object& pyobj) const; + + /** + * @brief Set the value of the component given a Python object. + * + * @param[in,out] pyobj The Python object to set the value to. + * @param[in] value The value to set. + */ void set(Py::Object& pyobj, const Py::Object& value) const; + + /** + * @brief Delete the value of the component given a Python object. + * + * @param[in,out] pyobj The Python object to delete the value from. + */ void del(Py::Object& pyobj) const; private: @@ -303,31 +663,69 @@ public: friend class ObjectIdentifier; }; + /** + * @brief Create a simple component with the given name. + * + * @param[in] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(const char* _component) { return Component::SimpleComponent(_component); } + /** + * @brief Create a simple component with the given name. + * + * @param[in] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(const String& _component) { return Component::SimpleComponent(_component); } + /** + * @brief Create a simple component with move semantics. + * + * @param[in,out] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(String&& _component) { return Component::SimpleComponent(std::move(_component)); } + /** + * @brief Create a simple component with the given name. + * + * @param[in] _component The name of the component. + * @return A new Component object. + */ static Component SimpleComponent(const std::string _component) { return Component::SimpleComponent(_component.c_str()); } + /** + * @brief Create an array component with the given index. + * + * @param[in] _index The index of the component. + * @return A new Component object. + */ static Component ArrayComponent(int _index) { return Component::ArrayComponent(_index); } + /** + * @brief Create a range component with given begin and end. + * + * @param[in] _begin The begin index of the range. + * @param[in] _end The end index of the range. + * @param[in] _step The step of the range. + * @return A new Component object. + */ static Component RangeComponent(int _begin, int _end = std::numeric_limits::max(), int _step = 1) @@ -335,22 +733,63 @@ public: return Component::RangeComponent(_begin, _end, _step); } + /** + * @brief Create a map component with a given key. + * + * @param[in] _key The key of the component. + * @return A new Component object. + */ static Component MapComponent(const String& _key) { return Component::MapComponent(_key); } + /** + * @brief Create a map component with move semantics. + * + * @param[in,out] _key The key of the component. + * @return A new Component object. + */ static Component MapComponent(String&& _key) { return Component::MapComponent(_key); } + /** + * @brief Construct an ObjectIdentifier object. + * + * Construct an ObjectIdentifier object given an owner and a single-value + * property, possibly with an array index. + * + * @param[in] _owner The owner of the property. + * @param[in] property The name of the property. + * @param[in] index The index into the array. + * @throw Base::RuntimeError if the owner is not a document object. + */ explicit ObjectIdentifier(const App::PropertyContainer* _owner = nullptr, const std::string& property = std::string(), int index = std::numeric_limits::max()); + /** + *@brief Construct an ObjectIdentifier object. + * + * @param[in] _owner The owner of the property. + * @param[in] localProperty If true, the property is a local property. + * @throw Base::RuntimeError if the owner is not a document object. + */ ObjectIdentifier(const App::PropertyContainer* _owner, bool localProperty); + /** + * @brief Construct an ObjectIdentifier object given a property. + * + * The property is assumed to be single-valued but may have an array index. + * + * @param[in] prop The property to construct object identifier for. + * @param[in] index The index into the array. + * + * @throw Base::RuntimeError if the owner is not a document object or if + * the property does not have a name. + */ ObjectIdentifier(const App::Property& prop, int index = std::numeric_limits::max()); // explicit bombs @@ -370,150 +809,441 @@ public: return *this; } + /// Destruct an ObjectIdentifier object. virtual ~ObjectIdentifier() = default; + /** + * @brief Get the owner of this object identifier. + * + * @return The owner of this object identifier. + */ App::DocumentObject* getOwner() const { return owner; } - // Components + /** + * @brief Add a component to this object identifier. + * + * @param[in] c The component to add. + */ void addComponent(const Component& c) { components.push_back(c); _cache.clear(); } - // Components + /** + * @brief Add a component to this object identifier with move semantics. + * + * @param[in] c The component to add. + */ void addComponent(Component&& c) { components.push_back(std::move(c)); _cache.clear(); } + /** + * @brief Get the name of the property. + * @return The name of the property. + */ std::string getPropertyName() const; + /** + * @brief Add components to this object identifier. + * + * @tparam C A container type that supports iterators. + * @param[in] cs The components to add. + */ template void addComponents(const C& cs) { components.insert(components.end(), cs.begin(), cs.end()); } + /** + * @brief Get a component given an index. + * + * @param[in] i: The index of the component. + * @param[out] idx: Optional return of an adjusted component index. + * @return A component. + */ const Component& getPropertyComponent(int i, int* idx = nullptr) const; + /** + * @brief Set a component at an index with move semantics. + * + * @param[in] idx: The index to store the component. + * @param[in,out] comp: The component to set. + */ void setComponent(int idx, Component&& comp); + + /** + * @brief Set a component at an index. + * + * @param[in] idx: The index to store the component. + * @param[in] comp: The component to set. + */ void setComponent(int idx, const Component& comp); + /** + * @brief Get the property components of this object identifier. + * + * @return A vector of components of properties. + */ std::vector getPropertyComponents() const; + + /** + * @brief Get the components of this object identifier. + * + * @return A vector of components. + */ const std::vector& getComponents() const { return components; } + /** + * @brief Get a string representation of the subpath. + * + * @param[in] toPython If true, use Python quoting rules. Otherwise, use + * FreeCAD quoting rules. + * + * @return The string representation of the subpath. + */ std::string getSubPathStr(bool toPython = false) const; + /** + * @brief Return the number of components. + * + * @return The number of components in this identifier. + */ int numComponents() const; + /** + * @brief Compute the number of sub components. + * + * Compute the number of sub components, meaning that this excludes the property. + * + * @return Number of components. + */ int numSubComponents() const; + /** + * @brief Create a string representation of this object identifier. + * + * An identifier is written as + * `document#documentobject.property.subproperty1...subpropertyN`. The + * string `document#` may be dropped; in that case it is assumed to be + * within owner's document. If `documentobject` is dropped, the property + * is assumed to be owned by the owner specified in the object identifiers + * constructor. + * + * @return A string representation of the object identifier. + */ const std::string& toString() const; + /** + * @brief Create a persistent string representation of this object identifier. + * + * The persistent string representation is used where the object identifier + * is required to survive import and export. + * + * @see toString() + * + * @return A persistent string representation of the object identifier. + */ std::string toPersistentString() const; + /** + * @brief Create an escapedstring representation of this object identifier. + * + * The escaped string representation is suitable for being embedded in a + * Python command. + * + * @return The escaped string representation. + */ std::string toEscapedString() const; + /** + * @brief Wether the property of the object identifier is touched. + * + * This method is used to determine if the property that this object + * identifier represents is touched. + * + * @return true if the property of the object identifier is touched, false + * otherwise. + */ bool isTouched() const; + /** + * @brief Get the property this object identifier represents. + * + * @param[out] ptype Optional return of the property type. + * + * @return A pointer to property if it is uniquely defined, or `nullptr` otherwise. + */ App::Property* getProperty(int* ptype = nullptr) const; + /** + * @brief Create a canonical representation of the object identifier. + * + * The main work is actually done by the property's virtual + * Property::canonicalPath() method that is invoked by this call. + * + * @return A new object identifier. + */ App::ObjectIdentifier canonicalPath() const; // Document-centric functions + /** + * @brief Set the document name for this object identifier. + * + * If @p force is true, the document name will always be included in the + * string representation. + * + * @param[in,out] name The name of the document. + * @param[in] force Force the name to be set. + */ void setDocumentName(String&& name, bool force = false); + /** + * @brief Get the document name from this object identifier + * + * @return The document name as a String object. + */ String getDocumentName() const; + /** + * @brief Set the document object name of this object identifier. + * + * If force is true, the document object will not be resolved dynamically + * from the object identifier's components, but used as given by this + * method. + * + * This function uses move semantics on @p name and @p subname. + * + * @param[in,out] name The name of document object. + * @param[in] force Force the name to be set. + * @param[in,out] subname The name of the subobject. + * @param[in] checkImport If true, check for import. + */ void setDocumentObjectName(String&& name, bool force = false, String&& subname = String(), bool checkImport = false); + /** + * @brief Set the document object name of this object identifier. + * + * If force is true, the document object will not be resolved dynamically + * from the object identifier's components, but used as given by this method. + * + * @param[in] obj The document object which name is set in the object identifier. + * @param[in] force Force the name to be set. + * @param[in,out] subname The name of the subobject using move semantics. + * @param[in] checkImport If true, check for import. + */ void setDocumentObjectName(const App::DocumentObject* obj, bool force = false, String&& subname = String(), bool checkImport = false); + /** + * @brief Whether the object identifier has a document object name. + * + * This method checks if the object identifier has a document object name + * and optionally checks if the name was forced. + * + * @param[in] forced If true, check if the name was forced. + * @return true if the object identifier has a document object name, false + * otherwise. + */ bool hasDocumentObjectName(bool forced = false) const; + /** + * @brief Test whether the property is local. + * + * This method checks whether the property this object identifier + * represents is a local property. + * + * @return true if the property is local, false otherwise. + */ bool isLocalProperty() const { return localProperty; } + /** + * @brief Get the document object name. + * + * @return String with name of document object as resolved by the object + * identifier. + */ String getDocumentObjectName() const; + /** + * @brief Get the subobject name. + * + * @param[in] newStyle If true, use the new style of subobject name. + * @return The subobject name. + */ const std::string& getSubObjectName(bool newStyle) const; + + /** + * @brief Get the subobject name. + * + * @return The subobject name. + */ const std::string& getSubObjectName() const; + /** + * @brief A type for a map of subobject names. + * + * The map is a map with keys of a pair of document object and a + * subobject name to the subobject name for the imported object. + */ using SubNameMap = std::map, std::string>; + + /** + * @brief Import subnames from a map of subnames. + * + * Given a map of subnames from the linked subobject to the imported + * subobject, this method will update the subnames in the object + * identifier. + * + * @param[in] subNameMap The map of subnames to import. + */ void importSubNames(const SubNameMap& subNameMap); - bool updateLabelReference(App::DocumentObject*, const std::string&, const char*); + /** + * @brief Update the label reference. + * + * This method updates the label reference of the object identifier. + * + * @param[in] obj The document object that owns the label. + * @param[in] ref The old label reference. + * @param[in] newLabel The new label to set. + */ + bool updateLabelReference(const App::DocumentObject* obj, + const std::string& ref, + const char* newLabel); + /** + * @brief Relabel the document name. + * + * This method relabels the document name of the object identifier as part + * of a visit of the ExpressionVisitor. + * + * @param[in,out] v The expression visitor. + * @param[in] oldLabel The old label to relabel. + * @param[in] newLabel The new label to set. + */ bool relabeledDocument(ExpressionVisitor& v, const std::string& oldLabel, const std::string& newLabel); - /** Type for storing dependency of an ObjectIdentifier + /** + * @brief A type for storing dependencies of an ObjectIdentifier. * - * The dependency is a map from document object to a set of property names. - * An object identifier may references multiple objects using syntax like - * 'Part.Group[0].Width'. + * It is a map from document object to a set of property names. An object + * identifier may references multiple objects using syntax like + * `%Part.%Group[0].Width`. * - * Also, we use set of string instead of set of Property pointer, because - * the property may not exist at the time this ObjectIdentifier is + * Additionally, we use a set of strings instead of set of Properties, + * because the property may not exist at the time this ObjectIdentifier is * constructed. */ using Dependencies = std::map>; - /** Get dependencies of this object identifier + /** + * @brief Get the dependencies of this object identifier. * - * @param needProps: whether need property dependencies. - * @param labels: optional return of any label references. + * @param[in] needProps: Whether we need property dependencies. + * @param[out] labels: Optional return of any label references. * - * In case of multi-object references, like 'Part.Group[0].Width', if no + * In case of multi-object references, like `%Part.%Group[0].Width`, if no * property dependency is required, then this function will only return the * first referred object dependency. Or else, all object and property * dependencies will be returned. */ Dependencies getDep(bool needProps, std::vector* labels = nullptr) const; - /** Get dependencies of this object identifier + /** + * @brief Get the dependencies of this object identifier. * - * @param deps: returns the dependencies. - * @param needProps: whether need property dependencies. - * @param labels: optional return of any label references. + * @param[in,out] deps: Returns the dependencies. + * @param[in] needProps: Whether need property dependencies. + * @param[out] labels: Optional return of any label references. * - * In case of multi-object references, like 'Part.Group[0].Width', if no - * property dependency is required, then this function will only return the - * first referred object dependency. Or else, all object and property - * dependencies will be returned. + * @see ObjectIdentifier::getDep(bool,std::vector*) const */ void getDep(Dependencies& deps, bool needProps, std::vector* labels = nullptr) const; - /// Returns all label references + /** + * @brief Returns all label references in the object identifier. + * + * @param[in,out] labels The container in which the labels are returned. + */ void getDepLabels(std::vector& labels) const; + /** + * @brief Find a document with the given name. + * + * This method will search for a document with the given name. If @p name + * is not provided, the document of the object identifier is returned. If + * @p ambiguous is not `nullptr`, the method will return whether the found + * document is unique. + * + * @param[in] name The name of the document. + * @param[out] ambiguous If true, the document is not uniquely defined by name. + * + * @return The found document, or `nullptr` if it is not found or not + * uniquely defined by name. + */ App::Document* getDocument(String name = String(), bool* ambiguous = nullptr) const; + /** + * @brief Get the document object for the object identifier. + * @return The document object, or `nullptr` if not found or uniquely defined. + */ App::DocumentObject* getDocumentObject() const; + /** + * @brief Get the parts of the object identifier as a string list. + * + * The parts include the document name, the document object name, the + * subobject name, and the various components. + * + * @return The list of strings representing the various components. + */ std::vector getStringList() const; + /** + * @brief Construct the simplest possible object identifier relative to another. + * + * @param[in] other The other object identifier. + * @return A new simplified object identifier. + */ App::ObjectIdentifier relativeTo(const App::ObjectIdentifier& other) const; + /** + * @brief Replace an object in the object identifier. + * + * This method replaces an object in the object identifier with another + * object. It is used to create a new object identifier when the document + * object is replaced. + * + * @param[out] res The resulting object identifier. + * @param[in] parent The parent document object. + * @param[in] oldObj The old document object to replace. + * @param[in] newObj The new document object to replace with. + * + * @return true if the object was replaced, false otherwise. + */ bool replaceObject(ObjectIdentifier& res, const App::DocumentObject* parent, App::DocumentObject* oldObj, @@ -521,48 +1251,202 @@ public: // Operators + /** + * @brief Operator to add a component to the object identifier. + * + * @param[in] value Component object + * + * @return A reference to itself. + */ App::ObjectIdentifier& operator<<(const Component& value); + + /** + * @brief Operator to add a component to the object identifier. + * + * This method uses move semantics. + * + * @param[in,out] value Component object + * + * @return A reference to itself. + */ App::ObjectIdentifier& operator<<(Component&& value); + /** + * @brief Compare object identifiers for equality. + * + * @param[in] other The other object identifier. + * + * @return true if they are equal, false otherwise. + */ bool operator==(const ObjectIdentifier& other) const; + /** + * @brief Compare object identifiers for inequality. + * + * @param[in] other The other object identifier. + * + * @return true if they differ from each other, false otherwise. + */ bool operator!=(const ObjectIdentifier& other) const; + /** + * @brief Lexicographical less-than comparison. + * + * @param[in] other The other object identifier. + * + * @return true if this object is less than the other. + */ bool operator<(const ObjectIdentifier& other) const; // Getter + /** + * @brief Get the value of the property or field pointed to by this object + * identifier. + * + * All type of objects are supported. Some types are casted to FC native + * type, including: Int, Float, %String, Unicode %String, and Quantities. Others + * are just kept as Python object wrapped by App::any. + * + * @param[in] pathValue: if true, calls the property's getPathValue(), which is + * necessary for quantities to work. + * @param[in] isPseudoProperty: if not `nullptr`, set to true if the property is a + * pseudo property. + * + * @return The value of the property or field. + */ App::any getValue(bool pathValue = false, bool* isPseudoProperty = nullptr) const; + /** + * @brief Get the value of the property or field pointed to by this object + * identifier. + * + * @see ObjectIdentifier::getValue(). In contrast, this method + * returns a Python %object. + * + * @param[in] pathValue: if true, calls the property's getPyPathValue(), which is + * necessary for quantities to work. + * @param[in] isPseudoProperty: if not `nullptr`, set to true if the property is a + * pseudo property. + * + * @return The value of the property or field. + */ Py::Object getPyValue(bool pathValue = false, bool* isPseudoProperty = nullptr) const; // Setter: is const because it does not alter the object state, // but does have an aiding effect. + /** + * @brief Set the value of a property or field pointed to by this object identifier. + * + * This method uses Python to do the actual work and a limited set of types + * that can be in the `App::any` variable are supported: `Base::Quantity`, + * `double`, `char*`, `const char*`, `int`, `unsigned int`, `short`, `unsigned short`, + * `char`, and `unsigned char`. + * + * @param[in] value The value to set. + */ void setValue(const App::any& value) const; // Static functions + /** + * @brief Parse a string to create an object identifier. + * + * @param[in] docObj Document object that will own this object identifier. + * @param[in] str String to parse + * + * @return A new object identifier. + * @throw Base::RuntimeError if the string is invalid. + */ static ObjectIdentifier parse(const App::DocumentObject* docObj, const std::string& str); + /** + * @brief Acquire the error string after name resolution of the object identifier. + * + * @return The error string. + */ std::string resolveErrorString() const; + /** + * @brief Adjust the links of the object identifier. + * + * This method will adjust the links of the object identifier and is part + * of a visit from an expression visitor. This is typically necessary when + * a link object is moved. The @p inList is a list of dependencies of the + * object for which the visitor was started. + * + * @param[in,out] v The expression visitor. + * @param[in] inList The list of dependencies. + * + * @return true if the links were adjusted, false otherwise. + */ bool adjustLinks(ExpressionVisitor& v, const std::set& inList); + /** + * @brief Update the element reference of the object identifier. + * + * This method is part of the expression visitor and is used to update the + * element reference of object identifiers in case of a geometry element + * reference change due to geometry model changes. + * + * @see PropertyLinkBase::_updateElementReference() + * + * @param[in,out] v The expression visitor. + * @param[in,out] feature If given, then only update element references for this + * feature, otherwise update geometry element references. + * @param[in] reverse If true, use the old style before the new style. If + * false the other way around. + * + * @return true if the element reference was updated, false otherwise. + */ bool updateElementReference(ExpressionVisitor& v, App::DocumentObject* feature = nullptr, bool reverse = false); + + /// Resolve ambiguity in the object identifier. void resolveAmbiguity(); + /** + * @brief Verify the object identifier. + * + * This method will verify the object identifier against property @p prop. + * + * @param[in] prop The property to verify against. + * @param[in] silent If true, do not throw an exception. + * + * @return true if verification succeeded, false otherwise. + * @throw Base::ValueError if there is an invalid property path. + */ bool verify(const App::Property& prop, bool silent = false) const; + /** + * @brief Compute the hash of the object identifier. + * + * This method computes the hash of the object identifier. The hash is + * computed from the string representation of the object identifier. + * + * @return The hash of the object identifier. + */ std::size_t hash() const; protected: + /** + * @brief A structure to hold the results of resolving an ObjectIdentifier. + * + * This structure is used to hold the results of resolving an object + * identifier. + */ struct ResolveResults { + /** + * @brief Construct and initialize a ResolveResults object, given an ObjectIdentifier instance. + * + * The constructor will invoke the ObjectIdentifier's resolve() method + * to initialize the object's data. + */ explicit ResolveResults(const ObjectIdentifier& oi); int propertyIndex {0}; @@ -577,58 +1461,167 @@ protected: int propertyType {0}; std::bitset<32> flags; + /** + * @brief Acquire the error string after name resolution. + * + * @return The error string. + */ std::string resolveErrorString() const; + + /** + * @brief Obtain the property of the object identifier for this ResolveResults. + * + * @param[in] oi The object identifier. + */ void getProperty(const ObjectIdentifier& oi); }; + + /// Provide access to the internals of ObjectIdentifier. friend struct ResolveResults; + /** + * @brief Resolve the property of the object identifier. + * + * This method will resolve the property of the object identifier and + * return the property type. + * + * @param[in] obj The document object that owns the property. + * @param[in] propertyName The name of the property to resolve. + * @param[out] sobj The sub object. + * @param[out] ptype The type of the property. + * + * @return The property or `nullptr` if not resolved. + */ App::Property* resolveProperty(const App::DocumentObject* obj, const char* propertyName, App::DocumentObject*& sobj, int& ptype) const; + /** + * @brief Get sub field part of a property as a string. + * + * @param[in,out] ss The output stream to write to. + * @param[in] result The resolve results. + * @param[in] toPython If true, use Python quoting rules. Otherwise, use + * FreeCAD quoting rules. + */ void getSubPathStr(std::ostream& ss, const ResolveResults& result, bool toPython = false) const; + /** + * @brief Access the value of the property or field pointed to by this + * object. + * + * This method can either set or get a value of the property or field of + * the object identifier given a ResolveResults. If @p deps is not + * `nullptr`, the dependencies are updated. + * + * @param[in] rs The resolve results. + * @param[in] value The value to set. + * @param[in,out] deps The dependencies to set. + */ Py::Object access(const ResolveResults& rs, - Py::Object* value = nullptr, + const Py::Object* value = nullptr, Dependencies* deps = nullptr) const; + /** + * @brief Resolve the object identifier to a concrete document, document + * object, and property. + * + * This method is a helper method that fills out data in the given + * ResolveResults object. + * + * @param[in,out] results The ResolveResults object to fill out. + */ void resolve(ResolveResults& results) const; - void resolveAmbiguity(ResolveResults& results); - static App::DocumentObject* - getDocumentObject(const App::Document* doc, const String& name, std::bitset<32>& flags); + /** + * @brief Resolve ambiguity in the object identifier. + * + * Given a ResolveResults, the ambiguities in the object identifier are resolved. + * + * @param[in] results The result of the resolve method. + */ + void resolveAmbiguity(const ResolveResults& results); + /** + * @brief Returns all label references in the object identifier. + * + * @param[in] result The result of the resolve method. + * @param[in,out] labels The container in which the labels are returned. + */ void getDepLabels(const ResolveResults& result, std::vector& labels) const; + /// The owner of the object identifier. App::DocumentObject* owner; + /// The document name that this object identifier refers to. String documentName; + /// The document object name that this object identifier refers to. String documentObjectName; + /// The sub object name that this object identifier refers to. String subObjectName; + /** + * @brief The shadow sub-element names that this object identifier refers to. + * + * This contains both the new and old style sub-element names. + */ ElementNamePair shadowSub; + /// The components of the object identifier. std::vector components; + /// Whether a document name is forced set. bool documentNameSet; + /// Whether a document object name is forced set. bool documentObjectNameSet; + /// Whether the property is local. bool localProperty; +private: + static App::DocumentObject* + getDocumentObject(const App::Document* doc, const String& name, std::bitset<32>& flags); + private: std::string _cache; // Cached string represstation of this identifier std::size_t _hash; // Cached hash of this string }; +/** + * @brief Hash function for ObjectIdentifier. + * + * @param[in] path The object identifier to hash. + * + * @return The hash value of the object identifier. + */ inline std::size_t hash_value(const App::ObjectIdentifier& path) { return path.hash(); } -/** Helper function to convert Python object to/from App::any - * - * WARNING! Must hold Python global interpreter lock before calling these - * functions - */ //@{ +/** + * @brief Helper function to convert Python object to App::any + * + * @warning Must hold Python global interpreter lock before calling these + * functions + * + * @param[in] pyobj The Python object to convert. + * @param[in] check If true, check if the object is convertible to App::any, + * otherwise just return as is. + * + * @return The converted App::any object. + * @throw Base::ValueError if the object is not convertible to a unicode string. + */ App::any AppExport pyObjectToAny(Py::Object pyobj, bool check = true); + +/** + * @brief Helper function to convert Python object from App::any + * + * @warning Must hold Python global interpreter lock before calling these + * functions + * + * @param[in] value The App::any object to convert. + * @return The converted Python object. + * @throw Base::ExpressionError if the value has an unknown type. + */ Py::Object AppExport pyObjectFromAny(const App::any& value); //@} } // namespace App diff --git a/src/App/Property.cpp b/src/App/Property.cpp index 4bd598a99a..1764e9778c 100644 --- a/src/App/Property.cpp +++ b/src/App/Property.cpp @@ -159,9 +159,9 @@ const char* Property::getDocumentation() const return father->getPropertyDocumentation(this); } -void Property::setContainer(PropertyContainer* Father) +void Property::setContainer(PropertyContainer* father) { - father = Father; + this->father = father; } void Property::setPathValue(const ObjectIdentifier& path, const boost::any& value) diff --git a/src/App/Property.h b/src/App/Property.h index edcc977b77..02dc8b9de9 100644 --- a/src/App/Property.h +++ b/src/App/Property.h @@ -45,16 +45,17 @@ class PropertyContainer; class ObjectIdentifier; /** - * @brief %Base class of all properties + * @brief %Base class of all properties. * @ingroup PropertyFramework * - * @details This is the father of all properties. Properties are objects which that used - * in the document tree to parameterize e.g. features and their graphical output. - * They are also used to gain access from the scripting facility. - * @par - * This abstract base class defines all methods shared by all - * possible properties. It is also possible to define user properties - * and use them in the framework. + * This is the base class of all properties. Properties are objects that are + * used in documents or document objects that maintain all kinds of information + * about the document or document objects. Examples are properties of + * features, such as the length, but properties can also keep track of shapes. + * They are also used to gain access to the document object in the console. + * + * This abstract base class defines all methods shared by all possible + * properties. It is also possible to create user-defined properties. * * For a more high-level overview see topic @ref PropertyFramework "Property Framework". */ @@ -142,223 +143,449 @@ public: User4 = 31 }; + /// Construct a property. Property(); + /// Destruct a property. ~Property() override; - /// For safe deleting of a dynamic property + /** + * @brief Safely delete a dynamic property. + * + * @param[inout] p The property to delete. + */ static void destroy(Property* p); - /** This method is used to get the size of objects - * It is not meant to have the exact size, it is more or less an estimation - * which runs fast! Is it two bytes or a GB? - * This method is defined in Base::Persistence - * @see Base::Persistence - */ unsigned int getMemSize() const override { // you have to implement this method in all property classes! return sizeof(father) + sizeof(StatusBits); } - /** Get the name of this property in the belonging container + /** + * @brief Get the name of this property in the belonging container. + * * With \ref hasName() it can be checked beforehand if a valid name is set. - * @note If no name is set this function returns an empty string, i.e. "". + * + * @return The name of the property or if no name is set, an empty string. */ const char* getName() const; - /** Check if the property has a name set. + + /** + * @brief Check whether the property has a name set. + * * If no name is set then \ref getName() will return an empty string + * + * @return True if a name is set, false otherwise. */ bool hasName() const; - /** Check if the passed name is valid. - * If \a name is null or an empty string it's considered invalid, - * and valid otherwise. + + /** + * @brief Check whether the passed name is valid. + * + * If a name is null or an empty string it is considered invalid, and valid + * otherwise. + * + * @param[in] name The name to check. + * @return True if the name is valid, false otherwise. */ static bool isValidName(const char* name); + /** + * @brief Get the name of the property and its container. + * + * The container name is separated from the property name by a dot. If the + * property has no name, then a question mark is returned. If the + * container has no name, then a question mark is returned for the + * container named. + */ std::string getFullName() const; - /// Get the class name of the associated property editor item + /** + * @brief Get the class name of the associated property editor item. + * + * @return The class name of the property editor item or an empty string if + * not defined. + */ virtual const char* getEditorName() const { return ""; } - /// Get the type of the property in the container + /** + * @brief Get the type of the property in the container. + * + * The type is expressed as a bitmask of enum PropertyType. + * + * @return The type of the property as a bitmask of enum PropertyType. + */ short getType() const; - /// Get the group of this property + /** + * @brief Get the group of this property. + * + * @return The group of the property or a nullptr if not defined. + */ const char* getGroup() const; - /// Get the documentation of this property + /** + * @brief Get the documentation of this property. + * + * @return The documentation of the property or a nullptr if not defined. + */ const char* getDocumentation() const; - /// Is called by the framework to set the father (container) - void setContainer(PropertyContainer* Father); + /** + * @brief Set the container of this property. + * + * This is called by the framework to set the father (container). + * + * @param[in] father The container of this property. + */ + void setContainer(PropertyContainer* father); - /// Get a pointer to the PropertyContainer derived class the property belongs to + /** + * @brief Get the container of this property. + * + * Get a pointer to the PropertyContainer derived class to which the + * property belongs. + * + * @return A pointer to the PropertyContainer derived class. + */ PropertyContainer* getContainer() const { return father; } - /// Set value of property + /** + * @brief Set the value of the property identified by the path. + * + * This function sets the value of the property identified by the path. It + * is meant to be overridden for subclasses in which the `path` is + * typically ignored. The default implementation redirects setting a value + * to the the `path` ObjectIdentifier. + * + * @param[in] path The path to the property. + * @param[in] value The value to set. + */ virtual void setPathValue(const App::ObjectIdentifier& path, const boost::any& value); - /// Get value of property + /** + * @brief Get the value of the property identified by the path. + * + * This function gets the value of the property identified by the path. It + * is meant to be overridden for subclasses in which the `path` is + * typically ignored. The default implementation makes use of the `path` + * ObjectIdentifier to get the value of the property. + * + * @param[in] path The path to the property. + * @return The value of the property. + */ virtual const boost::any getPathValue(const App::ObjectIdentifier& path) const; - /// Get Python value of property - virtual bool getPyPathValue(const App::ObjectIdentifier&, Py::Object&) const + /** + * @brief Get the Python value of the property identified by the path. + * + * This function gets the Python value of the property identified by the + * path. It is meant to be overridden for subclasses. This default + * implementation return `false`. + * + * @param[in] path The path to the property. + * @param[out] value The Python value of the property. + * @return True if the value was successfully retrieved, false otherwise. + */ + virtual bool getPyPathValue([[maybe_unused]] const App::ObjectIdentifier& path, + [[maybe_unused]] Py::Object& value) const { return false; } - /// Convert p to a canonical representation of it - virtual App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier& p) const; + /** + * @brief Convert an object identifier to a canonical representation. + * + * Convert an object identifier to a canonical representation of the object + * identifier. + * + * @param[in] path The object identifier to convert. + * @return An object identifier that represents the canonical path. + */ + virtual App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier& path) const; - /// Get valid paths for this property; used by auto completer + /** + * @brief Get valid paths for this property. + * + * This function is used by auto completer. + * + * @param[out] paths A vector of object identifiers with the valid paths + * for this property. + */ virtual void getPaths(std::vector& paths) const; - /** Called at the beginning of Document::afterRestore() + /** @brief Callback for after document restore. * - * This function is called without dependency sorting, because some - * types of link property can only reconstructs the linking information - * inside this function. + * This function is called at the beginning of Document::afterRestore(). + * It is called without dependency sorting, because some link property + * types can only reconstruct the linking information inside this function. + * Typical use cases include: * - * One example use case of this function is PropertyLinkSub that uses - * afterRestore() to parse and restore subname references, which may - * contain sub-object reference from external document, and there will be - * special mapping required during object import. + * - **PropertyLinkSub** + * Parses and restores sub-object references (including + * those that point into external documents), applying any necessary + * name-mapping during import. * - * Another example is PropertyExpressionEngine which only parse the - * restored expression in afterRestore(). The reason, in addition to - * subname mapping like PropertyLinkSub, is that it can handle document - * name adjustment as well. It internally relies on PropertyXLink to store - * the external document path for external linking. When the external - * document is restored, its internal name may change due to name conflict - * with existing documents. PropertyExpressionEngine can now auto adjust - * external references without any problem. + * - **PropertyExpressionEngine** + * Re-parses expressions after restore so that it can handle document + * name adjustment. It internally relies on PropertyXLink to store the + * external document path for external linking. When the external + * document is restored, its internal name may change due to name + * conflict with existing documents. With this callback it can now auto + * adjust external references without any problem. */ - virtual void afterRestore() - {} + virtual void afterRestore() {} - /** Called before calling DocumentObject::onDocumentRestored() + /** @brief Callback for after document restore. * - * This function is called after finished calling Property::afterRestore() - * of all properties of objects. By then, the object dependency information - * is assumed ready. So, unlike Property::afterRestore(), this function is - * called on objects with dependency order. + * This function is called by Document::restore() after finished calling + * Property::afterRestore() on all properties of objects. By then, the + * object dependency information is assumed ready. So, unlike + * Property::afterRestore(), this function is called on objects with + * dependency order. + * + * It is called before calling DocumentObject::onDocumentRestored(). */ - virtual void onContainerRestored() - {} + virtual void onContainerRestored() {} - /** Property status handling + /** @name Property status handling + * @{ */ - //@{ - /// Set the property touched + + /// Set the property touched. void touch(); - /// Test if this property is touched + + /** + * @brief Test if this property is touched. + * + * @return True if the property is touched, false otherwise. + */ inline bool isTouched() const { return StatusBits.test(Touched); } - /// Reset this property touched + + /// Reset this property as being touched. inline void purgeTouched() { StatusBits.reset(Touched); } - /// return the status bits + + /** + * @brief Get the status of this property. + * + * @return The status of the property as a bitmask of enum Status. + */ inline unsigned long getStatus() const { return StatusBits.to_ulong(); } + + /** + * @brief Test if the property has a specific status. + * + * @param[in] pos The status to test. + * @return True if the property has the specified status, false otherwise. + */ inline bool testStatus(Status pos) const { return StatusBits.test(static_cast(pos)); } + + /** + * @brief Set the status of the property. + * + * Sets the status of the property given a specific position. + * + * @param[in] pos The status to set. + * @param[in] on The value to set the status to. + */ void setStatus(Status pos, bool on); + + /** + * @brief Set the status of the property. + * + * Sets the status of the property given a specific bitmask. + * + * @param[in] status The status to set as a bitmask. + */ void setStatusValue(unsigned long status); - /// Sets property editable/grayed out in property editor + + /** + * @brief Set the property read only. + * + * This sets property editable/grayed out in property editor. + * @param[in] readOnly True to set the property as read-only, false otherwise. + */ void setReadOnly(bool readOnly); + + /** + * @brief Check if the property is read-only. + * + * @return True if the property is read-only, false otherwise. + */ inline bool isReadOnly() const { return testStatus(App::Property::ReadOnly); } - /// Sets precision of properties using floating point - /// numbers to single, the default is double. + + /** + * @brief Set the precision of floating point properties. + * + * This sets the precision of properties using floating point + * numbers to single precision. The default is double precision. + * + * @param[in] single True to set single precision, false for double precision. + */ void setSinglePrecision(bool single) { setStatus(App::Property::Single, single); } - /// Gets precision of properties using floating point numbers + + /** + * @brief Gets precision of floating point properties. + * + * @return True if single precision is set, false for double precision. + */ inline bool isSinglePrecision() const { return testStatus(App::Property::Single); } - //@} + /// @} - /// Returns a new copy of the property (mainly for Undo/Redo and transactions) + /** + * @brief Returns a new copy of the property. + * + * The copy is mainly used for Undo/Redo and transactions. + * + * @return A new copy of the property. + */ virtual Property* Copy() const = 0; - /// Paste the value from the property (mainly for Undo/Redo and transactions) + + /** + * @brief Pastes the value from a property. + * + * This function pastes the value from a property into this property. It + * is mainly used for Undo/Redo and transactions. + * + * @param[in] from The property to paste from. + */ virtual void Paste(const Property& from) = 0; - /// Called when a child property has changed value - virtual void hasSetChildValue(Property&) - {} - /// Called before a child property changing value - virtual void aboutToSetChildValue(Property&) - {} + /** + * @brief Callback for when a child property has changed value. + * + * @param[in] prop The child property that has changed value. + */ + virtual void hasSetChildValue([[maybe_unused]] Property& prop) {} - /// Compare if this property has the same content as the given one + /** + * @brief Callback for when a child property is about to change value. + * + * It is called before a child property changes value. + * + *@param[in] prop The child property that is about to change value. + */ + virtual void aboutToSetChildValue([[maybe_unused]] Property& prop) {} + + /** + * @brief Compare if this property has the same content as the given one. + * + * @param[in] other The property to compare with. + * @return True if the properties are the same, false otherwise. + */ virtual bool isSame(const Property& other) const; - /** Return a unique ID for the property + /** + * @brief Return a unique ID for the property. * * The ID of a property is generated from a monotonically increasing - * internal counter. The intention of the ID is to be used as a key for - * mapping, instead of using the raw pointer. Because, it is possible for - * the runtime memory allocator to reuse just deleted memory, which will - * cause hard to debug problem if use pointer as key. + * internal counter. The intention of the ID is to be used as a key for + * mapping, instead of using the raw pointer. This prevent the runtime + * allocator to reuse just deleted memory as a result of using raw + * pointers, something that is challenging to debug. */ int64_t getID() const { return _id; } - virtual void beforeSave() const - {} + /** + * @brief Callback for when the property is about to be saved. + * + * This method is called before saving the property. It can be overridden + * by subclasses to implement custom behavior before saving. + * + * @see PropertyContainer::beforeSave() + */ + virtual void beforeSave() const {} friend class PropertyContainer; friend struct PropertyData; friend class DynamicProperty; protected: - /** Status bits of the property + /** @brief %Status bits of the property. + * * The first 8 bits are used for the base system the rest can be used in * descendent classes to mark special statuses on the objects. * The bits and their meaning are listed below: - * 0 - object is marked as 'touched' - * 1 - object is marked as 'immutable' - * 2 - object is marked as 'read-only' (for property editor) - * 3 - object is marked as 'hidden' (for property editor) + * - **0**: object is marked as 'touched' + * - **1**: object is marked as 'immutable' + * - **2**: object is marked as 'read-only' (for property editor) + * - **3**: object is marked as 'hidden' (for property editor) + * + * @see Property::Status that defines the position of the status bits. */ std::bitset<32> StatusBits; protected: - /// Gets called by all setValue() methods after the value has changed + + /** + * @brief Callback for when the value of the property has changed. + * + * This is called by all setValue() methods after the value has changed. + */ virtual void hasSetValue(); - /// Gets called by all setValue() methods before the value has changed + + /** + * @brief Callback for when the value of the property is about to change. + * + * This is called by all setValue() methods before the value has changed. + */ virtual void aboutToSetValue(); - /// Verify a path for the current property - virtual void verifyPath(const App::ObjectIdentifier& p) const; + /** + * @brief Verify a path for the current property. + * + * @param[in] path The path to verify. + */ + virtual void verifyPath(const App::ObjectIdentifier& path) const; - /// Return a file name suitable for saving this property - std::string getFileName(const char* postfix = 0, const char* prefix = 0) const; + /** + * @brief Return a file name suitable for saving this property. + * + * @param[in] postfix The postfix to append to the file name. + * @param[in] prefix The prefix to prepend to the file name. + * @return The file name for saving the property. + */ + std::string getFileName(const char* postfix = nullptr, const char* prefix = nullptr) const; public: - // forbidden + /** + * @brief The copy constructor is deleted to prevent copying. + */ Property(const Property&) = delete; + + /** + * @brief The assignment operator is deleted to prevent assignment. + */ Property& operator=(const Property&) = delete; private: @@ -371,37 +598,42 @@ private: int64_t _id; public: + /// Signal emitted when the property value has changed. boost::signals2::signal signalChanged; }; -/** A template class that is used to inhibit multiple nested calls to aboutToSetValue/hasSetValue - * for properties. +/** + * @brief A template class to inhibit nested calls for setting values. * * A template class that is used to inhibit multiple nested calls to * aboutToSetValue/hasSetValue for properties, and only invoke it on change and - * last time it is needed. This is useful in cases where you want to change multiple - * values in a property "atomically", using possibly multiple primitive functions - * that normally would trigger aboutToSetValue/hasSetValue calls on their own. + * on the last time it is needed. This is useful in cases where you want to + * change multiple values in a property "atomically", using possibly multiple + * primitive functions that normally would trigger aboutToSetValue/hasSetValue + * calls on their own. * - * To use, inherit privately from the AtomicPropertyChangeInterface class, using - * your class name as the template argument. In all cases where you normally would - * call aboutToSetValue/hasSetValue before and after a change, create an - * AtomicPropertyChange object. The default constructor assume you are about to - * change the property and will call property's aboutToSetValue() if the - * property has not been marked as changed before by any other - * AtomicPropertyChange instances in current call stack. You can pass 'false' - * as the a second argument to the constructor, and manually call - * AtomicPropertyChange::aboutToChange() before actual change, this enables you - * to prevent unnecessary property copy for undo/redo where there is actual - * changes. AtomicPropertyChange will guaranetee calling hasSetValue() when the - * last instance in the current call stack is destroyed. + * To use, inherit privately from the AtomicPropertyChangeInterface class, + * using your class name as the template argument. In all cases in which you + * would normally call aboutToSetValue/hasSetValue before and after a change, + * create an AtomicPropertyChange object. + * + * The default constructor assumes you are about to change the property and + * will call property's Property::aboutToSetValue() if the property has not + * been marked as changed before by any other AtomicPropertyChange instances in + * current call stack. You can pass `false` as the a second argument to the + * constructor, and manually call AtomicPropertyChange::aboutToChange() before + * actual change, which enables you to prevent unnecessary property copy for + * undo/redo when there are actual changes. AtomicPropertyChange will + * guarantee calling Property::hasSetValue() when the last instance in the + * current call stack is destroyed. * * One thing to take note is that, because C++ does not allow throwing * exception in destructor, any exception thrown when calling property's - * hasSetValue() will be caught and swallowed. To allow exception propagation, - * you can manually call AtomicPropertyChange::tryInvoke(). If the condition is - * satisfied, it will call hasSetValue() that allows exception propagation. + * Property::hasSetValue() will be caught and swallowed. To allow exception + * propagation, you can manually call AtomicPropertyChange::tryInvoke(). If the + * condition is satisfied, it will call Property::hasSetValue() that allows + * exception propagation. */ template class AtomicPropertyChangeInterface @@ -410,10 +642,24 @@ protected: AtomicPropertyChangeInterface() = default; public: + /** + * @brief A class that captures property changes atomically. + * + * This class is used to capture multiple property changes atomically. It + * automatically marks the property as changed and calls the + * Property::aboutToSetValue() method when the object is constructed. It + * also automatically calls the Property::hasSetValue() method when the + * object is destructed, if the property has been marked as changed. This + * ensures that Property::aboutToSetValue() and Property::hasSetValue() are + * only called once for multiple property changes. + * + * @see AtomicPropertyChangeInterface + */ class AtomicPropertyChange { public: - /** Constructor + /** + * @brief Construct an AtomicPropertyChange object. * * @param prop: the property * @param markChange: If true, marks the property as changed if it @@ -429,7 +675,8 @@ public: } } - /** Mark the property as changed + /** + * @brief Mark the property as changed * * It will mark the property as changed only if it has been marked * before, and only then will it call the property's aboutToSetValue(). @@ -442,7 +689,8 @@ public: } } - /** Destructor + /** + * @brief Destruct an AtomicPropertyChange object. * * If the property is marked as changed, and this is the last instance * of the class in current call stack, it will call property's @@ -460,7 +708,7 @@ public: mProp.hasSetValue(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { } @@ -471,7 +719,8 @@ public: } } - /** Check and invoke property's hasSetValue() + /** + * @brief Check and invoke property's hasSetValue(). * * Check if this is the last instance and the property has been marked * as changed. If so, invoke property's hasSetValue(). @@ -494,34 +743,67 @@ public: }; protected: - int signalCounter {0}; /**< Counter for invoking transaction start/stop */ + /// Counter for invoking transaction start/stop. + int signalCounter {0}; + /// Flag to indicate if the property has been changed. bool hasChanged {false}; }; -/** Helper class to construct list like properties +/** + * @brief Base class for list-like properties. * * This class is not derived from Property so that we can have more that one - * base class for list like properties, e.g. see PropertyList, and - * PropertyLinkListBase + * base class for list-like properties. + * + * @see PropertyList + * @see PropertyLinkListBase */ class AppExport PropertyListsBase { public: + + /** + * @brief Set the size of the property list. + * + *@param newSize The new size of the property list. + */ virtual void setSize(int newSize) = 0; + + /** + * @brief Get the size of the property list. + * + * @return The size of the property list. + */ virtual int getSize() const = 0; + /** + * @brief Get the list of touched elements. + * + * @return A set of touched elements. + */ const std::set& getTouchList() const { return _touchList; } + /// Clear the list of touched elements. void clearTouchList() { _touchList.clear(); } protected: + /** + * @brief Set the values of the property list with Python values. + * + * This method is used to set the values of the property list with values + * represented as Python objects. If `indices` is empty, all values are + * set. + * + * @param[in] vals The new values for the property list as Python values. + * @param[in] indices The indices of the values to set. + */ virtual void setPyValues(const std::vector& vals, const std::vector& indices) { (void)vals; @@ -529,70 +811,154 @@ protected: throw Base::NotImplementedError("not implemented"); } - void _setPyObject(PyObject*); + /** + * @brief Set the values of the property list with a Python object. + * + * The Python object is expected to be a dictionary or something that looks + * like a sequence of values, for example a list or tuple, or an iterable. + * + * @param[in] pyObj The Python object to set the values from. + */ + void _setPyObject(PyObject* pyObj); protected: + /// The list of touched elements. std::set _touchList; }; -/** Base class of all property lists. - * The PropertyLists class is the base class for properties which can contain - * multiple values, not only a single value. - * All property types which may contain more than one value inherits this class. +/** + * @brief The base class of all property lists. + * + * The PropertyLists class is the base class for properties that can contain + * multiple values, not only a single value. All property types that may + * contain more than one value inherit from this class. */ class AppExport PropertyLists: public Property, public PropertyListsBase - { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: + /** + * @brief Set the values of the property list with a Python object. + * + * The Python object is expected to be a dictionary or something that looks + * like a sequence of values, for example a list or tuple, or an iterable. + * + * @param[in] obj The Python object to set the values from. + */ void setPyObject(PyObject* obj) override { _setPyObject(obj); } - // if the order of the elements in the list relevant? - // if yes, certain operations, like restoring must make sure that the - // order is kept despite errors. + /** + * @brief Set the order of the elements to be relevant. + * + * If the order of the elements in the list is relevant, certain + * operations, such as restoring, must ensure that the order is kept + * despite potential errors. + * + * @param[in] on True to set the order as relevant, false otherwise. + */ inline void setOrderRelevant(bool on) { this->setStatus(Status::Ordered, on); } + + /** + * @brief Check if the order of the elements is relevant. + * + * @return True if the order is relevant, false otherwise. + */ inline bool isOrderRelevant() const { return this->testStatus(Status::Ordered); } }; -/** Helper class to implement PropertyLists */ +/** + * @brief Helper class to implement PropertyLists. + * + * This class combines property storage (via a standard container ListT) with + * the change-notification interface in AtomicPropertyChangeInterface. + * + * @tparam T The type of individual property values. + * @tparam ListT The container type for holding values (defaults to @c std::vector). + * @tparam ParentT The base class providing core property-list behavior + * (defaults to PropertyLists). + */ template, class ParentT = PropertyLists> class PropertyListsT: public ParentT, public AtomicPropertyChangeInterface> { public: + /// Alias for a reference to a const element in the list. using const_reference = typename ListT::const_reference; + + /// The underlying container type. using list_type = ListT; + + /// The base class type. using parent_type = ParentT; + + /** + * @brief Helper type for performing atomic property changes. + * + * This is defined by the AtomicPropertyChangeInterface class. + */ using atomic_change = typename AtomicPropertyChangeInterface< PropertyListsT>::AtomicPropertyChange; + /** + * @brief Grant atomic_change access to private internals. + * + * Allows atomic_change operations to modify the internal state directly. + */ friend atomic_change; + /** + * @brief Resize the property list, filling new slots with a given value. + * + * @param[in] newSize The desired total number of elements. + * @param[in] def The single element value to use for all newly-added slots. + */ virtual void setSize(int newSize, const_reference def) { _lValueList.resize(newSize, def); } + /** + * @brief Resize the property list, value-initializing any new elements. + * + * Adjusts the container to hold exactly @p newSize elements. + * - If @p newSize is less than the current size, the container is shrunk. + * - If @p newSize is greater, new elements are default-constructed + * + * @param[in] newSize The desired total number of elements. + */ void setSize(int newSize) override { _lValueList.resize(newSize); } + /** + * @brief Get the size of the list. + * + * @return The size of the list. + */ int getSize() const override { return static_cast(_lValueList.size()); } + /** + * @brief Set a property list to a given value. + * + * Clears any existing values and makes the list contain exactly one + * element initialized to @p value. + * + * @param[in] value The value to assign. + */ void setValue(const_reference value) { ListT vals; @@ -600,6 +966,14 @@ public: setValues(vals); } + /** + * @brief Replace the entire list of values. + * + * Clears and assigns @p newValues to the internal list, notifying + * observers of the change atomically. + * + * @param[in] newValues The new container of values (defaults to empty list). + */ virtual void setValues(const ListT& newValues = ListT()) { atomic_change guard(*this); @@ -608,27 +982,55 @@ public: guard.tryInvoke(); } + /** + * @brief Alias for setValues(). + * + * @param[in] newValues The new container of values (defaults to empty list). + */ void setValue(const ListT& newValues = ListT()) { setValues(newValues); } + /** + * @brief Retrieve the underlying list of values. + * + * @return A const reference to the internal container. + */ const ListT& getValues() const { return _lValueList; } - // alias to getValues + /** + * @brief Alias for getValues(). + * + * @return A const reference to the internal container. + */ const ListT& getValue() const { return getValues(); } + /** + * @brief Retrieve an element by index. + * + * @param[in] idx The index of the element to retrieve. + * @return The element at position @p idx. + * + * @note No bounds-check is performed. + */ const_reference operator[](int idx) const { return _lValueList[idx]; } + /** + * @brief Compare two Property instances for equivalence. + * + * @param[in] other The other Property to compare against. + * @return True if both are of the same type and contain equal values. + */ bool isSame(const Property& other) const override { if (&other == this) { @@ -638,6 +1040,14 @@ public: && this->getValue() == static_cast(&other)->getValue(); } + /** + * @brief Set the property value from a Python object. + * + * Attempts to extract a value via getPyValue() and assign it; + * on failure, falls back to the ParentT implementation. + * + * @param[in] value A PyObject pointer representing the new value. + */ void setPyObject(PyObject* value) override { try { @@ -649,6 +1059,17 @@ public: parent_type::setPyObject(value); } + /** + * @brief Set a value at a specific index, growing the list if needed. + * + * If @p index is -1 or equal to the current size, the list grows by one. + * Otherwise, the existing element at @p index is replaced. + * Observers are notified of the change atomically. + * + * @param[in] index The position at which to set @p value (-1 for append). + * @param[in] value The new element value. + * @throw Base::RuntimeError if @p index is out of bounds (< -1 or > size). + */ virtual void set1Value(int index, const_reference value) { int size = getSize(); @@ -690,6 +1111,13 @@ protected: guard.tryInvoke(); } + /** + * @brief Convert a Python object to a value of type T. + * + * @param[in] item The Python object to convert. + * + * @return The converted value of type T. + */ virtual T getPyValue(PyObject* item) const = 0; protected: diff --git a/src/App/PropertyContainer.cpp b/src/App/PropertyContainer.cpp index c61c42f400..0171148efc 100644 --- a/src/App/PropertyContainer.cpp +++ b/src/App/PropertyContainer.cpp @@ -290,17 +290,17 @@ void PropertyContainer::Save (Base::Writer &writer) const it.second->Save(writer); } catch (const Base::Exception &e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const std::exception &e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const char* e) { - Base::Console().Error("%s\n", e); + Base::Console().error("%s\n", e); } #ifndef FC_DEBUG catch (...) { - Base::Console().Error("PropertyContainer::Save: Unknown C++ exception thrown. Try to continue...\n"); + Base::Console().error("PropertyContainer::Save: Unknown C++ exception thrown. Try to continue...\n"); } #endif writer.decInd(); // indentation for the actual property @@ -373,7 +373,7 @@ void PropertyContainer::Restore(Base::XMLReader &reader) } if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInProperty)) { - Base::Console().Error("Property %s of type %s was subject to a partial restore.\n",PropName.c_str(),TypeName.c_str()); + Base::Console().error("Property %s of type %s was subject to a partial restore.\n",PropName.c_str(),TypeName.c_str()); reader.clearPartialRestoreProperty(); } } @@ -383,20 +383,20 @@ void PropertyContainer::Restore(Base::XMLReader &reader) catch (const Base::RestoreError &) { reader.setPartialRestore(true); reader.clearPartialRestoreProperty(); - Base::Console().Error("Property %s of type %s was subject to a partial restore.\n",PropName.c_str(),TypeName.c_str()); + Base::Console().error("Property %s of type %s was subject to a partial restore.\n",PropName.c_str(),TypeName.c_str()); } catch (const Base::Exception &e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const std::exception &e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (const char* e) { - Base::Console().Error("%s\n", e); + Base::Console().error("%s\n", e); } #ifndef FC_DEBUG catch (...) { - Base::Console().Error("PropertyContainer::Restore: Unknown C++ exception thrown\n"); + Base::Console().error("PropertyContainer::Restore: Unknown C++ exception thrown\n"); } #endif reader.readEndElement("Property"); diff --git a/src/App/PropertyExpressionEngine.cpp b/src/App/PropertyExpressionEngine.cpp index 0667061b58..9f4a9dd56b 100644 --- a/src/App/PropertyExpressionEngine.cpp +++ b/src/App/PropertyExpressionEngine.cpp @@ -246,7 +246,7 @@ void PropertyExpressionEngine::updateHiddenReference(const std::string& key) } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to evaluate property binding " << myProp->getFullName() << " on change of " << key); } @@ -406,7 +406,7 @@ void PropertyExpressionEngine::buildGraphStructures( * @return New ObjectIdentifier */ -ObjectIdentifier PropertyExpressionEngine::canonicalPath(const ObjectIdentifier& p) const +ObjectIdentifier PropertyExpressionEngine::canonicalPath(const ObjectIdentifier& oid) const { DocumentObject* docObj = freecad_cast(getContainer()); @@ -416,24 +416,24 @@ ObjectIdentifier PropertyExpressionEngine::canonicalPath(const ObjectIdentifier& } int ptype; - Property* prop = p.getProperty(&ptype); + Property* prop = oid.getProperty(&ptype); - // p pointing to a property...? + // oid pointing to a property...? if (!prop) { - throw Base::RuntimeError(p.resolveErrorString().c_str()); + throw Base::RuntimeError(oid.resolveErrorString().c_str()); } if (ptype || prop->getContainer() != getContainer()) { - return p; + return oid; } // In case someone calls this with p pointing to a PropertyExpressionEngine for some reason if (prop->isDerivedFrom(PropertyExpressionEngine::classTypeId)) { - return p; + return oid; } // Dispatch call to actual canonicalPath implementation - return p.canonicalPath(); + return oid.canonicalPath(); } /** @@ -873,7 +873,7 @@ PropertyExpressionEngine::validateExpression(const ObjectIdentifier& path, auto inList = pathDocObj->getInListEx(true); for (auto& v : expr->getDepObjects()) { auto docObj = v.first; - if (!v.second && inList.count(docObj)) { + if (!v.second && inList.contains(docObj)) { std::stringstream ss; ss << "cyclic reference to " << docObj->getFullName(); return ss.str(); @@ -1008,7 +1008,7 @@ bool PropertyExpressionEngine::adjustLink(const std::set& inLis } bool found = false; for (auto& v : _Deps) { - if (inList.count(v.first)) { + if (inList.contains(v.first)) { found = true; break; } diff --git a/src/App/PropertyFile.cpp b/src/App/PropertyFile.cpp index 1652cb4652..0392c4db9f 100644 --- a/src/App/PropertyFile.cpp +++ b/src/App/PropertyFile.cpp @@ -509,7 +509,7 @@ Property* PropertyFileIncluded::Copy() const } // remember the new name for the Undo - Base::Console().Log("Copy '%s' to '%s'\n", _cValue.c_str(), newName.filePath().c_str()); + Base::Console().log("Copy '%s' to '%s'\n", _cValue.c_str(), newName.filePath().c_str()); prop->_cValue = newName.filePath().c_str(); // make backup files writable to avoid copying them again on undo/redo diff --git a/src/App/PropertyLinks.cpp b/src/App/PropertyLinks.cpp index 6c536ec398..128c07a274 100644 --- a/src/App/PropertyLinks.cpp +++ b/src/App/PropertyLinks.cpp @@ -189,7 +189,7 @@ void PropertyLinkBase::checkLabelReferences(const std::vector& subs std::string PropertyLinkBase::updateLabelReference(const App::DocumentObject* parent, const char* subname, - App::DocumentObject* obj, + const App::DocumentObject* obj, const std::string& ref, const char* newLabel) { @@ -288,7 +288,7 @@ void PropertyLinkBase::updateElementReferences(DocumentObject* feature, bool rev prop->updateElementReference(feature, reverse, true); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to update element reference of " << propertyName(prop)); } catch (std::exception& e) { @@ -788,14 +788,14 @@ void PropertyLink::Restore(Base::XMLReader& reader) DocumentObject* object = document ? document->getObject(name.c_str()) : nullptr; if (!object) { if (reader.isVerbose()) { - Base::Console().Warning("Lost link to '%s' while loading, maybe " + Base::Console().warning("Lost link to '%s' while loading, maybe " "an object was not loaded correctly\n", name.c_str()); } } else if (parent == object) { if (reader.isVerbose()) { - Base::Console().Warning("Object '%s' links to itself, nullify it\n", name.c_str()); + Base::Console().warning("Object '%s' links to itself, nullify it\n", name.c_str()); } object = nullptr; } @@ -2107,7 +2107,7 @@ adjustLinkSubs(App::PropertyLinkBase* prop, break; } if (!newLink) { - if (inList.count(sobj)) { + if (inList.contains(sobj)) { continue; } newLink = sobj; @@ -2138,7 +2138,7 @@ bool PropertyLinkSub::adjustLink(const std::set& inList) if (_pcScope == LinkScope::Hidden) { return false; } - if (!_pcLinkSub || !_pcLinkSub->isAttachedToDocument() || !inList.count(_pcLinkSub)) { + if (!_pcLinkSub || !_pcLinkSub->isAttachedToDocument() || !inList.contains(_pcLinkSub)) { return false; } auto subs = _cSubList; @@ -2878,7 +2878,7 @@ void PropertyLinkSubList::Restore(Base::XMLReader& reader) } } else if (reader.isVerbose()) { - Base::Console().Warning("Lost link to '%s' while loading, maybe " + Base::Console().warning("Lost link to '%s' while loading, maybe " "an object was not loaded correctly\n", name.c_str()); } @@ -3229,7 +3229,7 @@ bool PropertyLinkSubList::adjustLink(const std::set& inLis for (std::string& sub : subs) { ++idx; auto& link = links[idx]; - if (!link || !link->isAttachedToDocument() || !inList.count(link)) { + if (!link || !link->isAttachedToDocument() || !inList.contains(link)) { continue; } touched = true; @@ -3240,7 +3240,7 @@ bool PropertyLinkSubList::adjustLink(const std::set& inLis pos = std::string::npos; break; } - if (!inList.count(sobj)) { + if (!inList.contains(sobj)) { link = sobj; sub = sub.substr(pos + 1); break; @@ -4657,7 +4657,7 @@ bool PropertyXLink::adjustLink(const std::set& inList) if (_pcScope == LinkScope::Hidden) { return false; } - if (!_pcLink || !_pcLink->isAttachedToDocument() || !inList.count(_pcLink)) { + if (!_pcLink || !_pcLink->isAttachedToDocument() || !inList.contains(_pcLink)) { return false; } auto subs = _SubList; @@ -5479,7 +5479,7 @@ bool PropertyXLinkSubList::adjustLink(const std::set& inLi ++count; continue; } - if (inList.count(obj) && adjustLinkSubs(this, inList, obj, l._SubList, &values)) { + if (inList.contains(obj) && adjustLinkSubs(this, inList, obj, l._SubList, &values)) { touched = true; } } @@ -5849,7 +5849,7 @@ void PropertyXLinkContainer::_onBreakLink(DocumentObject* obj) onBreakLink(obj); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Exception on breaking link property " << getFullName()); } catch (std::exception& e) { diff --git a/src/App/PropertyLinks.h b/src/App/PropertyLinks.h index edf2d6b098..587f0d22dd 100644 --- a/src/App/PropertyLinks.h +++ b/src/App/PropertyLinks.h @@ -583,7 +583,7 @@ public: */ static std::string updateLabelReference(const App::DocumentObject* linked, const char* subname, - App::DocumentObject* obj, + const App::DocumentObject* obj, const std::string& ref, const char* newLabel); //@} diff --git a/src/App/PropertyPythonObject.cpp b/src/App/PropertyPythonObject.cpp index 935abd69fd..144903f93b 100644 --- a/src/App/PropertyPythonObject.cpp +++ b/src/App/PropertyPythonObject.cpp @@ -51,7 +51,7 @@ PropertyPythonObject::~PropertyPythonObject() try { this->object = Py::Object(); } catch (Py::TypeError &) { - Base::Console().Warning("Py::TypeError Exception caught while destroying PropertyPythonObject\n"); + Base::Console().warning("Py::TypeError Exception caught while destroying PropertyPythonObject\n"); } } @@ -122,10 +122,10 @@ std::string PropertyPythonObject::toString() const } catch (Py::Exception&) { Py::String typestr(this->object.type().str()); - Base::Console().Error("PropertyPythonObject::toString(): failed for %s\n", + Base::Console().error("PropertyPythonObject::toString(): failed for %s\n", typestr.as_string().c_str()); Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return repr; @@ -175,7 +175,7 @@ void PropertyPythonObject::fromString(const std::string& repr) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -201,7 +201,7 @@ void PropertyPythonObject::loadPickle(const std::string& str) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -293,10 +293,10 @@ void PropertyPythonObject::restoreObject(Base::XMLReader& reader) e.clear(); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (...) { - Base::Console().Error("Critical error in PropertyPythonObject::restoreObject\n"); + Base::Console().error("Critical error in PropertyPythonObject::restoreObject\n"); } } @@ -324,7 +324,7 @@ void PropertyPythonObject::Save(Base::Writer& writer) const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } saveObject(writer); @@ -394,7 +394,7 @@ void PropertyPythonObject::Restore(Base::XMLReader& reader) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); this->object = Py::None(); load_failed = true; } @@ -407,7 +407,7 @@ void PropertyPythonObject::Restore(Base::XMLReader& reader) this->loadPickle(buffer); } else if (!load_failed) { - Base::Console().Warning( + Base::Console().warning( "PropertyPythonObject::Restore: unsupported serialisation: %s\n", buffer.c_str()); } diff --git a/src/App/PropertyStandard.cpp b/src/App/PropertyStandard.cpp index 32a0f2e7d4..d14bf0bd06 100644 --- a/src/App/PropertyStandard.cpp +++ b/src/App/PropertyStandard.cpp @@ -442,7 +442,7 @@ void PropertyEnumeration::Restore(Base::XMLReader& reader) if (val < 0) { // If the enum is empty at this stage do not print a warning if (_enum.hasEnums()) { - Base::Console().DeveloperWarning(std::string("PropertyEnumeration"), + Base::Console().developerWarning(std::string("PropertyEnumeration"), "Enumeration index %d is out of range, ignore it\n", val); } @@ -518,7 +518,7 @@ void PropertyEnumeration::setPyObject(PyObject* value) } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } } diff --git a/src/App/StringHasher.cpp b/src/App/StringHasher.cpp index 3e2a211841..dbe6c064cb 100644 --- a/src/App/StringHasher.cpp +++ b/src/App/StringHasher.cpp @@ -813,7 +813,7 @@ void StringHasher::Restore(Base::XMLReader& reader) restoreStreamNew(reader.beginCharStream(), count); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to restore string table: full-document recompute strongly recommended."); } reader.readEndElement("StringHasher2"); diff --git a/src/App/Transactions.cpp b/src/App/Transactions.cpp index 988e2d20e7..af83c79d9b 100644 --- a/src/App/Transactions.cpp +++ b/src/App/Transactions.cpp @@ -141,7 +141,11 @@ bool Transaction::isEmpty() const bool Transaction::hasObject(const TransactionalObject* Obj) const { +#if BOOST_VERSION < 107500 return !!_Objects.get<1>().count(Obj); +#else + return !!_Objects.get<1>().contains(Obj); +#endif } void Transaction::addOrRemoveProperty(TransactionalObject* Obj, const Property* pcProp, bool add) @@ -183,7 +187,7 @@ void Transaction::apply(Document& Doc, bool forward) } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); errMsg = e.what(); } catch (std::exception& e) { @@ -364,7 +368,7 @@ void TransactionObject::applyChn(Document& /*Doc*/, TransactionalObject* pcObj, prop->Paste(*data.property); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("exception while restoring " << prop->getFullName() << ": " << e.what()); } catch (std::exception& e) { diff --git a/src/Base/BaseClass.h b/src/Base/BaseClass.h index 4f6fdffb7d..8e5e18accf 100644 --- a/src/Base/BaseClass.h +++ b/src/Base/BaseClass.h @@ -102,7 +102,7 @@ private: Base::Type _class_::classTypeId = Base::Type::BadType; \ void* _class_::create(void) \ { \ - return 0; \ + return nullptr; \ } diff --git a/src/Base/Builder3D.cpp b/src/Base/Builder3D.cpp index e356faf093..2ab928cc1c 100644 --- a/src/Base/Builder3D.cpp +++ b/src/Base/Builder3D.cpp @@ -1002,7 +1002,7 @@ void Builder3D::clear() } /** - * Save the resulting inventor 3D representation to the Console().Log() facility. + * Save the resulting inventor 3D representation to the Console().log() facility. * In DEBUG mode the Gui (if running) will trigger on that and show the representation in * the active Viewer/Document. It shows only one representation on time. If you need to * show more then one representation use saveToFile() instead. @@ -1010,9 +1010,9 @@ void Builder3D::clear() */ void Builder3D::saveToLog() { - ILogger* obs = Base::Console().Get("StatusBar"); + ILogger* obs = Base::Console().get("StatusBar"); if (obs) { - obs->SendLog("Builder3D", + obs->sendLog("Builder3D", result.str(), Base::LogStyle::Log, Base::IntendedRecipient::Developer, diff --git a/src/Base/CMakeLists.txt b/src/Base/CMakeLists.txt index b21250c43c..607772a213 100644 --- a/src/Base/CMakeLists.txt +++ b/src/Base/CMakeLists.txt @@ -150,20 +150,10 @@ SET(FreeCADBase_UNITAPI_SRCS UnitsApi.h UnitsSchema.h UnitsSchema.cpp - UnitsSchemaInternal.h - UnitsSchemaInternal.cpp - UnitsSchemaMKS.h - UnitsSchemaMKS.cpp - UnitsSchemaImperial1.h - UnitsSchemaImperial1.cpp - UnitsSchemaCentimeters.h - UnitsSchemaCentimeters.cpp - UnitsSchemaMmMin.h - UnitsSchemaMmMin.cpp - UnitsSchemaFemMilliMeterNewton.h - UnitsSchemaFemMilliMeterNewton.cpp - UnitsSchemaMeterDecimal.h - UnitsSchemaMeterDecimal.cpp + UnitsSchemas.cpp + UnitsSchemas.h + UnitsSchemasData.h + UnitsSchemasSpecs.h Quantity.h Quantity.cpp QuantityPyImp.cpp diff --git a/src/Base/Console.cpp b/src/Base/Console.cpp index 2ae3f1deb5..b8cfd89561 100644 --- a/src/Base/Console.cpp +++ b/src/Base/Console.cpp @@ -55,12 +55,12 @@ public: std::string notifier; std::string msg; - ConsoleEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, - IntendedRecipient recipient, - ContentType content, + ConsoleEvent(const ConsoleSingleton::FreeCAD_ConsoleMsgType type, + const IntendedRecipient recipient, + const ContentType content, const std::string& notifier, const std::string& msg) - : QEvent(QEvent::User) + : QEvent(QEvent::User) // NOLINT , msgtype(type) , recipient(recipient) , content(content) @@ -88,8 +88,7 @@ public: void customEvent(QEvent* ev) override { if (ev->type() == QEvent::User) { - ConsoleEvent* ce = static_cast(ev); - switch (ce->msgtype) { + switch (const auto ce = static_cast(ev); ce->msgtype) { case ConsoleSingleton::MsgType_Txt: Console().notifyPrivate(LogStyle::Message, ce->recipient, @@ -159,7 +158,7 @@ ConsoleSingleton::ConsoleSingleton() ConsoleSingleton::~ConsoleSingleton() { ConsoleOutput::destruct(); - for (ILogger* Iter : _aclObservers) { + for (ILogger* Iter : _aclObservers) { // NOLINT delete Iter; } } @@ -186,10 +185,11 @@ ConsoleSingleton::~ConsoleSingleton() * switches off warnings and error messages and restore the state before the modification. * If the observer \a sObs doesn't exist then nothing happens. */ -ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on) +ConsoleMsgFlags ConsoleSingleton::setEnabledMsgType(const char* sObs, + const ConsoleMsgFlags type, + const bool on) const { - ILogger* pObs = Get(sObs); - if (pObs) { + if (ILogger* pObs = get(sObs)) { ConsoleMsgFlags flags = 0; if (type & MsgType_Err) { @@ -235,10 +235,9 @@ ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsg return 0; } -bool ConsoleSingleton::IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const +bool ConsoleSingleton::isMsgTypeEnabled(const char* sObs, const FreeCAD_ConsoleMsgType type) const { - ILogger* pObs = Get(sObs); - if (pObs) { + if (const ILogger* pObs = get(sObs)) { switch (type) { case MsgType_Txt: return pObs->bMsg; @@ -260,7 +259,7 @@ bool ConsoleSingleton::IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType return false; } -void ConsoleSingleton::SetConnectionMode(ConnectionMode mode) +void ConsoleSingleton::setConnectionMode(const ConnectionMode mode) { connectionMode = mode; @@ -279,10 +278,10 @@ void ConsoleSingleton::SetConnectionMode(ConnectionMode mode) * be forwarded to it. * @see ILogger */ -void ConsoleSingleton::AttachObserver(ILogger* pcObserver) +void ConsoleSingleton::attachObserver(ILogger* pcObserver) { // double insert !! - assert(_aclObservers.find(pcObserver) == _aclObservers.end()); + assert(!_aclObservers.contains(pcObserver)); _aclObservers.insert(pcObserver); } @@ -292,20 +291,20 @@ void ConsoleSingleton::AttachObserver(ILogger* pcObserver) * After detaching you can destruct the Observer or reinsert it later. * @see ILogger */ -void ConsoleSingleton::DetachObserver(ILogger* pcObserver) +void ConsoleSingleton::detachObserver(ILogger* pcObserver) { _aclObservers.erase(pcObserver); } -void Base::ConsoleSingleton::notifyPrivate(LogStyle category, - IntendedRecipient recipient, - ContentType content, - const std::string& notifiername, - const std::string& msg) +void ConsoleSingleton::notifyPrivate(const LogStyle category, + const IntendedRecipient recipient, + const ContentType content, + const std::string& notifiername, + const std::string& msg) const { for (ILogger* Iter : _aclObservers) { if (Iter->isActive(category)) { - Iter->SendLog(notifiername, + Iter->sendLog(notifiername, msg, category, recipient, @@ -314,9 +313,9 @@ void Base::ConsoleSingleton::notifyPrivate(LogStyle category, } } -void ConsoleSingleton::postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, - IntendedRecipient recipient, - ContentType content, +void ConsoleSingleton::postEvent(const FreeCAD_ConsoleMsgType type, + const IntendedRecipient recipient, + const ContentType content, const std::string& notifiername, const std::string& msg) { @@ -324,11 +323,11 @@ void ConsoleSingleton::postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, new ConsoleEvent(type, recipient, content, notifiername, msg)); } -ILogger* ConsoleSingleton::Get(const char* Name) const +ILogger* ConsoleSingleton::get(const char* Name) const { const char* OName {}; for (ILogger* Iter : _aclObservers) { - OName = Iter->Name(); // get the name + OName = Iter->name(); // get the name if (OName && strcmp(OName, Name) == 0) { return Iter; } @@ -336,12 +335,12 @@ ILogger* ConsoleSingleton::Get(const char* Name) const return nullptr; } -int* ConsoleSingleton::GetLogLevel(const char* tag, bool create) +int* ConsoleSingleton::getLogLevel(const char* tag, const bool create) { if (!tag) { tag = ""; } - if (_logLevels.find(tag) != _logLevels.end()) { + if (_logLevels.contains(tag)) { return &_logLevels[tag]; } if (!create) { @@ -352,14 +351,14 @@ int* ConsoleSingleton::GetLogLevel(const char* tag, bool create) return &ret; } -void ConsoleSingleton::Refresh() +void ConsoleSingleton::refresh() const { if (_bCanRefresh) { qApp->processEvents(QEventLoop::ExcludeUserInputEvents); } } -void ConsoleSingleton::EnableRefresh(bool enable) +void ConsoleSingleton::enableRefresh(const bool enable) { _bCanRefresh = enable; } @@ -377,7 +376,7 @@ void ConsoleSingleton::Destruct() _pcSingleton = nullptr; } -ConsoleSingleton& ConsoleSingleton::Instance() +ConsoleSingleton& ConsoleSingleton::instance() { // not initialized? if (!_pcSingleton) { @@ -392,85 +391,85 @@ ConsoleSingleton& ConsoleSingleton::Instance() // ConsoleSingleton Methods structure PyMethodDef ConsoleSingleton::Methods[] = { {"PrintMessage", - ConsoleSingleton::sPyMessage, + sPyMessage, METH_VARARGS, "PrintMessage(obj) -> None\n\n" "Print a message to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintLog", - ConsoleSingleton::sPyLog, + sPyLog, METH_VARARGS, "PrintLog(obj) -> None\n\n" "Print a log message to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintError", - ConsoleSingleton::sPyError, + sPyError, METH_VARARGS, "PrintError(obj) -> None\n\n" "Print an error message to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintDeveloperError", - ConsoleSingleton::sPyDeveloperError, + sPyDeveloperError, METH_VARARGS, "PrintDeveloperError(obj) -> None\n\n" "Print an error message intended only for Developers to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintUserError", - ConsoleSingleton::sPyUserError, + sPyUserError, METH_VARARGS, "PrintUserError(obj) -> None\n\n" "Print an error message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintTranslatedUserError", - ConsoleSingleton::sPyTranslatedUserError, + sPyTranslatedUserError, METH_VARARGS, "PrintTranslatedUserError(obj) -> None\n\n" "Print an already translated error message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintWarning", - ConsoleSingleton::sPyWarning, + sPyWarning, METH_VARARGS, "PrintWarning(obj) -> None\n\n" "Print a warning message to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintDeveloperWarning", - ConsoleSingleton::sPyDeveloperWarning, + sPyDeveloperWarning, METH_VARARGS, "PrintDeveloperWarning(obj) -> None\n\n" "Print an warning message intended only for Developers to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintUserWarning", - ConsoleSingleton::sPyUserWarning, + sPyUserWarning, METH_VARARGS, "PrintUserWarning(obj) -> None\n\n" "Print a warning message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintTranslatedUserWarning", - ConsoleSingleton::sPyTranslatedUserWarning, + sPyTranslatedUserWarning, METH_VARARGS, "PrintTranslatedUserWarning(obj) -> None\n\n" "Print an already translated warning message intended only for the User to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintCritical", - ConsoleSingleton::sPyCritical, + sPyCritical, METH_VARARGS, "PrintCritical(obj) -> None\n\n" "Print a critical message to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintNotification", - ConsoleSingleton::sPyNotification, + sPyNotification, METH_VARARGS, "PrintNotification(obj) -> None\n\n" "Print a user notification to the output.\n\n" "obj : object\n The string representation is printed."}, {"PrintTranslatedNotification", - ConsoleSingleton::sPyTranslatedNotification, + sPyTranslatedNotification, METH_VARARGS, "PrintTranslatedNotification(obj) -> None\n\n" "Print an already translated notification to the output.\n\n" "obj : object\n The string representation is printed."}, {"SetStatus", - ConsoleSingleton::sPySetStatus, + sPySetStatus, METH_VARARGS, "SetStatus(observer, type, status) -> None\n\n" "Set the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n\n" @@ -478,7 +477,7 @@ PyMethodDef ConsoleSingleton::Methods[] = { "type : str\n Message type.\n" "status : bool"}, {"GetStatus", - ConsoleSingleton::sPyGetStatus, + sPyGetStatus, METH_VARARGS, "GetStatus(observer, type) -> bool or None\n\n" "Get the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n" @@ -486,7 +485,7 @@ PyMethodDef ConsoleSingleton::Methods[] = { "observer : str\n Logging interface name.\n" "type : str\n Message type."}, {"GetObservers", - ConsoleSingleton::sPyGetObservers, + sPyGetObservers, METH_VARARGS, "GetObservers() -> list of str\n\n" "Get the names of the current logging interfaces."}, @@ -500,7 +499,7 @@ PyObject* FC_PYCONSOLE_MSG(std::function func, P PyObject* output {}; PyObject* notifier {}; - const char* notifierStr = ""; + auto notifierStr = ""; auto retrieveString = [](PyObject* pystr) { PyObject* unicode = nullptr; @@ -539,9 +538,8 @@ PyObject* FC_PYCONSOLE_MSG(std::function func, P PY_TRY { - const char* string = retrieveString(output); - if (string) { + if (const char* string = retrieveString(output)) { func(notifierStr, string); /*process message*/ } } @@ -554,10 +552,11 @@ PyObject* ConsoleSingleton::sPyMessage(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -566,7 +565,7 @@ PyObject* ConsoleSingleton::sPyWarning(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance().Warning(notifier, "%s", msg); + instance().warning(notifier, "%s", msg); }, args); } @@ -575,10 +574,11 @@ PyObject* ConsoleSingleton::sPyDeveloperWarning(PyObject* /*self*/, PyObject* ar { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -587,10 +587,10 @@ PyObject* ConsoleSingleton::sPyUserWarning(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -599,10 +599,10 @@ PyObject* ConsoleSingleton::sPyTranslatedUserWarning(PyObject* /*self*/, PyObjec { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -611,10 +611,10 @@ PyObject* ConsoleSingleton::sPyError(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -623,10 +623,11 @@ PyObject* ConsoleSingleton::sPyDeveloperError(PyObject* /*self*/, PyObject* args { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -635,10 +636,10 @@ PyObject* ConsoleSingleton::sPyUserError(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -647,10 +648,10 @@ PyObject* ConsoleSingleton::sPyTranslatedUserError(PyObject* /*self*/, PyObject* { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -659,10 +660,11 @@ PyObject* ConsoleSingleton::sPyLog(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -671,10 +673,10 @@ PyObject* ConsoleSingleton::sPyCritical(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance().send( + notifier, + "%s", + msg); }, args); } @@ -683,10 +685,11 @@ PyObject* ConsoleSingleton::sPyNotification(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -695,10 +698,11 @@ PyObject* ConsoleSingleton::sPyTranslatedNotification(PyObject* /*self*/, PyObje { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - Instance() - .Send(notifier, "%s", msg); + instance() + .send( + notifier, + "%s", + msg); }, args); } @@ -714,7 +718,7 @@ PyObject* ConsoleSingleton::sPyGetStatus(PyObject* /*self*/, PyObject* args) PY_TRY { bool b = false; - ILogger* pObs = Instance().Get(pstr1); + const ILogger* pObs = instance().get(pstr1); if (!pObs) { Py_Return; } @@ -759,9 +763,8 @@ PyObject* ConsoleSingleton::sPySetStatus(PyObject* /*self*/, PyObject* args) PY_TRY { - bool status = asBoolean(pyStatus); - ILogger* pObs = Instance().Get(pstr1); - if (pObs) { + const bool status = asBoolean(pyStatus); + if (ILogger* pObs = instance().get(pstr1)) { if (strcmp(pstr2, "Log") == 0) { pObs->bLog = status; } @@ -803,13 +806,13 @@ PyObject* ConsoleSingleton::sPyGetObservers(PyObject* /*self*/, PyObject* args) PY_TRY { Py::List list; - for (auto i : Instance()._aclObservers) { - list.append(Py::String(i->Name() ? i->Name() : "")); + for (const auto i : instance()._aclObservers) { + list.append(Py::String(i->name() ? i->name() : "")); } - return Py::new_reference_to(list); + return new_reference_to(list); } PY_CATCH } -Base::ILogger::~ILogger() = default; +ILogger::~ILogger() = default; diff --git a/src/Base/Console.h b/src/Base/Console.h index 09352cf1b8..619f6b3d6a 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -368,29 +368,29 @@ using PyMethodDef = struct PyMethodDef; _str << '\n'; \ Base::Console()._func(_notifier, _str.str().c_str()); \ if (_instance.refresh) \ - Base::Console().Refresh(); \ + Base::Console().refresh(); \ } \ } while (0) #define _FC_PRINT(_instance, _l, _func, _msg) \ __FC_PRINT(_instance, _l, _func, std::string(), _msg, __FILE__, __LINE__) -#define FC_MSG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, Message, _msg) -#define FC_WARN(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, DeveloperWarning, _msg) -#define FC_ERR(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, DeveloperError, _msg) -#define FC_LOG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, Log, _msg) -#define FC_TRACE(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, Log, _msg) +#define FC_MSG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, message, _msg) +#define FC_WARN(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, developerWarning, _msg) +#define FC_ERR(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, developerError, _msg) +#define FC_LOG(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, log, _msg) +#define FC_TRACE(_msg) _FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, log, _msg) #define _FC_MSG(_file, _line, _msg) \ - __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, Message, std::string(), _msg, _file, _line) + __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_MSG, message, std::string(), _msg, _file, _line) #define _FC_WARN(_file, _line, _msg) \ - __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, DeveloperWarning, std::string(), _msg, _file, _line) + __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_WARN, developerWarning, std::string(), _msg, _file, _line) #define _FC_ERR(_file, _line, _msg) \ - __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, DeveloperError, std::string(), _msg, _file, _line) + __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_ERR, developerError, std::string(), _msg, _file, _line) #define _FC_LOG(_file, _line, _msg) \ - __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, Log, std::string(), _msg, _file, _line) + __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_LOG, log, std::string(), _msg, _file, _line) #define _FC_TRACE(_file, _line, _msg) \ - __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, Log, std::string(), _msg, _file, _line) + __FC_PRINT(FC_LOG_INSTANCE, FC_LOGLEVEL_TRACE, log, std::string(), _msg, _file, _line) #define FC_XYZ(_pt) '(' << (_pt).X() << ", " << (_pt).Y() << ", " << (_pt).Z() << ')' #define FC_xy(_pt) '(' << (_pt).x << ", " << (_pt).y << ')' @@ -485,7 +485,6 @@ using PyMethodDef = struct PyMethodDef; // clang-format on // NOLINTEND(bugprone-reserved-identifier,bugprone-macro-parentheses,cppcoreguidelines-macro-usage,cppcoreguidelines-avoid-do-while) -// TODO: Get rid of this typedef using ConsoleMsgFlags = unsigned int; namespace Base @@ -494,8 +493,8 @@ namespace Base #ifndef FC_LOG_NO_TIMING inline FC_DURATION GetDuration(FC_TIME_POINT& tp) { - auto tnow = std::chrono::FC_TIME_CLOCK::now(); - auto dc = std::chrono::duration_cast(tnow - tp); + const auto tnow = std::chrono::FC_TIME_CLOCK::now(); + const auto dc = std::chrono::duration_cast(tnow - tp); tp = tnow; return dc; } @@ -571,7 +570,7 @@ public: * translated (are untranslatable). Or conversely, may decide not to process already translated * notifications. It is up to the intended behaviour of the observer. */ - virtual void SendLog(const std::string& notifiername, + virtual void sendLog(const std::string& notifiername, const std::string& msg, LogStyle level, IntendedRecipient recipient, @@ -580,27 +579,27 @@ public: /** * Returns whether a LogStyle category is active or not */ - bool isActive(Base::LogStyle category) const + bool isActive(const LogStyle category) const { switch (category) { - case Base::LogStyle::Log: + case LogStyle::Log: return bLog; - case Base::LogStyle::Warning: + case LogStyle::Warning: return bWrn; - case Base::LogStyle::Error: + case LogStyle::Error: return bErr; - case Base::LogStyle::Message: + case LogStyle::Message: return bMsg; - case Base::LogStyle::Critical: + case LogStyle::Critical: return bCritical; - case Base::LogStyle::Notification: + case LogStyle::Notification: return bNotification; } return false; } - virtual const char* Name() + virtual const char* name() { return nullptr; } @@ -623,7 +622,7 @@ public: * instance of the class from every where in c++ by simply using: * \code * #include - * Base::Console().Log("Stage: %d",i); + * Base::Console().log("Stage: %d",i); * \endcode * \par * ConsoleSingleton is able to switch between several modes to, e.g. switch @@ -655,10 +654,10 @@ public: * \endcode * * These convenience functions cover most common cases: - * - Unqualified convenience functions, such as Error() and Warning(), produce messages intended to + * - Unqualified convenience functions, such as error() and warning(), produce messages intended to * both User and Developer with an untranslated message. * - Functions qualified with Developer, such as DeveloperError are intended for a Developer and - * are untranslatable. Functions qualified with User, such as UserError are intended only for the + * are untranslatable. Functions qualified with User, such as userError are intended only for the * User and a untranslated (leaving the responsibility to the observer to find the translation). * - Functions qualified with Translated, such as TranslatedError, are intended for the User and * the message is already translated. @@ -681,7 +680,7 @@ public: * * Example: * \code - * Base::Console().UserError(this->getFullName(), QT_TRANSLATE_NOOP("Notifications", + * Base::Console().userError(this->getFullName(), QT_TRANSLATE_NOOP("Notifications", * "Impossible to migrate Parabolas!!\n")); * \endcode * @@ -689,7 +688,7 @@ public: * often the case in legacy UI code, where localized strings are already available. For these * cases the solution is to indicate the translated status. For example: * \code - * Base::Console().TranslatedUserError( + * Base::Console().translatedUserError( * this->getFullName(), * QObject::tr("The selected edge already has a Block constraint!")); * \endcode @@ -712,86 +711,83 @@ public: Notification can be direct or via queue. */ - template - inline void Send(const std::string& notifiername, const char* pMsg, Args&&... args); + void send(const std::string& notifiername, const char* pMsg, Args&&... args); /// Prints a Message template - inline void Message(const char* pMsg, Args&&... args); + void message(const char* pMsg, Args&&... args); /// Prints a warning Message template - inline void Warning(const char* pMsg, Args&&... args); + void warning(const char* pMsg, Args&&... args); /// Prints a error Message template - inline void Error(const char* pMsg, Args&&... args); + void error(const char* pMsg, Args&&... args); /// Prints a log Message template - inline void Log(const char* pMsg, Args&&... args); + void log(const char* pMsg, Args&&... args); /// Prints a Critical Message template - inline void Critical(const char* pMsg, Args&&... args); + void critical(const char* pMsg, Args&&... args); /// Sends a User Notification template - inline void UserNotification(const char* pMsg, Args&&... args); + void userNotification(const char* pMsg, Args&&... args); /// Sends an already translated User Notification template - inline void UserTranslatedNotification(const char* pMsg, Args&&... args); + void userTranslatedNotification(const char* pMsg, Args&&... args); /// Prints a Message with source indication template - inline void Message(const std::string& notifier, const char* pMsg, Args&&... args); + void message(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a warning Message with source indication template - inline void Warning(const std::string& notifier, const char* pMsg, Args&&... args); + void warning(const std::string& notifier, const char* pMsg, Args&&... args); template - inline void DeveloperWarning(const std::string& notifier, const char* pMsg, Args&&... args); + void developerWarning(const std::string& notifier, const char* pMsg, Args&&... args); template - inline void UserWarning(const std::string& notifier, const char* pMsg, Args&&... args); + void userWarning(const std::string& notifier, const char* pMsg, Args&&... args); template - inline void - TranslatedUserWarning(const std::string& notifier, const char* pMsg, Args&&... args); + void translatedUserWarning(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a error Message with source indication template - inline void Error(const std::string& notifier, const char* pMsg, Args&&... args); + void error(const std::string& notifier, const char* pMsg, Args&&... args); template - inline void DeveloperError(const std::string& notifier, const char* pMsg, Args&&... args); + void developerError(const std::string& notifier, const char* pMsg, Args&&... args); template /// A noexcept DeveloperError for use in destructors. When compiled in debug, terminates via an /// assert. In release, the exception is silently caught and dropped. - inline void - DestructorError(const std::string& notifier, const char* pMsg, Args&&... args) noexcept; + void destructorError(const std::string& notifier, const char* pMsg, Args&&... args) noexcept; template - inline void UserError(const std::string& notifier, const char* pMsg, Args&&... args); + void userError(const std::string& notifier, const char* pMsg, Args&&... args); template - inline void TranslatedUserError(const std::string& notifier, const char* pMsg, Args&&... args); + void translatedUserError(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a log Message with source indication template - inline void Log(const std::string& notifier, const char* pMsg, Args&&... args); + void log(const std::string& notifier, const char* pMsg, Args&&... args); /// Prints a Critical Message with source indication template - inline void Critical(const std::string& notifier, const char* pMsg, Args&&... args); + void critical(const std::string& notifier, const char* pMsg, Args&&... args); /// Sends a User Notification with source indication template - inline void UserNotification(const std::string& notifier, const char* pMsg, Args&&... args); + void userNotification(const std::string& notifier, const char* pMsg, Args&&... args); /// Sends an already translated User Notification with source indication template - inline void - UserTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args); + void userTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args); // Notify a message directly to observers - template - inline void Notify(const std::string& notifiername, const std::string& msg); + template + void notify(const std::string& notifiername, const std::string& msg); /// Attaches an Observer to FCConsole - void AttachObserver(ILogger* pcObserver); + void attachObserver(ILogger* pcObserver); /// Detaches an Observer from FCConsole - void DetachObserver(ILogger* pcObserver); + void detachObserver(ILogger* pcObserver); /// enumeration for the console modes enum ConsoleMode @@ -815,35 +811,35 @@ public: }; /// Enables or disables message types of a certain console observer - ConsoleMsgFlags SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on); + ConsoleMsgFlags setEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on) const; /// Checks if message types of a certain console observer are enabled - bool IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const; - void SetConnectionMode(ConnectionMode mode); + bool isMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const; + void setConnectionMode(ConnectionMode mode); - int* GetLogLevel(const char* tag, bool create = true); + int* getLogLevel(const char* tag, bool create = true); - void SetDefaultLogLevel(int level) + void setDefaultLogLevel(const int level) { _defaultLogLevel = level; } - inline int LogLevel(int level) const + int logLevel(const int level) const { return level < 0 ? _defaultLogLevel : level; } /// singleton - static ConsoleSingleton& Instance(); + static ConsoleSingleton& instance(); // retrieval of an observer by name - ILogger* Get(const char* Name) const; + ILogger* get(const char* Name) const; static PyMethodDef Methods[]; - void Refresh(); - void EnableRefresh(bool enable); + void refresh() const; + void enableRefresh(bool enable); - inline constexpr FreeCAD_ConsoleMsgType getConsoleMsg(Base::LogStyle style); + constexpr FreeCAD_ConsoleMsgType getConsoleMsg(LogStyle style); private: // python exports goes here +++++++++++++++++++++++++++++++++++++++++++ @@ -879,7 +875,7 @@ public: ConsoleSingleton& operator=(ConsoleSingleton&&) = delete; private: - void postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, + void postEvent(FreeCAD_ConsoleMsgType type, IntendedRecipient recipient, ContentType content, const std::string& notifiername, @@ -888,7 +884,7 @@ private: IntendedRecipient recipient, ContentType content, const std::string& notifiername, - const std::string& msg); + const std::string& msg) const; // singleton static void Destruct(); @@ -909,19 +905,18 @@ private: */ inline ConsoleSingleton& Console() { - return ConsoleSingleton::Instance(); + return ConsoleSingleton::instance(); } -inline constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType -ConsoleSingleton::getConsoleMsg(Base::LogStyle style) +constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType ConsoleSingleton::getConsoleMsg(LogStyle style) { - constexpr std::array msgTypes {// In order of Base::LogStyle - FreeCAD_ConsoleMsgType::MsgType_Wrn, - FreeCAD_ConsoleMsgType::MsgType_Txt, - FreeCAD_ConsoleMsgType::MsgType_Err, - FreeCAD_ConsoleMsgType::MsgType_Log, - FreeCAD_ConsoleMsgType::MsgType_Critical, - FreeCAD_ConsoleMsgType::MsgType_Notification}; + constexpr std::array msgTypes {// In order of LogStyle + MsgType_Wrn, + MsgType_Txt, + MsgType_Err, + MsgType_Log, + MsgType_Critical, + MsgType_Notification}; return msgTypes.at(static_cast(style)); } @@ -931,12 +926,12 @@ class BaseExport ConsoleRefreshDisabler public: ConsoleRefreshDisabler() { - Console().EnableRefresh(false); + Console().enableRefresh(false); } ~ConsoleRefreshDisabler() { - Console().EnableRefresh(true); + Console().enableRefresh(true); } ConsoleRefreshDisabler(const ConsoleRefreshDisabler&) = delete; @@ -959,13 +954,13 @@ public: bool refresh; LogLevel(const char* tag, - bool print_tag = true, - int print_src = 0, - bool print_time = false, - bool add_eol = true, - bool refresh = false) + const bool print_tag = true, + const int print_src = 0, + const bool print_time = false, + const bool add_eol = true, + const bool refresh = false) : tag(tag) - , lvl(*Console().GetLogLevel(tag)) + , lvl(*Console().getLogLevel(tag)) , print_tag(print_tag) , print_src(print_src) , print_time(print_time) @@ -973,14 +968,14 @@ public: , refresh(refresh) {} - bool isEnabled(int lev) const + bool isEnabled(const int lev) const { return lev <= level(); } int level() const { - return Console().LogLevel(lvl); + return Console().logLevel(lvl); } std::stringstream& prefix(std::stringstream& str, const char* src, int line); @@ -1005,94 +1000,95 @@ public: * @see UserTranslatedNotification */ template -inline void Base::ConsoleSingleton::Message(const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::message(const char* pMsg, Args&&... args) { - Message(std::string(""), pMsg, std::forward(args)...); + message(std::string(""), pMsg, std::forward(args)...); } template -inline void -Base::ConsoleSingleton::Message(const std::string& notifier, const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::message(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + send(notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::Warning(const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::warning(const char* pMsg, Args&&... args) { - Warning(std::string(""), pMsg, std::forward(args)...); + warning(std::string(""), pMsg, std::forward(args)...); } template -inline void -Base::ConsoleSingleton::Warning(const std::string& notifier, const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::warning(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + send(notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::DeveloperWarning(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::developerWarning(const std::string& notifier, + const char* pMsg, + Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); -} - -template -inline void -Base::ConsoleSingleton::UserWarning(const std::string& notifier, const char* pMsg, Args&&... args) -{ - Send( + send( notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::TranslatedUserWarning(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::userWarning(const std::string& notifier, + const char* pMsg, + Args&&... args) { - Send( + send( notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::Error(const char* pMsg, Args&&... args) -{ - Error(std::string(""), pMsg, std::forward(args)...); -} - -template -inline void -Base::ConsoleSingleton::Error(const std::string& notifier, const char* pMsg, Args&&... args) -{ - Send(notifier, pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::DeveloperError(const std::string& notifier, +void Base::ConsoleSingleton::translatedUserWarning(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); + send( + notifier, + pMsg, + std::forward(args)...); } template -inline void Base::ConsoleSingleton::DestructorError(const std::string& notifier, - const char* pMsg, - Args&&... args) noexcept +void Base::ConsoleSingleton::error(const char* pMsg, Args&&... args) +{ + error(std::string(""), pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::error(const std::string& notifier, const char* pMsg, Args&&... args) +{ + send(notifier, pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::developerError(const std::string& notifier, + const char* pMsg, + Args&&... args) +{ + send( + notifier, + pMsg, + std::forward(args)...); +} + +template +void Base::ConsoleSingleton::destructorError(const std::string& notifier, + const char* pMsg, + Args&&... args) noexcept { try { - Send(notifier, pMsg, std::forward(args)...); + send( + notifier, + pMsg, + std::forward(args)...); } catch (...) { assert("An exception was thrown while attempting console output in a destructor" && false); @@ -1100,90 +1096,90 @@ inline void Base::ConsoleSingleton::DestructorError(const std::string& notifier, } template -inline void -Base::ConsoleSingleton::UserError(const std::string& notifier, const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::userError(const std::string& notifier, + const char* pMsg, + Args&&... args) { - Send( + send( notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::TranslatedUserError(const std::string& notifier, +void Base::ConsoleSingleton::translatedUserError(const std::string& notifier, + const char* pMsg, + Args&&... args) +{ + send( + notifier, + pMsg, + std::forward(args)...); +} + +template +void Base::ConsoleSingleton::critical(const char* pMsg, Args&&... args) +{ + critical(std::string(""), pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::critical(const std::string& notifier, const char* pMsg, Args&&... args) +{ + send(notifier, pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::userNotification(const char* pMsg, Args&&... args) +{ + userNotification(std::string(""), pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::userNotification(const std::string& notifier, + const char* pMsg, + Args&&... args) +{ + send( + notifier, + pMsg, + std::forward(args)...); +} + +template +void Base::ConsoleSingleton::userTranslatedNotification(const char* pMsg, Args&&... args) +{ + userTranslatedNotification(std::string(""), pMsg, std::forward(args)...); +} + +template +void Base::ConsoleSingleton::userTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args) { - Send( + send( notifier, pMsg, std::forward(args)...); } template -inline void Base::ConsoleSingleton::Critical(const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::log(const char* pMsg, Args&&... args) { - Critical(std::string(""), pMsg, std::forward(args)...); + log(std::string(""), pMsg, std::forward(args)...); } template -inline void -Base::ConsoleSingleton::Critical(const std::string& notifier, const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::log(const std::string& notifier, const char* pMsg, Args&&... args) { - Send(notifier, pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::UserNotification(const char* pMsg, Args&&... args) -{ - UserNotification(std::string(""), pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::UserNotification(const std::string& notifier, - const char* pMsg, - Args&&... args) -{ - Send(notifier, pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::UserTranslatedNotification(const char* pMsg, Args&&... args) -{ - UserTranslatedNotification(std::string(""), pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::UserTranslatedNotification(const std::string& notifier, - const char* pMsg, - Args&&... args) -{ - Send(notifier, pMsg, std::forward(args)...); -} - -template -inline void Base::ConsoleSingleton::Log(const char* pMsg, Args&&... args) -{ - Log(std::string(""), pMsg, std::forward(args)...); -} - -template -inline void -Base::ConsoleSingleton::Log(const std::string& notifier, const char* pMsg, Args&&... args) -{ - Send(notifier, pMsg, std::forward(args)...); + send(notifier, pMsg, std::forward(args)...); } template -inline void -Base::ConsoleSingleton::Send(const std::string& notifiername, const char* pMsg, Args&&... args) +void Base::ConsoleSingleton::send(const std::string& notifiername, const char* pMsg, Args&&... args) { std::string format; try { @@ -1198,11 +1194,11 @@ Base::ConsoleSingleton::Send(const std::string& notifiername, const char* pMsg, } if (connectionMode == Direct) { - Notify(notifiername, format); + notify(notifiername, format); } else { - auto type = getConsoleMsg(category); + const auto type = getConsoleMsg(category); postEvent(type, recipient, contenttype, notifiername, format); } @@ -1211,7 +1207,7 @@ Base::ConsoleSingleton::Send(const std::string& notifiername, const char* pMsg, template -inline void Base::ConsoleSingleton::Notify(const std::string& notifiername, const std::string& msg) +void Base::ConsoleSingleton::notify(const std::string& notifiername, const std::string& msg) { notifyPrivate(category, recipient, contenttype, notifiername, msg); } diff --git a/src/Base/ConsoleObserver.cpp b/src/Base/ConsoleObserver.cpp index 8b862991ba..4b50fc70fb 100644 --- a/src/Base/ConsoleObserver.cpp +++ b/src/Base/ConsoleObserver.cpp @@ -48,7 +48,7 @@ ConsoleObserverFile::ConsoleObserverFile(const char* sFileName) : cFileStream(Base::FileInfo(sFileName)) // can be in UTF8 { if (!cFileStream.is_open()) { - Console().Warning("Cannot open log file '%s'.\n", sFileName); + Console().warning("Cannot open log file '%s'.\n", sFileName); } // mark the file as a UTF-8 encoded file unsigned char bom[3] = {0xef, 0xbb, 0xbf}; @@ -60,7 +60,7 @@ ConsoleObserverFile::~ConsoleObserverFile() cFileStream.close(); } -void ConsoleObserverFile::SendLog(const std::string& notifiername, +void ConsoleObserverFile::sendLog(const std::string& notifiername, const std::string& msg, LogStyle level, IntendedRecipient recipient, @@ -113,7 +113,7 @@ ConsoleObserverStd::ConsoleObserverStd() ConsoleObserverStd::~ConsoleObserverStd() = default; -void ConsoleObserverStd::SendLog(const std::string& notifiername, +void ConsoleObserverStd::sendLog(const std::string& notifiername, const std::string& msg, LogStyle level, IntendedRecipient recipient, @@ -261,7 +261,7 @@ int RedirectStdOutput::sync() { // Print as log as this might be verbose if (!buffer.empty() && buffer.back() == '\n') { - Base::Console().Log("%s", buffer.c_str()); + Base::Console().log("%s", buffer.c_str()); buffer.clear(); } return 0; @@ -284,7 +284,7 @@ int RedirectStdLog::sync() { // Print as log as this might be verbose if (!buffer.empty() && buffer.back() == '\n') { - Base::Console().Log("%s", buffer.c_str()); + Base::Console().log("%s", buffer.c_str()); buffer.clear(); } return 0; @@ -306,7 +306,7 @@ int RedirectStdError::overflow(int ch) int RedirectStdError::sync() { if (!buffer.empty() && buffer.back() == '\n') { - Base::Console().Error("%s", buffer.c_str()); + Base::Console().error("%s", buffer.c_str()); buffer.clear(); } return 0; diff --git a/src/Base/ConsoleObserver.h b/src/Base/ConsoleObserver.h index cdf37cc2e6..1392e5f92d 100644 --- a/src/Base/ConsoleObserver.h +++ b/src/Base/ConsoleObserver.h @@ -43,12 +43,12 @@ public: explicit ConsoleObserverFile(const char* sFileName); ~ConsoleObserverFile() override; - void SendLog(const std::string& notifiername, + void sendLog(const std::string& notifiername, const std::string& msg, LogStyle level, IntendedRecipient recipient, ContentType content) override; - const char* Name() override + const char* name() override { return "File"; } @@ -70,12 +70,12 @@ class BaseExport ConsoleObserverStd: public ILogger public: ConsoleObserverStd(); ~ConsoleObserverStd() override; - void SendLog(const std::string& notifiername, + void sendLog(const std::string& notifiername, const std::string& msg, LogStyle level, IntendedRecipient recipient, ContentType content) override; - const char* Name() override + const char* name() override { return "Console"; } @@ -127,20 +127,20 @@ private: ILoggerBlocker::ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes) : conObs(co) { - msgTypesBlocked = Console().SetEnabledMsgType(conObs, msgTypes, false); + msgTypesBlocked = Console().setEnabledMsgType(conObs, msgTypes, false); } ILoggerBlocker::~ILoggerBlocker() { try { #ifdef FC_DEBUG - auto debug = Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); + auto debug = Console().setEnabledMsgType(conObs, msgTypesBlocked, true); if (debug != msgTypesBlocked) { - Console().Warning( + Console().warning( "Enabled message types have been changed while ILoggerBlocker was set\n"); } #else - Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); + Console().setEnabledMsgType(conObs, msgTypesBlocked, true); #endif } catch (...) { diff --git a/src/Base/Debugger.cpp b/src/Base/Debugger.cpp index 302b4f9311..99c1573d48 100644 --- a/src/Base/Debugger.cpp +++ b/src/Base/Debugger.cpp @@ -66,7 +66,7 @@ bool Debugger::eventFilter(QObject* /*watched*/, QEvent* event) int Debugger::exec() { if (isAttached) { - Base::Console().Message("TO CONTINUE PRESS ANY KEY...\n"); + Base::Console().message("TO CONTINUE PRESS ANY KEY...\n"); } return loop.exec(); } diff --git a/src/Base/DualQuaternion.h b/src/Base/DualQuaternion.h index cef6394663..37d09c24c5 100644 --- a/src/Base/DualQuaternion.h +++ b/src/Base/DualQuaternion.h @@ -130,7 +130,7 @@ public: // DEBUG // void print() const { - // Console().Log("%f, %f, %f, %f; %f, %f, %f, %f", x.re,y.re,z.re,w.re, x.du,y.du,z.du, + // Console().log("%f, %f, %f, %f; %f, %f, %f, %f", x.re,y.re,z.re,w.re, x.du,y.du,z.du, // w.du); // } }; diff --git a/src/Base/Exception.cpp b/src/Base/Exception.cpp index acbf6aa16c..aba6e95ee6 100644 --- a/src/Base/Exception.cpp +++ b/src/Base/Exception.cpp @@ -21,13 +21,15 @@ * * ***************************************************************************/ - #include "PreCompiled.h" +#ifndef _PreComp_ +#include +#endif -#include "Exception.h" #include "Console.h" #include "PyObjectBase.h" +#include "Exception.h" FC_LOG_LEVEL_INIT("Exception", true, true) @@ -35,120 +37,96 @@ using namespace Base; TYPESYSTEM_SOURCE(Base::Exception, Base::BaseClass) - - -Exception::Exception() - : _sErrMsg("FreeCAD Exception") - , _line(0) - , _isTranslatable(false) - , _isReported(false) +Exception::Exception(std::string message) + : errorMessage {std::move(message)} {} Exception::Exception(const Exception& inst) = default; Exception::Exception(Exception&& inst) noexcept = default; -Exception::Exception(const char* sMessage) - : _sErrMsg(sMessage) - , _line(0) - , _isTranslatable(false) - , _isReported(false) -{} - -Exception::Exception(std::string sMessage) - : _sErrMsg(std::move(sMessage)) - , _line(0) - , _isTranslatable(false) - , _isReported(false) -{} - Exception& Exception::operator=(const Exception& inst) { - _sErrMsg = inst._sErrMsg; - _file = inst._file; - _line = inst._line; - _function = inst._function; - _isTranslatable = inst._isTranslatable; + errorMessage = inst.errorMessage; + fileName = inst.fileName; + lineNum = inst.lineNum; + functionName = inst.functionName; + isTranslatable = inst.isTranslatable; return *this; } Exception& Exception::operator=(Exception&& inst) noexcept { - _sErrMsg = std::move(inst._sErrMsg); - _file = std::move(inst._file); - _line = inst._line; - _function = std::move(inst._function); - _isTranslatable = inst._isTranslatable; + errorMessage = std::move(inst.errorMessage); + fileName = std::move(inst.fileName); + lineNum = inst.lineNum; + functionName = std::move(inst.functionName); + isTranslatable = inst.isTranslatable; return *this; } const char* Exception::what() const noexcept { - return _sErrMsg.c_str(); + return errorMessage.c_str(); } -void Exception::ReportException() const +void Exception::reportException() const { - if (!_isReported) { - const char* msg {}; - if (_sErrMsg.empty()) { - msg = typeid(*this).name(); - } - else { - msg = _sErrMsg.c_str(); - } -#ifdef FC_DEBUG - if (!_function.empty()) { - _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); - } - else -#endif - { - _FC_ERR(_file.c_str(), _line, msg); - } - _isReported = true; + if (hasBeenReported) { + return; } + + std::string msg = errorMessage.empty() ? typeid(*this).name() : errorMessage; + +#ifdef FC_DEBUG + if (!functionName.empty()) { + msg = functionName + " -- " + msg; + } +#endif + + _FC_ERR(fileName.c_str(), lineNum, msg); + hasBeenReported = true; } PyObject* Exception::getPyObject() { Py::Dict edict; edict.setItem("sclassname", Py::String(typeid(*this).name())); - edict.setItem("sErrMsg", Py::String(this->getMessage())); - edict.setItem("sfile", Py::String(this->getFile())); - edict.setItem("iline", Py::Long(this->getLine())); - edict.setItem("sfunction", Py::String(this->getFunction())); - edict.setItem("swhat", Py::String(this->what())); - edict.setItem("btranslatable", Py::Boolean(this->getTranslatable())); - edict.setItem("breported", Py::Boolean(this->_isReported)); - return Py::new_reference_to(edict); + edict.setItem("sErrMsg", Py::String(getMessage())); + edict.setItem("sfile", Py::String(getFile())); + edict.setItem("iline", Py::Long(getLine())); + edict.setItem("sfunction", Py::String(getFunction())); + edict.setItem("swhat", Py::String(what())); + edict.setItem("btranslatable", Py::Boolean(getTranslatable())); + edict.setItem("breported", Py::Boolean(hasBeenReported)); + return new_reference_to(edict); } void Exception::setPyObject(PyObject* pydict) { try { if (pydict && Py::_Dict_Check(pydict)) { - Py::Dict edict(pydict); + const Py::Dict edict(pydict); if (edict.hasKey("sfile")) { - _file = static_cast(Py::String(edict.getItem("sfile"))); + fileName = Py::String(edict.getItem("sfile")); } if (edict.hasKey("sfunction")) { - _function = static_cast(Py::String(edict.getItem("sfunction"))); + functionName = Py::String(edict.getItem("sfunction")); } if (edict.hasKey("sErrMsg")) { - _sErrMsg = static_cast(Py::String(edict.getItem("sErrMsg"))); + errorMessage = Py::String(edict.getItem("sErrMsg")); } if (edict.hasKey("iline")) { - _line = static_cast(Py::Long(edict.getItem("iline"))); + lineNum = static_cast(Py::Long(edict.getItem("iline"))); } if (edict.hasKey("btranslatable")) { - _isTranslatable = static_cast(Py::Boolean(edict.getItem("btranslatable"))); + isTranslatable = static_cast(Py::Boolean(edict.getItem("btranslatable"))); } if (edict.hasKey("breported")) { - _isReported = static_cast(Py::Boolean(edict.getItem("breported"))); + hasBeenReported = static_cast(Py::Boolean(edict.getItem("breported"))); } } } @@ -176,15 +154,10 @@ void Exception::setPyException() const TYPESYSTEM_SOURCE(Base::AbortException, Base::Exception) -AbortException::AbortException(const char* sMessage) - : Exception(sMessage) +AbortException::AbortException(const std::string& message) + : Exception(message) {} -AbortException::AbortException() -{ - _sErrMsg = "Aborted operation"; -} - const char* AbortException::what() const noexcept { return Exception::what(); @@ -197,15 +170,8 @@ PyObject* AbortException::getPyExceptionType() const // --------------------------------------------------------- - -XMLBaseException::XMLBaseException() = default; - -XMLBaseException::XMLBaseException(const char* sMessage) - : Exception(sMessage) -{} - -XMLBaseException::XMLBaseException(const std::string& sMessage) - : Exception(sMessage) +XMLBaseException::XMLBaseException(const std::string& message) + : Exception(message) {} PyObject* XMLBaseException::getPyExceptionType() const @@ -215,19 +181,10 @@ PyObject* XMLBaseException::getPyExceptionType() const // --------------------------------------------------------- -XMLParseException::XMLParseException(const char* sMessage) - : XMLBaseException(sMessage) +XMLParseException::XMLParseException(const std::string& message) + : XMLBaseException(message) {} -XMLParseException::XMLParseException(const std::string& sMessage) - : XMLBaseException(sMessage) -{} - -XMLParseException::XMLParseException() -{ - _sErrMsg = "XML parse exception"; -} - const char* XMLParseException::what() const noexcept { return XMLBaseException::what(); @@ -240,19 +197,10 @@ PyObject* XMLParseException::getPyExceptionType() const // --------------------------------------------------------- -XMLAttributeError::XMLAttributeError(const char* sMessage) - : XMLBaseException(sMessage) +XMLAttributeError::XMLAttributeError(const std::string& message) + : XMLBaseException(message) {} -XMLAttributeError::XMLAttributeError(const std::string& sMessage) - : XMLBaseException(sMessage) -{} - -XMLAttributeError::XMLAttributeError() -{ - _sErrMsg = "XML attribute error"; -} - const char* XMLAttributeError::what() const noexcept { return XMLBaseException::what(); @@ -265,33 +213,27 @@ PyObject* XMLAttributeError::getPyExceptionType() const // --------------------------------------------------------- - -FileException::FileException(const char* sMessage, const char* sFileName) - : Exception(sMessage) - , file(sFileName) +FileException::FileException(const std::string& message, const std::string& fileName) + : Exception(message) + , file(fileName) { - setFileName(sFileName); + setFileName(fileName); } -FileException::FileException(const char* sMessage, const FileInfo& File) - : Exception(sMessage) +FileException::FileException(const std::string& message, const FileInfo& File) + : Exception(message) , file(File) { - setFileName(File.filePath().c_str()); + setFileName(File.filePath()); } -FileException::FileException() - : Exception("Unknown file exception happened") - , _sErrMsgAndFileName(_sErrMsg) -{} - -void FileException::setFileName(const char* sFileName) +void FileException::setFileName(const std::string& fileName) { - file.setFile(sFileName); - _sErrMsgAndFileName = _sErrMsg; - if (sFileName) { + file.setFile(fileName); + _sErrMsgAndFileName = getMessage(); + if (!getFile().empty()) { _sErrMsgAndFileName += ": "; - _sErrMsgAndFileName += sFileName; + _sErrMsgAndFileName += fileName; } } @@ -305,34 +247,28 @@ const char* FileException::what() const noexcept return _sErrMsgAndFileName.c_str(); } -void FileException::ReportException() const +void FileException::reportException() const { - if (!_isReported) { - const char* msg {}; - if (_sErrMsgAndFileName.empty()) { - msg = typeid(*this).name(); - } - else { - msg = _sErrMsgAndFileName.c_str(); - } -#ifdef FC_DEBUG - if (!_function.empty()) { - _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); - } - else -#endif - { - _FC_ERR(_file.c_str(), _line, msg); - } - _isReported = true; + if (getReported()) { + return; } + std::string msg = _sErrMsgAndFileName.empty() ? typeid(*this).name() : _sErrMsgAndFileName; + +#ifdef FC_DEBUG + if (!getFunction().empty()) { + msg = getFunction() + " -- " + msg; + } +#endif + + _FC_ERR(getFile().c_str(), getLine(), msg); + setReported(true); } PyObject* FileException::getPyObject() { Py::Dict edict(Exception::getPyObject(), true); edict.setItem("filename", Py::String(this->file.fileName())); - return Py::new_reference_to(edict); + return new_reference_to(edict); } void FileException::setPyObject(PyObject* pydict) @@ -340,9 +276,8 @@ void FileException::setPyObject(PyObject* pydict) if (pydict) { Exception::setPyObject(pydict); - Py::Dict edict(pydict); - if (edict.hasKey("filename")) { - setFileName(Py::String(edict.getItem("filename")).as_std_string("utf-8").c_str()); + if (const Py::Dict edict(pydict); edict.hasKey("filename")) { + setFileName(Py::String(edict.getItem("filename")).as_std_string("utf-8")); } } } @@ -354,15 +289,8 @@ PyObject* FileException::getPyExceptionType() const // --------------------------------------------------------- - -FileSystemError::FileSystemError() = default; - -FileSystemError::FileSystemError(const char* sMessage) - : Exception(sMessage) -{} - -FileSystemError::FileSystemError(const std::string& sMessage) - : Exception(sMessage) +FileSystemError::FileSystemError(const std::string& message) + : Exception(message) {} PyObject* FileSystemError::getPyExceptionType() const @@ -372,15 +300,8 @@ PyObject* FileSystemError::getPyExceptionType() const // --------------------------------------------------------- - -BadFormatError::BadFormatError() = default; - -BadFormatError::BadFormatError(const char* sMessage) - : Exception(sMessage) -{} - -BadFormatError::BadFormatError(const std::string& sMessage) - : Exception(sMessage) +BadFormatError::BadFormatError(const std::string& message) + : Exception(message) {} PyObject* BadFormatError::getPyExceptionType() const @@ -390,47 +311,14 @@ PyObject* BadFormatError::getPyExceptionType() const // --------------------------------------------------------- - -MemoryException::MemoryException() -{ - _sErrMsg = "Not enough memory available"; -} - -MemoryException::MemoryException(const MemoryException& inst) -#if defined(__GNUC__) - : std::bad_alloc() - , Exception(inst) -#else - : Exception(inst) -#endif +MemoryException::MemoryException(const std::string& message) + : Exception(message) // NOLINT(*-throw-keyword-missing) {} -MemoryException::MemoryException(MemoryException&& inst) noexcept -#if defined(__GNUC__) - : std::bad_alloc() - , Exception(inst) -#else - : Exception(inst) -#endif -{} - -MemoryException& MemoryException::operator=(const MemoryException& inst) -{ - Exception::operator=(inst); - return *this; -} - -MemoryException& MemoryException::operator=(MemoryException&& inst) noexcept -{ - Exception::operator=(inst); - return *this; -} - #if defined(__GNUC__) const char* MemoryException::what() const noexcept { - // call what() of Exception, not of std::bad_alloc - return Exception::what(); + return Exception::what(); // from Exception, not std::bad_alloc } #endif @@ -441,17 +329,8 @@ PyObject* MemoryException::getPyExceptionType() const // --------------------------------------------------------- -AccessViolation::AccessViolation() -{ - _sErrMsg = "Access violation"; -} - -AccessViolation::AccessViolation(const char* sMessage) - : Exception(sMessage) -{} - -AccessViolation::AccessViolation(const std::string& sMessage) - : Exception(sMessage) +AccessViolation::AccessViolation(const std::string& message) + : Exception(message) {} PyObject* AccessViolation::getPyExceptionType() const @@ -461,17 +340,8 @@ PyObject* AccessViolation::getPyExceptionType() const // --------------------------------------------------------- -AbnormalProgramTermination::AbnormalProgramTermination() -{ - _sErrMsg = "Abnormal program termination"; -} - -AbnormalProgramTermination::AbnormalProgramTermination(const char* sMessage) - : Exception(sMessage) -{} - -AbnormalProgramTermination::AbnormalProgramTermination(const std::string& sMessage) - : Exception(sMessage) +AbnormalProgramTermination::AbnormalProgramTermination(const std::string& message) + : Exception(message) {} PyObject* AbnormalProgramTermination::getPyExceptionType() const @@ -481,14 +351,8 @@ PyObject* AbnormalProgramTermination::getPyExceptionType() const // --------------------------------------------------------- -UnknownProgramOption::UnknownProgramOption() = default; - -UnknownProgramOption::UnknownProgramOption(const char* sMessage) - : Exception(sMessage) -{} - -UnknownProgramOption::UnknownProgramOption(const std::string& sMessage) - : Exception(sMessage) +UnknownProgramOption::UnknownProgramOption(const std::string& message) + : Exception(message) {} PyObject* UnknownProgramOption::getPyExceptionType() const @@ -498,26 +362,14 @@ PyObject* UnknownProgramOption::getPyExceptionType() const // --------------------------------------------------------- -ProgramInformation::ProgramInformation() = default; - -ProgramInformation::ProgramInformation(const char* sMessage) - : Exception(sMessage) -{} - -ProgramInformation::ProgramInformation(const std::string& sMessage) - : Exception(sMessage) +ProgramInformation::ProgramInformation(const std::string& message) + : Exception(message) {} // --------------------------------------------------------- -TypeError::TypeError() = default; - -TypeError::TypeError(const char* sMessage) - : Exception(sMessage) -{} - -TypeError::TypeError(const std::string& sMessage) - : Exception(sMessage) +TypeError::TypeError(const std::string& message) + : Exception(message) {} PyObject* TypeError::getPyExceptionType() const @@ -527,14 +379,8 @@ PyObject* TypeError::getPyExceptionType() const // --------------------------------------------------------- -ValueError::ValueError() = default; - -ValueError::ValueError(const char* sMessage) - : Exception(sMessage) -{} - -ValueError::ValueError(const std::string& sMessage) - : Exception(sMessage) +ValueError::ValueError(const std::string& message) + : Exception(message) {} PyObject* ValueError::getPyExceptionType() const @@ -544,14 +390,8 @@ PyObject* ValueError::getPyExceptionType() const // --------------------------------------------------------- -IndexError::IndexError() = default; - -IndexError::IndexError(const char* sMessage) - : Exception(sMessage) -{} - -IndexError::IndexError(const std::string& sMessage) - : Exception(sMessage) +IndexError::IndexError(const std::string& message) + : Exception(message) {} PyObject* IndexError::getPyExceptionType() const @@ -561,14 +401,8 @@ PyObject* IndexError::getPyExceptionType() const // --------------------------------------------------------- -NameError::NameError() = default; - -NameError::NameError(const char* sMessage) - : Exception(sMessage) -{} - -NameError::NameError(const std::string& sMessage) - : Exception(sMessage) +NameError::NameError(const std::string& message) + : Exception(message) {} PyObject* NameError::getPyExceptionType() const @@ -578,14 +412,8 @@ PyObject* NameError::getPyExceptionType() const // --------------------------------------------------------- -ImportError::ImportError() = default; - -ImportError::ImportError(const char* sMessage) - : Exception(sMessage) -{} - -ImportError::ImportError(const std::string& sMessage) - : Exception(sMessage) +ImportError::ImportError(const std::string& message) + : Exception(message) {} PyObject* ImportError::getPyExceptionType() const @@ -595,14 +423,8 @@ PyObject* ImportError::getPyExceptionType() const // --------------------------------------------------------- -AttributeError::AttributeError() = default; - -AttributeError::AttributeError(const char* sMessage) - : Exception(sMessage) -{} - -AttributeError::AttributeError(const std::string& sMessage) - : Exception(sMessage) +AttributeError::AttributeError(const std::string& message) + : Exception(message) {} PyObject* AttributeError::getPyExceptionType() const @@ -612,14 +434,8 @@ PyObject* AttributeError::getPyExceptionType() const // --------------------------------------------------------- -PropertyError::PropertyError() = default; - -PropertyError::PropertyError(const char* sMessage) - : AttributeError(sMessage) -{} - -PropertyError::PropertyError(const std::string& sMessage) - : AttributeError(sMessage) +PropertyError::PropertyError(const std::string& message) + : AttributeError(message) {} PyObject* PropertyError::getPyExceptionType() const @@ -629,14 +445,8 @@ PyObject* PropertyError::getPyExceptionType() const // --------------------------------------------------------- -RuntimeError::RuntimeError() = default; - -RuntimeError::RuntimeError(const char* sMessage) - : Exception(sMessage) -{} - -RuntimeError::RuntimeError(const std::string& sMessage) - : Exception(sMessage) +RuntimeError::RuntimeError(const std::string& message) + : Exception(message) {} PyObject* RuntimeError::getPyExceptionType() const @@ -646,16 +456,8 @@ PyObject* RuntimeError::getPyExceptionType() const // --------------------------------------------------------- -BadGraphError::BadGraphError() - : RuntimeError("The graph must be a DAG.") -{} - -BadGraphError::BadGraphError(const char* sMessage) - : RuntimeError(sMessage) -{} - -BadGraphError::BadGraphError(const std::string& sMessage) - : RuntimeError(sMessage) +BadGraphError::BadGraphError(const std::string& message) + : RuntimeError(message) {} PyObject* BadGraphError::getPyExceptionType() const @@ -665,14 +467,8 @@ PyObject* BadGraphError::getPyExceptionType() const // --------------------------------------------------------- -NotImplementedError::NotImplementedError() = default; - -NotImplementedError::NotImplementedError(const char* sMessage) - : Exception(sMessage) -{} - -NotImplementedError::NotImplementedError(const std::string& sMessage) - : Exception(sMessage) +NotImplementedError::NotImplementedError(const std::string& message) + : Exception(message) {} PyObject* NotImplementedError::getPyExceptionType() const @@ -682,14 +478,8 @@ PyObject* NotImplementedError::getPyExceptionType() const // --------------------------------------------------------- -ZeroDivisionError::ZeroDivisionError() = default; - -ZeroDivisionError::ZeroDivisionError(const char* sMessage) - : Exception(sMessage) -{} - -ZeroDivisionError::ZeroDivisionError(const std::string& sMessage) - : Exception(sMessage) +ZeroDivisionError::ZeroDivisionError(const std::string& message) + : Exception(message) {} PyObject* ZeroDivisionError::getPyExceptionType() const @@ -699,14 +489,8 @@ PyObject* ZeroDivisionError::getPyExceptionType() const // --------------------------------------------------------- -ReferenceError::ReferenceError() = default; - -ReferenceError::ReferenceError(const char* sMessage) - : Exception(sMessage) -{} - -ReferenceError::ReferenceError(const std::string& sMessage) - : Exception(sMessage) +ReferenceError::ReferenceError(const std::string& message) + : Exception(message) {} PyObject* ReferenceError::getPyExceptionType() const @@ -716,14 +500,8 @@ PyObject* ReferenceError::getPyExceptionType() const // --------------------------------------------------------- -ExpressionError::ExpressionError() = default; - -ExpressionError::ExpressionError(const char* sMessage) - : Exception(sMessage) -{} - -ExpressionError::ExpressionError(const std::string& sMessage) - : Exception(sMessage) +ExpressionError::ExpressionError(const std::string& message) + : Exception(message) {} PyObject* ExpressionError::getPyExceptionType() const @@ -733,14 +511,8 @@ PyObject* ExpressionError::getPyExceptionType() const // --------------------------------------------------------- -ParserError::ParserError() = default; - -ParserError::ParserError(const char* sMessage) - : Exception(sMessage) -{} - -ParserError::ParserError(const std::string& sMessage) - : Exception(sMessage) +ParserError::ParserError(const std::string& message) + : Exception(message) {} PyObject* ParserError::getPyExceptionType() const @@ -750,14 +522,8 @@ PyObject* ParserError::getPyExceptionType() const // --------------------------------------------------------- -UnicodeError::UnicodeError() = default; - -UnicodeError::UnicodeError(const char* sMessage) - : Exception(sMessage) -{} - -UnicodeError::UnicodeError(const std::string& sMessage) - : Exception(sMessage) +UnicodeError::UnicodeError(const std::string& message) + : Exception(message) {} PyObject* UnicodeError::getPyExceptionType() const @@ -767,14 +533,8 @@ PyObject* UnicodeError::getPyExceptionType() const // --------------------------------------------------------- -OverflowError::OverflowError() = default; - -OverflowError::OverflowError(const char* sMessage) - : Exception(sMessage) -{} - -OverflowError::OverflowError(const std::string& sMessage) - : Exception(sMessage) +OverflowError::OverflowError(const std::string& message) + : Exception(message) {} PyObject* OverflowError::getPyExceptionType() const @@ -784,14 +544,8 @@ PyObject* OverflowError::getPyExceptionType() const // --------------------------------------------------------- -UnderflowError::UnderflowError() = default; - -UnderflowError::UnderflowError(const char* sMessage) - : Exception(sMessage) -{} - -UnderflowError::UnderflowError(const std::string& sMessage) - : Exception(sMessage) +UnderflowError::UnderflowError(const std::string& message) + : Exception(message) {} PyObject* UnderflowError::getPyExceptionType() const @@ -801,14 +555,8 @@ PyObject* UnderflowError::getPyExceptionType() const // --------------------------------------------------------- -UnitsMismatchError::UnitsMismatchError() = default; - -UnitsMismatchError::UnitsMismatchError(const char* sMessage) - : Exception(sMessage) -{} - -UnitsMismatchError::UnitsMismatchError(const std::string& sMessage) - : Exception(sMessage) +UnitsMismatchError::UnitsMismatchError(const std::string& message) + : Exception(message) {} PyObject* UnitsMismatchError::getPyExceptionType() const @@ -818,14 +566,8 @@ PyObject* UnitsMismatchError::getPyExceptionType() const // --------------------------------------------------------- -CADKernelError::CADKernelError() = default; - -CADKernelError::CADKernelError(const char* sMessage) - : Exception(sMessage) -{} - -CADKernelError::CADKernelError(const std::string& sMessage) - : Exception(sMessage) +CADKernelError::CADKernelError(const std::string& message) + : Exception(message) {} PyObject* CADKernelError::getPyExceptionType() const @@ -835,14 +577,8 @@ PyObject* CADKernelError::getPyExceptionType() const // --------------------------------------------------------- -RestoreError::RestoreError() = default; - -RestoreError::RestoreError(const char* sMessage) - : Exception(sMessage) -{} - -RestoreError::RestoreError(const std::string& sMessage) - : Exception(sMessage) +RestoreError::RestoreError(const std::string& message) + : Exception(message) {} PyObject* RestoreError::getPyExceptionType() const @@ -855,6 +591,7 @@ PyObject* RestoreError::getPyExceptionType() const #if defined(__GNUC__) && defined(FC_OS_LINUX) #include #include +#include SignalException::SignalException() { @@ -876,7 +613,7 @@ SignalException::~SignalException() #endif } -void SignalException::throw_signal(int signum) +void SignalException::throw_signal(const int signum) { std::cerr << "SIGSEGV signal raised: " << signum << std::endl; throw std::runtime_error("throw_signal"); diff --git a/src/Base/Exception.h b/src/Base/Exception.h index 2ebdd78744..b85a3592c1 100644 --- a/src/Base/Exception.h +++ b/src/Base/Exception.h @@ -21,172 +21,126 @@ * * ***************************************************************************/ - #ifndef BASE_EXCEPTION_H #define BASE_EXCEPTION_H #include +#include #include + #include "BaseClass.h" #include "FileInfo.h" +using PyObject = struct _object; // NOLINT -using PyObject = struct _object; +// Remove once all used compilers support this +#if defined(__cpp_lib_source_location) +#define HAVE_STD_SOURCE_LOCATION 1 +#else +#undef HAVE_STD_SOURCE_LOCATION +#endif +// std::source_location is implemented, but buggy in Clang 15 +#if defined(__clang__) && __clang_major__ <= 15 +#undef HAVE_STD_SOURCE_LOCATION +#endif -/* MACROS FOR THROWING EXCEPTIONS */ - -/// the macros do NOT mark any message for translation +/// The macros do NOT mark any message for translation /// If you want to mark text for translation, use the QT_TRANSLATE_NOOP macro -/// with the context "Exceptions" and the right throwing macro from below (the one ending in T) +/// with the context "Exceptions" and the right throwing macro from below (the one ending with T) /// example: /// THROWMT(Base::ValueError,QT_TRANSLATE_NOOP("Exceptions","The multiplicity cannot be increased /// beyond the degree of the B-Spline.")); /// /// N.B.: The QT_TRANSLATE_NOOP macro won't translate your string. It will just allow lupdate to /// identify that string for translation so that if you ask for a translation (and the translator -/// have provided one) at that time it gets translated (e.g. in the UI before showing the message of -/// the exception). +/// have provided one) at that time it gets translated (e.g. in the UI before showing the message +/// of the exception). -// NOLINTBEGIN -#ifdef _MSC_VER - -#define THROW(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - throw myexcp; \ - } -#define THROWM(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - throw myexcp; \ - } -#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - throw myexcp; \ - } - -#define THROWT(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMT(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __FUNCSIG__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } - -#elif defined(__GNUC__) - -#define THROW(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - throw myexcp; \ - } -#define THROWM(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - throw myexcp; \ - } -#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - throw myexcp; \ - } - -#define THROWT(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMT(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __PRETTY_FUNCTION__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } - -#else - -#define THROW(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - throw myexcp; \ - } -#define THROWM(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - throw myexcp; \ - } -#define THROWMF_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - throw myexcp; \ - } - -#define THROWT(exception) \ - { \ - exception myexcp; \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMT(exception, message) \ - { \ - exception myexcp(message); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } -#define THROWMFT_FILEEXCEPTION(message, filenameorfileinfo) \ - { \ - FileException myexcp(message, filenameorfileinfo); \ - myexcp.setDebugInformation(__FILE__, __LINE__, __func__); \ - myexcp.setTranslatable(true); \ - throw myexcp; \ - } - - -#endif - -#define FC_THROWM(_exception, _msg) \ +#if defined(HAVE_STD_SOURCE_LOCATION) +// NOLINTBEGIN(*-macro-usage) +#define THROWM(exc, msg) Base::setupAndThrowException((msg), std::source_location::current()); +#define THROWMT(exc, msg) \ + Base::setupAndThrowException((msg), std::source_location::current(), true); +#define FC_THROWM(exception, msg) \ do { \ std::stringstream ss; \ - ss << _msg; \ - THROWM(_exception, ss.str().c_str()); \ + ss << msg; \ + THROWM(exception, ss.str()); \ } while (0) -// NOLINTEND +// NOLINTEND(*-macro-usage) + +namespace Base +{ +template +[[noreturn]] void setupAndThrowException(const std::string message, + const std::source_location location, + const bool translatable = false) +{ + ExceptionType exception {message}; + exception.setTranslatable(translatable); + exception.setDebugInformation(location); + throw exception; +} // NOLINT // unreachable +} // namespace Base + +#else // HAVE_STD_SOURCE_LOCATION + +#ifdef _MSC_VER +#define FC_THROW_INFO __FILE__, __LINE__, __FUNCSIG__ +#elif __GNUC__ +#define FC_THROW_INFO __FILE__, __LINE__, __PRETTY_FUNCTION__ +#else +#define FC_THROW_INFO __FILE__, __LINE__, __func__ +#endif + +#define THROWM(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO); +#define THROWMT(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO, true); +#define FC_THROWM(exception, msg) \ + do { \ + std::stringstream ss; \ + ss << msg; \ + THROWM(exception, ss.str()); \ + } while (0) +namespace Base +{ +template +[[noreturn]] void setupAndThrowException(const std::string message, + const char* file, + const int line, + const char* func, + const bool translatable = false) +{ + ExceptionType exception {message}; + exception.setTranslatable(translatable); + exception.setDebugInformation(file, line, func); + throw exception; +} // NOLINT // unreachable +} // namespace Base + +#endif // HAVE_STD_SOURCE_LOCATION + +//-------------------------------------------------------------------------------------------------- + +template +constexpr void THROWM_(const std::string& msg, + const std::source_location location = std::source_location::current()) +{ + Base::setupAndThrowException(msg, location); +} + +template +constexpr void THROWMT_(const std::string& msg, + const std::source_location location = std::source_location::current()) +{ + Base::setupAndThrowException(msg, location, true); +} + +template +constexpr void FC_THROWM_(const std::string& raw_msg, + const std::source_location location = std::source_location::current()) +{ + THROWM_(raw_msg, location); +} namespace Base { @@ -196,18 +150,16 @@ class BaseExport Exception: public BaseClass TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: + explicit Exception(std::string message = "FreeCAD Exception"); ~Exception() noexcept override = default; Exception& operator=(const Exception& inst); Exception& operator=(Exception&& inst) noexcept; virtual const char* what() const noexcept; + virtual void reportException() const; // once only - /// Reports exception. It includes a mechanism to only report an exception once. - virtual void ReportException() const; - - inline void setMessage(const char* sMessage); - inline void setMessage(const std::string& sMessage); + inline void setMessage(const std::string& message); // what may differ from the message given by the user in // derived classes inline std::string getMessage() const; @@ -215,212 +167,104 @@ public: inline int getLine() const; inline std::string getFunction() const; inline bool getTranslatable() const; - inline bool getReported() const - { - return _isReported; - } + inline bool getReported() const; + inline void setReported(bool reported) const; - /// setter methods for including debug information - /// intended to use via macro for autofilling of debugging information - inline void setDebugInformation(const std::string& file, int line, const std::string& function); +#if defined(HAVE_STD_SOURCE_LOCATION) + inline void setDebugInformation(const std::source_location& location); +#else + inline void setDebugInformation(const char* file, int line, const char* func); +#endif inline void setTranslatable(bool translatable); - inline void setReported(bool reported) - { - _isReported = reported; - } + PyObject* getPyObject() override; // exception data + void setPyObject(PyObject* pydict) override; // set the exception data - /// returns a Python dictionary containing the exception data - PyObject* getPyObject() override; - /// returns sets the exception data from a Python dictionary - void setPyObject(PyObject* pydict) override; - - /// returns the corresponding python exception type virtual PyObject* getPyExceptionType() const; - /// Sets the Python error indicator and an error message virtual void setPyException() const; protected: - /* sMessage may be: - * - a UI compliant string susceptible to being translated and shown to the user in the UI - * - a very technical message not intended to be translated or shown to the user in the UI - * The preferred way of throwing an exception is using the macros above. - * This way, the file, line, and function are automatically inserted. */ - explicit Exception(const char* sMessage); - explicit Exception(std::string sMessage); - Exception(); Exception(const Exception& inst); Exception(Exception&& inst) noexcept; -protected: - std::string _sErrMsg; - std::string _file; - int _line; - std::string _function; - bool _isTranslatable; - mutable bool _isReported; +private: + std::string errorMessage; + std::string fileName; + int lineNum {0}; + std::string functionName; + bool isTranslatable {false}; + mutable bool hasBeenReported {false}; }; - -/** - * The AbortException is thrown if a pending operation was aborted. - * @author Werner Mayer - */ class BaseExport AbortException: public Exception { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - /// Construction - explicit AbortException(const char* sMessage); - /// Construction - AbortException(); - AbortException(const AbortException&) = default; - AbortException(AbortException&&) = default; + explicit AbortException(const std::string& message = "Aborted operation"); - /// Destruction - ~AbortException() noexcept override = default; - AbortException& operator=(const AbortException&) = default; - AbortException& operator=(AbortException&&) = default; - - /// Description of the exception const char* what() const noexcept override; - /// returns the corresponding python exception type PyObject* getPyExceptionType() const override; }; -/** - * The XMLBaseException can be used to indicate any kind of XML related errors. - * @author Werner Mayer - */ class BaseExport XMLBaseException: public Exception { public: - /// Construction - XMLBaseException(); - explicit XMLBaseException(const char* sMessage); - explicit XMLBaseException(const std::string& sMessage); - XMLBaseException(const XMLBaseException&) = default; - XMLBaseException(XMLBaseException&&) = default; - - /// Destruction - ~XMLBaseException() noexcept override = default; - XMLBaseException& operator=(const XMLBaseException&) = default; - XMLBaseException& operator=(XMLBaseException&&) = default; + explicit XMLBaseException(const std::string& message = "XML base exception"); PyObject* getPyExceptionType() const override; }; -/** - * The XMLParseException is thrown if parsing an XML failed. - * @author Werner Mayer - */ class BaseExport XMLParseException: public XMLBaseException { public: - /// Construction - explicit XMLParseException(const char* sMessage); - /// Construction - explicit XMLParseException(const std::string& sMessage); - /// Construction - XMLParseException(); - XMLParseException(const XMLParseException&) = default; - XMLParseException(XMLParseException&&) = default; + explicit XMLParseException(const std::string& message = "XML parse exception"); - /// Destruction - ~XMLParseException() noexcept override = default; - XMLParseException& operator=(const XMLParseException&) = default; - XMLParseException& operator=(XMLParseException&&) = default; - - /// Description of the exception const char* what() const noexcept override; PyObject* getPyExceptionType() const override; }; -/** - * The XMLAttributeError is thrown if a requested attribute doesn't exist. - * @author Werner Mayer - */ class BaseExport XMLAttributeError: public XMLBaseException { public: - /// Construction - explicit XMLAttributeError(const char* sMessage); - /// Construction - explicit XMLAttributeError(const std::string& sMessage); - /// Construction - XMLAttributeError(); - XMLAttributeError(const XMLAttributeError&) = default; - XMLAttributeError(XMLAttributeError&&) = default; + explicit XMLAttributeError(const std::string& message = "XML attribute error"); - /// Destruction - ~XMLAttributeError() noexcept override = default; - XMLAttributeError& operator=(const XMLAttributeError&) = default; - XMLAttributeError& operator=(XMLAttributeError&&) = default; - - /// Description of the exception const char* what() const noexcept override; PyObject* getPyExceptionType() const override; }; -/** File exception handling class - * This class is specialized to go with exception thrown in case of File IO Problems. - * @author Juergen Riegel - */ class BaseExport FileException: public Exception { public: - /// With massage and file name - explicit FileException(const char* sMessage, const char* sFileName = nullptr); - /// With massage and file name - FileException(const char* sMessage, const FileInfo& File); - /// standard construction - FileException(); - FileException(const FileException&) = default; - FileException(FileException&&) = default; - /// Destruction - ~FileException() noexcept override = default; - /// Assignment operator - FileException& operator=(const FileException&) = default; - FileException& operator=(FileException&&) = default; + explicit FileException(const std::string& message = "Unknown file exception happened", + const std::string& fileName = ""); + FileException(const std::string& message, const FileInfo& File); - /// Description of the exception const char* what() const noexcept override; - /// Report generation - void ReportException() const override; - /// Get file name for use with translatable message + void reportException() const override; std::string getFileName() const; - /// returns a Python dictionary containing the exception data PyObject* getPyObject() override; - /// returns sets the exception data from a Python dictionary + void setPyObject(PyObject* pydict) override; PyObject* getPyExceptionType() const override; -protected: +private: FileInfo file; // necessary for what() legacy behaviour as it returns a buffer that // can not be of a temporary object to be destroyed at end of what() std::string _sErrMsgAndFileName; - void setFileName(const char* sFileName = nullptr); + void setFileName(const std::string& fileName); }; -/** - * The FileSystemError can be used to indicate errors on file system - * e.g. if renaming of a file failed. - * @author Werner Mayer - */ class BaseExport FileSystemError: public Exception { public: - /// Construction - FileSystemError(); - explicit FileSystemError(const char* sMessage); - explicit FileSystemError(const std::string& sMessage); + explicit FileSystemError(const std::string& message = "File system error"); FileSystemError(const FileSystemError&) = default; FileSystemError(FileSystemError&&) = default; - /// Destruction + ~FileSystemError() noexcept override = default; FileSystemError& operator=(const FileSystemError&) = default; FileSystemError& operator=(FileSystemError&&) = default; @@ -428,580 +272,267 @@ public: PyObject* getPyExceptionType() const override; }; -/** - * The BadFormatError can be used to indicate errors in a data structure. - * @author Werner Mayer - */ +/** errors in a data structure */ class BaseExport BadFormatError: public Exception { public: - /// Construction - BadFormatError(); - explicit BadFormatError(const char* sMessage); - explicit BadFormatError(const std::string& sMessage); + explicit BadFormatError(const std::string& message = "Bad format error"); BadFormatError(const BadFormatError&) = default; BadFormatError(BadFormatError&&) = default; - /// Destruction + ~BadFormatError() noexcept override = default; BadFormatError& operator=(const BadFormatError&) = default; BadFormatError& operator=(BadFormatError&&) = default; PyObject* getPyExceptionType() const override; }; -/** - * The MemoryException is thrown if not enough memory can be allocated. - * @author Werner Mayer - */ #if defined(__GNUC__) -// It seems that the calling instance of our new handler expects a bad_alloc exception +// calling instance of our new handler expects a bad_alloc exception class BaseExport MemoryException: public Exception, virtual public std::bad_alloc #else class BaseExport MemoryException: public Exception #endif { public: - /// Construction - MemoryException(); - /// Construction - MemoryException(const MemoryException& inst); - MemoryException(MemoryException&& inst) noexcept; - /// Destruction - ~MemoryException() noexcept override = default; - /// Assignment operator - MemoryException& operator=(const MemoryException& inst); - MemoryException& operator=(MemoryException&& inst) noexcept; + explicit MemoryException(const std::string& = "Not enough memory available"); + #if defined(__GNUC__) - /// Description of the exception const char* what() const noexcept override; #endif + PyObject* getPyExceptionType() const override; }; -/** - * The AccessViolation can be used in an own signal handler. - * @author Werner Mayer - */ +/** can be used in an own signal handler */ class BaseExport AccessViolation: public Exception { public: - /// Construction - AccessViolation(); - explicit AccessViolation(const char* sMessage); - explicit AccessViolation(const std::string& sMessage); - AccessViolation(const AccessViolation&) = default; - AccessViolation(AccessViolation&&) = default; - /// Destruction - ~AccessViolation() noexcept override = default; - AccessViolation& operator=(const AccessViolation&) = default; - AccessViolation& operator=(AccessViolation&&) = default; + explicit AccessViolation(const std::string& message = "Access violation"); PyObject* getPyExceptionType() const override; }; -/** - * The AbnormalProgramTermination can be used in an own signal handler. - * @author Werner Mayer - */ +/** can be used in an own signal handler */ class BaseExport AbnormalProgramTermination: public Exception { public: - /// Construction - AbnormalProgramTermination(); - /// Construction - explicit AbnormalProgramTermination(const char* sMessage); - explicit AbnormalProgramTermination(const std::string& sMessage); - AbnormalProgramTermination(const AbnormalProgramTermination&) = default; - AbnormalProgramTermination(AbnormalProgramTermination&&) = default; - /// Destruction - ~AbnormalProgramTermination() noexcept override = default; - AbnormalProgramTermination& operator=(const AbnormalProgramTermination&) = default; - AbnormalProgramTermination& operator=(AbnormalProgramTermination&&) = default; + explicit AbnormalProgramTermination( + const std::string& message = "Abnormal program termination"); PyObject* getPyExceptionType() const override; }; -/** - * The UnknownProgramOption can be used to indicate an unknown program option. - * @author Werner Mayer - */ class BaseExport UnknownProgramOption: public Exception { public: - /// Construction - UnknownProgramOption(); - explicit UnknownProgramOption(const char* sMessage); - explicit UnknownProgramOption(const std::string& sMessage); - UnknownProgramOption(const UnknownProgramOption&) = default; - UnknownProgramOption(UnknownProgramOption&&) = default; - /// Destruction - ~UnknownProgramOption() noexcept override = default; - UnknownProgramOption& operator=(const UnknownProgramOption&) = default; - UnknownProgramOption& operator=(UnknownProgramOption&&) = default; + explicit UnknownProgramOption(const std::string& message = "Unknown program option"); PyObject* getPyExceptionType() const override; }; -/** - * The ProgramInformation can be used to show information about the program. - * @author Werner Mayer - */ class BaseExport ProgramInformation: public Exception { public: - /// Construction - ProgramInformation(); - explicit ProgramInformation(const char* sMessage); - explicit ProgramInformation(const std::string& sMessage); - ProgramInformation(const ProgramInformation&) = default; - ProgramInformation(ProgramInformation&&) = default; - - /// Destruction - ~ProgramInformation() noexcept override = default; - ProgramInformation& operator=(const ProgramInformation&) = default; - ProgramInformation& operator=(ProgramInformation&&) = default; + explicit ProgramInformation(const std::string& message = "Program information"); }; -/** - * The TypeError can be used to indicate the usage of a wrong type. - * @author Werner Mayer - */ class BaseExport TypeError: public Exception { public: - /// Construction - TypeError(); - explicit TypeError(const char* sMessage); - explicit TypeError(const std::string& sMessage); - TypeError(const TypeError&) = default; - TypeError(TypeError&&) = default; - /// Destruction - ~TypeError() noexcept override = default; - TypeError& operator=(const TypeError&) = default; - TypeError& operator=(TypeError&&) = default; + explicit TypeError(const std::string& message = "Type error"); PyObject* getPyExceptionType() const override; }; -/** - * The ValueError can be used to indicate the usage of a wrong value. - * @author Werner Mayer - */ class BaseExport ValueError: public Exception { public: - /// Construction - ValueError(); - explicit ValueError(const char* sMessage); - explicit ValueError(const std::string& sMessage); - ValueError(const ValueError&) = default; - ValueError(ValueError&&) = default; - /// Destruction - ~ValueError() noexcept override = default; - ValueError& operator=(const ValueError&) = default; - ValueError& operator=(ValueError&&) = default; + explicit ValueError(const std::string& message = "Value error"); PyObject* getPyExceptionType() const override; }; -/** - * The IndexError can be used when a sequence subscript is out of range. - * @author Werner Mayer - */ +/** sequence subscript is out of range */ class BaseExport IndexError: public Exception { public: - /// Construction - IndexError(); - explicit IndexError(const char* sMessage); - explicit IndexError(const std::string& sMessage); - IndexError(const IndexError&) = default; - IndexError(IndexError&&) = default; - /// Destruction - ~IndexError() noexcept override = default; - IndexError& operator=(const IndexError&) = default; - IndexError& operator=(IndexError&&) = default; + explicit IndexError(const std::string& message = "Index error"); PyObject* getPyExceptionType() const override; }; class BaseExport NameError: public Exception { public: - /// Construction - NameError(); - explicit NameError(const char* sMessage); - explicit NameError(const std::string& sMessage); - NameError(const NameError&) = default; - NameError(NameError&&) = default; - /// Destruction - ~NameError() noexcept override = default; - NameError& operator=(const NameError&) = default; - NameError& operator=(NameError&&) = default; + explicit NameError(const std::string& message = "Name error"); PyObject* getPyExceptionType() const override; }; class BaseExport ImportError: public Exception { public: - /// Construction - ImportError(); - explicit ImportError(const char* sMessage); - explicit ImportError(const std::string& sMessage); - ImportError(const ImportError&) = default; - ImportError(ImportError&&) = default; - /// Destruction - ~ImportError() noexcept override = default; - ImportError& operator=(const ImportError&) = default; - ImportError& operator=(ImportError&&) = default; + explicit ImportError(const std::string& message = "Import error"); PyObject* getPyExceptionType() const override; }; -/** - * The AttributeError can be used to indicate the usage of a wrong value. - * @author Werner Mayer - */ class BaseExport AttributeError: public Exception { public: - /// Construction - AttributeError(); - explicit AttributeError(const char* sMessage); - explicit AttributeError(const std::string& sMessage); - AttributeError(const AttributeError&) = default; - AttributeError(AttributeError&&) = default; - /// Destruction - ~AttributeError() noexcept override = default; - AttributeError& operator=(const AttributeError&) = default; - AttributeError& operator=(AttributeError&&) = default; + explicit AttributeError(const std::string& message = "Attribute error"); PyObject* getPyExceptionType() const override; }; -/** - * The PropertyError can be used to indicate the usage of a wrong property name or value. - * @author Mario Passaglia - */ class BaseExport PropertyError: public AttributeError { public: - /// Construction - PropertyError(); - explicit PropertyError(const char* sMessage); - explicit PropertyError(const std::string& sMessage); - PropertyError(const PropertyError&) = default; - PropertyError(PropertyError&&) = default; - /// Destruction - ~PropertyError() noexcept override = default; - PropertyError& operator=(const PropertyError&) = default; - PropertyError& operator=(PropertyError&&) = default; + explicit PropertyError(const std::string& message = "Property error"); PyObject* getPyExceptionType() const override; }; -/** - * The RuntimeError can be used to indicate an unknown exception at runtime. - * @author Werner Mayer - */ class BaseExport RuntimeError: public Exception { public: - /// Construction - RuntimeError(); - explicit RuntimeError(const char* sMessage); - explicit RuntimeError(const std::string& sMessage); - RuntimeError(const RuntimeError&) = default; - RuntimeError(RuntimeError&&) = default; - /// Destruction - ~RuntimeError() noexcept override = default; - RuntimeError& operator=(const RuntimeError&) = default; - RuntimeError& operator=(RuntimeError&&) = default; + explicit RuntimeError(const std::string& message = "Runtime error"); PyObject* getPyExceptionType() const override; }; -/** - * The BadGraphError can be used to indicate that a graph is e.g. not a DAG. - * @author Werner Mayer - */ class BaseExport BadGraphError: public RuntimeError { public: - /// Construction - BadGraphError(); - explicit BadGraphError(const char* sMessage); - explicit BadGraphError(const std::string& sMessage); - BadGraphError(const BadGraphError&) = default; - BadGraphError(BadGraphError&&) = default; - /// Destruction - ~BadGraphError() noexcept override = default; - BadGraphError& operator=(const BadGraphError&) = default; - BadGraphError& operator=(BadGraphError&&) = default; + explicit BadGraphError(const std::string& message = "Bad graph error"); PyObject* getPyExceptionType() const override; }; -/** - * The NotImplementedError can be used to indicate that an invoked function is not implemented. - * @author Werner Mayer - */ class BaseExport NotImplementedError: public Exception { public: - /// Construction - NotImplementedError(); - explicit NotImplementedError(const char* sMessage); - explicit NotImplementedError(const std::string& sMessage); - NotImplementedError(const NotImplementedError&) = default; - NotImplementedError(NotImplementedError&&) = default; - /// Destruction - ~NotImplementedError() noexcept override = default; - NotImplementedError& operator=(const NotImplementedError&) = default; - NotImplementedError& operator=(NotImplementedError&&) = default; + explicit NotImplementedError(const std::string& message = "Not implemented error"); PyObject* getPyExceptionType() const override; }; -/** - * The ZeroDivisionError can be used to indicate a division by zero. - * @author Werner Mayer - */ class BaseExport ZeroDivisionError: public Exception { public: - /// Construction - ZeroDivisionError(); - explicit ZeroDivisionError(const char* sMessage); - explicit ZeroDivisionError(const std::string& sMessage); - ZeroDivisionError(const ZeroDivisionError&) = default; - ZeroDivisionError(ZeroDivisionError&&) = default; - /// Destruction - ~ZeroDivisionError() noexcept override = default; - ZeroDivisionError& operator=(const ZeroDivisionError&) = default; - ZeroDivisionError& operator=(ZeroDivisionError&&) = default; + explicit ZeroDivisionError(const std::string& message = "Zero division error"); PyObject* getPyExceptionType() const override; }; -/** - * The ReferenceError can be used to indicate a reference counter has the wrong value. - * @author Werner Mayer - */ class BaseExport ReferenceError: public Exception { public: - /// Construction - ReferenceError(); - explicit ReferenceError(const char* sMessage); - explicit ReferenceError(const std::string& sMessage); - ReferenceError(const ReferenceError&) = default; - ReferenceError(ReferenceError&&) = default; - /// Destruction - ~ReferenceError() noexcept override = default; - ReferenceError& operator=(const ReferenceError&) = default; - ReferenceError& operator=(ReferenceError&&) = default; + explicit ReferenceError(const std::string& message = "Reference error"); PyObject* getPyExceptionType() const override; }; -/** - * The ExpressionError can be used to indicate erroneous.input - * to the expression engine. - * @author Werner Mayer - */ class BaseExport ExpressionError: public Exception { public: - /// Construction - ExpressionError(); - explicit ExpressionError(const char* sMessage); - explicit ExpressionError(const std::string& sMessage); - ExpressionError(const ExpressionError&) = default; - ExpressionError(ExpressionError&&) = default; - /// Destruction - ~ExpressionError() noexcept override = default; - ExpressionError& operator=(const ExpressionError&) = default; - ExpressionError& operator=(ExpressionError&&) = default; + explicit ExpressionError(const std::string& message = "Expression error"); PyObject* getPyExceptionType() const override; }; -/** - * The ParserError can be used to indicate the parsing error. - * @author Werner Mayer - */ class BaseExport ParserError: public Exception { public: - /// Construction - ParserError(); - explicit ParserError(const char* sMessage); - explicit ParserError(const std::string& sMessage); - ParserError(const ParserError&) = default; - ParserError(ParserError&&) = default; - /// Destruction - ~ParserError() noexcept override = default; - ParserError& operator=(const ParserError&) = default; - ParserError& operator=(ParserError&&) = default; + explicit ParserError(const std::string& message = "Parser error"); PyObject* getPyExceptionType() const override; }; -/** - * The UnicodeError can be used to indicate unicode encoding/decoding error. - * @author Werner Mayer - */ class BaseExport UnicodeError: public Exception { public: - /// Construction - UnicodeError(); - explicit UnicodeError(const char* sMessage); - explicit UnicodeError(const std::string& sMessage); - UnicodeError(const UnicodeError&) = default; - UnicodeError(UnicodeError&&) = default; - /// Destruction - ~UnicodeError() noexcept override = default; - UnicodeError& operator=(const UnicodeError&) = default; - UnicodeError& operator=(UnicodeError&&) = default; + explicit UnicodeError(const std::string& message = "Unicode error"); PyObject* getPyExceptionType() const override; }; -/** - * The OverflowError can be used to indicate overflows of numbers. - * @author Werner Mayer - */ class BaseExport OverflowError: public Exception { public: - /// Construction - OverflowError(); - explicit OverflowError(const char* sMessage); - explicit OverflowError(const std::string& sMessage); - OverflowError(const OverflowError&) = default; - OverflowError(OverflowError&&) = default; - /// Destruction - ~OverflowError() noexcept override = default; - OverflowError& operator=(const OverflowError&) = default; - OverflowError& operator=(OverflowError&&) = default; + explicit OverflowError(const std::string& message = "Overflow error"); PyObject* getPyExceptionType() const override; }; -/** - * The UnderflowError can be used to indicate underflows of numbers. - * @author Werner Mayer - */ class BaseExport UnderflowError: public Exception { public: - /// Construction - UnderflowError(); - explicit UnderflowError(const char* sMessage); - explicit UnderflowError(const std::string& sMessage); - UnderflowError(const UnderflowError&) = default; - UnderflowError(UnderflowError&&) = default; - /// Destruction - ~UnderflowError() noexcept override = default; - UnderflowError& operator=(const UnderflowError&) = default; - UnderflowError& operator=(UnderflowError&&) = default; + explicit UnderflowError(const std::string& message = "Underflow error"); PyObject* getPyExceptionType() const override; }; -/** - * The UnitsMismatchError can be used to indicate that quantities with different units are used. - * @author Werner Mayer - */ class BaseExport UnitsMismatchError: public Exception { public: - /// Construction - UnitsMismatchError(); - explicit UnitsMismatchError(const char* sMessage); - explicit UnitsMismatchError(const std::string& sMessage); - UnitsMismatchError(const UnitsMismatchError&) = default; - UnitsMismatchError(UnitsMismatchError&&) = default; - /// Destruction - ~UnitsMismatchError() noexcept override = default; - UnitsMismatchError& operator=(const UnitsMismatchError&) = default; - UnitsMismatchError& operator=(UnitsMismatchError&&) = default; + explicit UnitsMismatchError(const std::string& message = "Units mismatch error"); PyObject* getPyExceptionType() const override; }; -/* The CADKernelError can be used to indicate an exception originating in the CAD Kernel - * allowing to propagate the error messages of, for example, OCC Standard_Failure exception to - * the FreeCAD application without making the FreeCAD application depend on OCC. - * @author Abdullah Tahiri - */ class BaseExport CADKernelError: public Exception { public: - /// Construction - CADKernelError(); - explicit CADKernelError(const char* sMessage); - explicit CADKernelError(const std::string& sMessage); - CADKernelError(const CADKernelError&) = default; - CADKernelError(CADKernelError&&) = default; - /// Destruction - ~CADKernelError() noexcept override = default; - CADKernelError& operator=(const CADKernelError&) = default; - CADKernelError& operator=(CADKernelError&&) = default; + explicit CADKernelError(const std::string& message = "CAD kernel error"); PyObject* getPyExceptionType() const override; }; -/* The RestoreError can be used to try to do a best recovery effort when an error during restoring - * occurs. The best recovery effort may be to ignore the element altogether or to insert a - * placeholder depending on where the actual element being restored is used. - * - * For example, if it is part of an array (e.g. PropertyList) and the order in the array is - * relevant, it is better to have a placeholder than to fail to restore the whole array. - */ class BaseExport RestoreError: public Exception { public: - /// Construction - RestoreError(); - explicit RestoreError(const char* sMessage); - explicit RestoreError(const std::string& sMessage); - RestoreError(const RestoreError&) = default; - RestoreError(RestoreError&&) = default; - /// Destruction - ~RestoreError() noexcept override = default; - RestoreError& operator=(const RestoreError&) = default; - RestoreError& operator=(RestoreError&&) = default; + explicit RestoreError(const std::string& message = "Restore error"); PyObject* getPyExceptionType() const override; }; - -inline void Exception::setMessage(const char* sMessage) +inline void Exception::setMessage(const std::string& message) { - _sErrMsg = sMessage; -} - -inline void Exception::setMessage(const std::string& sMessage) -{ - _sErrMsg = sMessage; + errorMessage = message; } inline std::string Exception::getMessage() const { - return _sErrMsg; + return errorMessage; } inline std::string Exception::getFile() const { - return _file; + return fileName; } inline int Exception::getLine() const { - return _line; + return lineNum; } inline std::string Exception::getFunction() const { - return _function; + return functionName; } inline bool Exception::getTranslatable() const { - return _isTranslatable; + return isTranslatable; } -inline void -Exception::setDebugInformation(const std::string& file, int line, const std::string& function) +inline bool Exception::getReported() const { - _file = file; - _line = line; - _function = function; + return hasBeenReported; } -inline void Exception::setTranslatable(bool translatable) +inline void Exception::setReported(const bool reported) const { - _isTranslatable = translatable; + hasBeenReported = reported; +} + +#if defined(HAVE_STD_SOURCE_LOCATION) +inline void Exception::setDebugInformation(const std::source_location& location) +{ + fileName = location.file_name(); + lineNum = static_cast(location.line()); + functionName = location.function_name(); +} +#else +inline void Exception::setDebugInformation(const char* file, int line, const char* func) +{ + fileName = file; + lineNum = line; + functionName = func; +} +#endif + +inline void Exception::setTranslatable(const bool translatable) +{ + isTranslatable = translatable; } #if defined(__GNUC__) && defined(FC_OS_LINUX) @@ -1014,11 +545,9 @@ public: private: static void throw_signal(int signum); -private: - // clang-format off - struct sigaction new_action {}, old_action {}; + struct sigaction new_action {}; // NOLINT (keep struct) + struct sigaction old_action {}; // NOLINT (keep struct) bool ok {false}; - // clang-format on }; #endif diff --git a/src/Base/Factory.cpp b/src/Base/Factory.cpp index c3967f43f2..35717b1110 100644 --- a/src/Base/Factory.cpp +++ b/src/Base/Factory.cpp @@ -99,7 +99,7 @@ const char* ScriptFactorySingleton::ProduceScript(const char* sScriptName) const if (!script) { #ifdef FC_DEBUG - Console().Warning("\"%s\" is not registered\n", sScriptName); + Console().warning("\"%s\" is not registered\n", sScriptName); #endif return ""; // no data } diff --git a/src/Base/Interpreter.cpp b/src/Base/Interpreter.cpp index de026dd469..6a27225b36 100644 --- a/src/Base/Interpreter.cpp +++ b/src/Base/Interpreter.cpp @@ -45,7 +45,7 @@ using namespace Base; PyException::PyException(const Py::Object& obj) { - _sErrMsg = obj.as_string(); + setMessage(obj.as_string()); // WARNING: we are assuming that python type object will never be // destroyed, so we don't keep reference here to save book-keeping in // our copy constructor and destructor @@ -64,7 +64,7 @@ PyException::PyException() std::string prefix = PP_last_error_type; /* exception name text */ std::string error = PP_last_error_info; /* exception data text */ - _sErrMsg = error; + setMessage(error); _errorType = prefix; // NOLINTNEXTLINE @@ -89,10 +89,10 @@ PyException::PyException() PyException::~PyException() noexcept = default; -void PyException::ThrowException() +void PyException::throwException() { PyException myexcp; - myexcp.ReportException(); + myexcp.reportException(); myexcp.raiseException(); } @@ -106,35 +106,35 @@ void PyException::raiseException() std::string exceptionname; if (_exceptionType == Base::PyExc_FC_FreeCADAbort) { - edict.setItem("sclassname", Py::String(typeid(Base::AbortException).name())); + edict.setItem("sclassname", Py::String(typeid(AbortException).name())); } - if (_isReported) { + if (getReported()) { edict.setItem("breported", Py::True()); } Base::ExceptionFactory::Instance().raiseException(edict.ptr()); } - if (_exceptionType == Base::PyExc_FC_FreeCADAbort) { - Base::AbortException exc(_sErrMsg.c_str()); - exc.setReported(_isReported); + if (_exceptionType == PyExc_FC_FreeCADAbort) { + AbortException exc(getMessage()); + exc.setReported(getReported()); throw exc; } throw *this; } -void PyException::ReportException() const +void PyException::reportException() const { - if (!_isReported) { - _isReported = true; + if (!getReported()) { + setReported(true); // set sys.last_vars to make post-mortem debugging work PyGILStateLocker locker; PySys_SetObject("last_traceback", PP_last_traceback); - Base::Console().DeveloperError("pyException", - "%s%s: %s\n", - _stackTrace.c_str(), - _errorType.c_str(), - what()); + Console().developerError("pyException", + "%s%s: %s\n", + _stackTrace.c_str(), + _errorType.c_str(), + what()); } } @@ -187,7 +187,7 @@ SystemExitException::SystemExitException() } } - _sErrMsg = errMsg; + setMessage(errMsg); _exitCode = errCode; } @@ -252,7 +252,7 @@ std::string InterpreterSingleton::runString(const char* sCmd) throw SystemExitException(); } - PyException::ThrowException(); + PyException::throwException(); return {}; // just to quieten code analyzers } @@ -296,7 +296,7 @@ std::string InterpreterSingleton::runStringWithKey(const char* psCmd, throw SystemExitException(); } - PyException::ThrowException(); + PyException::throwException(); return {}; // just to quieten code analyzers } Py_DECREF(presult); @@ -656,8 +656,8 @@ std::string InterpreterSingleton::init(int argc, char* argv[]) } return getPythonPath(); } - catch (const Base::Exception& e) { - e.ReportException(); + catch (const Exception& e) { + e.reportException(); throw; } } diff --git a/src/Base/Interpreter.h b/src/Base/Interpreter.h index e2196a3897..4ab7d0f993 100644 --- a/src/Base/Interpreter.h +++ b/src/Base/Interpreter.h @@ -104,7 +104,7 @@ public: /// this method determines if the original exception /// can be reconstructed or not, if yes throws the reconstructed version /// if not, throws a generic PyException. - static void ThrowException(); + static void throwException(); /// this function returns the stack trace const std::string& getStackTrace() const @@ -119,7 +119,7 @@ public: { return _exceptionType; } - void ReportException() const override; + void reportException() const override; /// Sets the Python error indicator and an error message void setPyException() const override; diff --git a/src/Base/Observer.h b/src/Base/Observer.h index ba94365bd0..f6ced06289 100644 --- a/src/Base/Observer.h +++ b/src/Base/Observer.h @@ -85,7 +85,7 @@ public: * and returns the name of the observer. Needed to use the Get * Method of the Subject. */ - virtual const char* Name() + virtual const char* name() { return nullptr; } @@ -122,7 +122,7 @@ public: virtual ~Subject() { if (_ObserverSet.size() > 0) { - Base::Console().DeveloperWarning(std::string("~Subject()"), + Base::Console().developerWarning(std::string("~Subject()"), "Not detached all observers yet\n"); } } @@ -139,7 +139,7 @@ public: size_t count = _ObserverSet.size(); _ObserverSet.insert(ToObserv); if (_ObserverSet.size() == count) { - Base::Console().DeveloperWarning(std::string("Subject::Attach"), + Base::Console().developerWarning(std::string("Subject::Attach"), "Observer %p already attached\n", static_cast(ToObserv)); } @@ -160,7 +160,7 @@ public: size_t count = _ObserverSet.size(); _ObserverSet.erase(ToObserv); if (_ObserverSet.size() == count) { - Base::Console().DeveloperWarning(std::string("Subject::Detach"), + Base::Console().developerWarning(std::string("Subject::Detach"), "Observer %p already detached\n", static_cast(ToObserv)); } @@ -184,17 +184,17 @@ public: (*Iter)->OnChange(*this, rcReason); // send OnChange-signal } catch (Base::Exception& e) { - Base::Console().Error("Unhandled Base::Exception caught when notifying observer.\n" + Base::Console().error("Unhandled Base::Exception caught when notifying observer.\n" "The error message is: %s\n", e.what()); } catch (std::exception& e) { - Base::Console().Error("Unhandled std::exception caught when notifying observer\n" + Base::Console().error("Unhandled std::exception caught when notifying observer\n" "The error message is: %s\n", e.what()); } catch (...) { - Base::Console().Error( + Base::Console().error( "Unhandled unknown exception caught in when notifying observer.\n"); } } @@ -210,7 +210,7 @@ public: for (typename std::set*>::iterator Iter = _ObserverSet.begin(); Iter != _ObserverSet.end(); ++Iter) { - OName = (*Iter)->Name(); // get the name + OName = (*Iter)->name(); // get the name if (OName && strcmp(OName, Name) == 0) { return *Iter; } diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index 9a7ca96709..980e0bd776 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -366,7 +366,7 @@ ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, != 0 && XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParameters").unicodeForm()) != 0) { - Base::Console().Warning("CreateElement: %s cannot have the element %s of type %s\n", + Base::Console().warning("CreateElement: %s cannot have the element %s of type %s\n", StrX(Start->getNodeName()).c_str(), Name, Type); @@ -1447,7 +1447,7 @@ ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, != 0 && XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParameters").unicodeForm()) != 0) { - Base::Console().Warning("FindElement: %s cannot have the element %s of type %s\n", + Base::Console().warning("FindElement: %s cannot have the element %s of type %s\n", StrX(Start->getNodeName()).c_str(), Name, Type); @@ -2082,7 +2082,7 @@ void ParameterManager::CheckDocument() const XercesDOMParser parser; Grammar* grammar = parser.loadGrammar(xsdFile, Grammar::SchemaGrammarType, true); if (!grammar) { - Base::Console().Error("Grammar file cannot be loaded.\n"); + Base::Console().error("Grammar file cannot be loaded.\n"); return; } @@ -2099,7 +2099,7 @@ void ParameterManager::CheckDocument() const parser.parse(xmlFile); if (parser.getErrorCount() > 0) { - Base::Console().Error("Unexpected XML structure detected: %zu errors\n", + Base::Console().error("Unexpected XML structure detected: %zu errors\n", parser.getErrorCount()); } } diff --git a/src/Base/ParameterPy.cpp b/src/Base/ParameterPy.cpp index 07483ef92e..2f000d80bd 100644 --- a/src/Base/ParameterPy.cpp +++ b/src/Base/ParameterPy.cpp @@ -82,7 +82,7 @@ public: } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } bool isEqual(const Py::Object& obj) const @@ -777,7 +777,7 @@ void ParameterGrpPy::tryCall(ParameterGrpObserver* obs, } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } } diff --git a/src/Base/PyObjectBase.cpp b/src/Base/PyObjectBase.cpp index a90ac36e88..daf17e75a8 100644 --- a/src/Base/PyObjectBase.cpp +++ b/src/Base/PyObjectBase.cpp @@ -68,7 +68,7 @@ PyObjectBase::PyObjectBase(void* voidp, PyTypeObject *T) #endif _Py_NewReference(this); #ifdef FC_LOGPYOBJECTS - Base::Console().Log("PyO+: %s (%p)\n",T->tp_name, this); + Base::Console().log("PyO+: %s (%p)\n",T->tp_name, this); #endif StatusBits.set(Valid); // valid, the second bit is NOT set, i.e. it's mutable StatusBits.set(Notify); @@ -79,7 +79,7 @@ PyObjectBase::~PyObjectBase() { PyGILStateLocker lock; #ifdef FC_LOGPYOBJECTS - Base::Console().Log("PyO-: %s (%p)\n",Py_TYPE(this)->tp_name, this); + Base::Console().log("PyO-: %s (%p)\n",Py_TYPE(this)->tp_name, this); #endif // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) if (baseProxy && reinterpret_cast(baseProxy)->baseobject == this) { @@ -462,7 +462,7 @@ PyObject *PyObjectBase::_repr() std::stringstream a; a << ""; # ifdef FCDebug - Console().Log("PyObjectBase::_repr() not overwritten representation!"); + Console().log("PyObjectBase::_repr() not overwritten representation!"); # endif return Py_BuildValue("s", a.str().c_str()); } diff --git a/src/Base/Quantity.cpp b/src/Base/Quantity.cpp index e5102dbb16..efa8c37a3c 100644 --- a/src/Base/Quantity.cpp +++ b/src/Base/Quantity.cpp @@ -26,14 +26,16 @@ #include #include #include +#include #endif #include -#include #include "Exception.h" #include "Quantity.h" +#include "Tools.h" #include "UnitsApi.h" +#include "UnitsSchema.h" /** \defgroup Units Units system \ingroup BASE @@ -50,7 +52,9 @@ #pragma warning(disable : 4335) // disable MAC file format warning on VC #endif -using namespace Base; +using Base::Quantity; +using Base::QuantityFormat; +using Base::UnitsSchema; // ====== Static attributes ========================= // NOLINTNEXTLINE @@ -60,7 +64,7 @@ int QuantityFormat::defaultDenominator = 8; // for 1/8" QuantityFormat::QuantityFormat() : option(OmitGroupSeparator | RejectGroupSeparator) , format(Fixed) - , precision(UnitsApi::getDecimals()) + , precision(static_cast(UnitsApi::getDecimals())) , denominator(defaultDenominator) {} @@ -237,6 +241,13 @@ Quantity Quantity::operator-() const return Quantity(-(this->myValue), this->myUnit); } +std::string Quantity::getUserString() const +{ + double dummy1 {}; // to satisfy GCC + std::string dummy2 {}; + return getUserString(dummy1, dummy2); +} + std::string Quantity::getUserString(double& factor, std::string& unitString) const { return Base::UnitsApi::schemaTranslate(*this, factor, unitString); @@ -245,20 +256,18 @@ std::string Quantity::getUserString(double& factor, std::string& unitString) con std::string Quantity::getUserString(UnitsSchema* schema, double& factor, std::string& unitString) const { - return schema->schemaTranslate(*this, factor, unitString); + return schema->translate(*this, factor, unitString); } std::string Quantity::getSafeUserString() const { - auto ret = getUserString(); - if (this->myValue) { - auto feedbackQty = parse(ret); - auto feedbackVal = feedbackQty.getValue(); - if (feedbackVal == 0) { - ret = fmt::format("{} {}", this->myValue, this->getUnit().getString()); - } + auto userStr = getUserString(); + if (myValue != 0.0 && parse(userStr).getValue() == 0) { + auto unitStr = getUnit().getString(); + userStr = fmt::format("{}{}{}", myValue, unitStr.empty() ? "" : " ", unitStr); } - return Base::Tools::escapeQuotesFromString(ret); + + return Tools::escapeQuotesFromString(userStr); } /// true if it has a number without a unit diff --git a/src/Base/Quantity.h b/src/Base/Quantity.h index ccfc33cb96..ed0f947ac9 100644 --- a/src/Base/Quantity.h +++ b/src/Base/Quantity.h @@ -156,14 +156,10 @@ public: { myFormat = fmt; } + + std::string getUserString() const; /// transfer to user preferred unit/potence std::string getUserString(double& factor, std::string& unitString) const; - std::string getUserString() const - { // to satisfy GCC - double dummy1 {}; - std::string dummy2 {}; - return getUserString(dummy1, dummy2); - } std::string getUserString(UnitsSchema* schema, double& factor, std::string& unitString) const; std::string getSafeUserString() const; diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index ce84681dfa..617b914046 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -22,7 +22,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include +#include +#include +#include +#include #endif #include "Unit.h" @@ -33,7 +38,7 @@ #include "UnitPy.h" -using namespace Base; +using Base::Quantity; // returns a string which represents the object e.g. when printed in python std::string QuantityPy::representation() const @@ -181,84 +186,128 @@ PyObject* QuantityPy::getUserPreferred(PyObject* /*args*/) const PyObject* QuantityPy::getValueAs(PyObject* args) const { - Quantity quant; - quant.setInvalid(); - - // first try Quantity - if (!quant.isValid()) { + auto tryQuantity = [&]() -> std::optional { PyObject* object {}; - if (PyArg_ParseTuple(args, "O!", &(QuantityPy::Type), &object)) { - quant = *static_cast(object)->getQuantityPtr(); + if (!PyArg_ParseTuple(args, "O!", &(QuantityPy::Type), &object)) { + return std::nullopt; } - } - if (!quant.isValid()) { + return *getQuantityPtr(); + }; + + auto tryUnit = [&]() -> std::optional { PyObject* object {}; - PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", &(UnitPy::Type), &object)) { - quant.setUnit(*static_cast(object)->getUnitPtr()); - quant.setValue(1.0); + if (!PyArg_ParseTuple(args, "O!", &(UnitPy::Type), &object)) { + return std::nullopt; } - } - if (!quant.isValid()) { + return Quantity {1.0, *static_cast(object)->getUnitPtr()}; + }; + + auto tryUnitAndValue = [&]() -> std::optional { PyObject* object {}; double value {}; - PyErr_Clear(); - if (PyArg_ParseTuple(args, "dO!", &value, &(UnitPy::Type), &object)) { - quant.setUnit(*static_cast(object)->getUnitPtr()); - quant.setValue(value); + if (!PyArg_ParseTuple(args, "dO!", &value, &(UnitPy::Type), &object)) { + return std::nullopt; } - } - if (!quant.isValid()) { + return Quantity {value, *static_cast(object)->getUnitPtr()}; + }; + + auto tryUnitPartsAndValue = [&]() -> std::optional { double f = std::numeric_limits::max(); - int i1 = 0; - int i2 = 0; - int i3 = 0; - int i4 = 0; - int i5 = 0; - int i6 = 0; - int i7 = 0; - int i8 = 0; + int i1 {0}; + int i2 {0}; + int i3 {0}; + int i4 {0}; + int i5 {0}; + int i6 {0}; + int i7 {0}; + int i8 {0}; PyErr_Clear(); - if (PyArg_ParseTuple(args, "d|iiiiiiii", &f, &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8)) { - if (f < std::numeric_limits::max()) { - quant = Quantity(f, - Unit {static_cast(i1), - static_cast(i2), - static_cast(i3), - static_cast(i4), - static_cast(i5), - static_cast(i6), - static_cast(i7), - static_cast(i8)}); + if (!PyArg_ParseTuple(args, "d|iiiiiiii", &f, &i1, &i2, &i3, &i4, &i5, &i6, &i7, &i8)) { + return std::nullopt; + } + + if (f >= std::numeric_limits::max()) { + return std::nullopt; + } + + auto re = [](auto val) { + return static_cast(val); + }; + + return Quantity {f, Unit {re(i1), re(i2), re(i3), re(i4), re(i5), re(i6), re(i7), re(i8)}}; + }; + + auto tryString = [&]() -> std::optional { + char* string {}; + if (!PyArg_ParseTuple(args, "et", "utf-8", &string)) { + return std::nullopt; + } + + const std::string str {string}; + PyMem_Free(string); + return Quantity::parse(str); + }; + + const std::vector()>> funcs = {tryQuantity, + tryUnit, + tryUnitAndValue, + tryUnitPartsAndValue, + tryString}; + + auto tryFuncs = [&]() -> std::optional { + for (const auto& func : funcs) { + PyErr_Clear(); + if (auto quant = func(); quant.has_value()) { + return quant; } } + return std::nullopt; + }; + + auto checkQuant = [&](const Quantity& quant) -> bool { + auto err = [&](const std::string& str) { + PyErr_SetString(PyExc_ValueError, str.c_str()); + }; + + const auto* qPtr = getQuantityPtr(); + if (!qPtr) { + err("QuantityPtr is null"); + return false; + } + + const auto qpUnit = qPtr->getUnit(); + if (qpUnit.isEmpty()) { + err("QuantityPtr returned empty unit"); + return false; + } + + if (const auto qUnit = quant.getUnit(); qUnit != qpUnit) { + err("Unit mismatch (`" + qUnit.getString() + "` != `" + qpUnit.getString() + "`)"); + return false; + } + + return true; + }; + + //---------------------------------------------------------------------------------------------- + + const auto optQuant = tryFuncs(); + if (!optQuant.has_value()) { + PyErr_SetString(PyExc_TypeError, "Expected quantity, string, float or unit"); + return nullptr; } - if (!quant.isValid()) { - PyErr_Clear(); - char* string {}; - if (PyArg_ParseTuple(args, "et", "utf-8", &string)) { - std::string str(string); - PyMem_Free(string); - quant = Quantity::parse(str); + const auto quant = optQuant.value(); + if (quant.isQuantity()) { + if (!checkQuant(quant)) { + return nullptr; } } - if (!quant.isValid()) { - PyErr_SetString(PyExc_TypeError, "Either quantity, string, float or unit expected"); - return nullptr; - } - - if (getQuantityPtr()->getUnit() != quant.getUnit() && quant.isQuantity()) { - PyErr_SetString(PyExc_ValueError, "Unit mismatch"); - return nullptr; - } - - quant = Quantity(getQuantityPtr()->getValueAs(quant)); - return new QuantityPy(new Quantity(quant)); + return new QuantityPy(new Quantity(getQuantityPtr()->getValue() / quant.getValue())); } PyObject* QuantityPy::__round__(PyObject* args) const diff --git a/src/Base/Reader.cpp b/src/Base/Reader.cpp index f9765d32e9..f2632e0664 100644 --- a/src/Base/Reader.cpp +++ b/src/Base/Reader.cpp @@ -440,7 +440,7 @@ void Base::XMLReader::readFiles(zipios::ZipInputStream& zipstream) const // less data than the file size would allow. // All what we need to do is to notify the user about the // failure. - Base::Console().Error("Reading failed from embedded file: %s\n", + Base::Console().error("Reading failed from embedded file: %s\n", entry->toString().c_str()); FailedFiles.push_back(jt->FileName); } diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index 63eb34245a..c86ed6a687 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -125,7 +125,7 @@ void Type::importModule(const char* typeName) // lets load the module Interpreter().loadModule(mod.c_str()); #ifdef FC_LOGLOADMODULE - Console().Log("Act: Module %s loaded through class %s \n", Mod.c_str(), typeName); + Console().log("Act: Module %s loaded through class %s \n", Mod.c_str(), typeName); #endif loadModuleSet.insert(mod); } diff --git a/src/Base/Type.h b/src/Base/Type.h index 0527a493c8..ed7599c83b 100644 --- a/src/Base/Type.h +++ b/src/Base/Type.h @@ -63,7 +63,7 @@ struct TypeData; // do something.. } else { - Base::Console().Warning("getRightFeature", "Unknown feature type %s!\n", + Base::Console().warning("getRightFeature", "Unknown feature type %s!\n", anode->getTypeId().getName()); } } diff --git a/src/Base/UnitsApi.cpp b/src/Base/UnitsApi.cpp index 0cf3133d0e..41328297fd 100644 --- a/src/Base/UnitsApi.cpp +++ b/src/Base/UnitsApi.cpp @@ -20,124 +20,91 @@ * * ***************************************************************************/ - #include "PreCompiled.h" - -#include +#ifndef _PreComp_ #include -#include +#include +#endif #include #include -#include + #include "Exception.h" - #include "UnitsApi.h" -#include "UnitsSchemaCentimeters.h" -#include "UnitsSchemaInternal.h" -#include "UnitsSchemaImperial1.h" -#include "UnitsSchemaMKS.h" -#include "UnitsSchemaMmMin.h" -#include "UnitsSchemaFemMilliMeterNewton.h" -#include "UnitsSchemaMeterDecimal.h" +#include "UnitsSchema.h" +#include "UnitsSchemas.h" +#include "UnitsSchemasData.h" -using namespace Base; +using Base::UnitsApi; +using Base::UnitsSchema; +using Base::UnitsSchemas; -// === static attributes ================================================ - -UnitsSchemaPtr UnitsApi::UserPrefSystem(new UnitsSchemaInternal()); -UnitSystem UnitsApi::currentSystem = UnitSystem::SI1; - -int UnitsApi::UserPrefDecimals = 2; - -QString UnitsApi::getDescription(UnitSystem system) +void UnitsApi::init() { - switch (system) { - case UnitSystem::SI1: - return tr("Standard (mm, kg, s, °)"); - case UnitSystem::SI2: - return tr("MKS (m, kg, s, °)"); - case UnitSystem::Imperial1: - return tr("US customary (in, lb)"); - case UnitSystem::ImperialDecimal: - return tr("Imperial decimal (in, lb)"); - case UnitSystem::Centimeters: - return tr("Building Euro (cm, m², m³)"); - case UnitSystem::ImperialBuilding: - return tr("Building US (ft-in, sqft, cft)"); - case UnitSystem::MmMin: - return tr("Metric small parts & CNC (mm, mm/min)"); - case UnitSystem::ImperialCivil: - return tr("Imperial for Civil Eng (ft, ft/s)"); - case UnitSystem::FemMilliMeterNewton: - return tr("FEM (mm, N, s)"); - case UnitSystem::MeterDecimal: - return tr("Meter decimal (m, m², m³)"); - default: - return tr("Unknown schema"); - } + schemas = std::make_unique(UnitsSchemasData::unitSchemasDataPack); } -UnitsSchemaPtr UnitsApi::createSchema(UnitSystem system) +std::vector UnitsApi::getDescriptions() { - switch (system) { - case UnitSystem::SI1: - return std::make_unique(); - case UnitSystem::SI2: - return std::make_unique(); - case UnitSystem::Imperial1: - return std::make_unique(); - case UnitSystem::ImperialDecimal: - return std::make_unique(); - case UnitSystem::Centimeters: - return std::make_unique(); - case UnitSystem::ImperialBuilding: - return std::make_unique(); - case UnitSystem::MmMin: - return std::make_unique(); - case UnitSystem::ImperialCivil: - return std::make_unique(); - case UnitSystem::FemMilliMeterNewton: - return std::make_unique(); - case UnitSystem::MeterDecimal: - return std::make_unique(); - default: - break; - } - - return nullptr; + return schemas->descriptions(); } -void UnitsApi::setSchema(UnitSystem system) +std::vector UnitsApi::getNames() { - if (UserPrefSystem) { - UserPrefSystem->resetSchemaUnits(); // for schemas changed the Quantity constants - } - - UserPrefSystem = createSchema(system); - currentSystem = system; - - // for wrong value fall back to standard schema - if (!UserPrefSystem) { - UserPrefSystem = std::make_unique(); - currentSystem = UnitSystem::SI1; - } - - UserPrefSystem->setSchemaUnits(); // if necessary a unit schema can change the constants in - // Quantity (e.g. mi=1.8km rather then 1.6km). + return schemas->names(); } -std::string UnitsApi::toString(const Base::Quantity& quantity, const QuantityFormat& format) +std::size_t UnitsApi::count() +{ + return static_cast(schemas->count()); +} + +bool UnitsApi::isMultiUnitAngle() +{ + return schemas->currentSchema()->isMultiUnitAngle(); +} + +bool UnitsApi::isMultiUnitLength() +{ + return schemas->currentSchema()->isMultiUnitLength(); +} + +std::string UnitsApi::getBasicLengthUnit() +{ + return schemas->currentSchema()->getBasicLengthUnit(); +} + +std::size_t UnitsApi::getFractDenominator() +{ + return schemas->defFractDenominator(); +} + +std::unique_ptr UnitsApi::createSchema(const std::size_t num) +{ + return std::make_unique(schemas->spec(num)); +} + +void UnitsApi::setSchema(const std::string& name) +{ + schemas->select(name); +} + +void UnitsApi::setSchema(const size_t num) +{ + schemas->select(num); +} + +std::string UnitsApi::toString(const Quantity& quantity, const QuantityFormat& format) { return fmt::format("'{} {}'", toNumber(quantity, format), quantity.getUnit().getString()); } -std::string UnitsApi::toNumber(const Base::Quantity& quantity, const QuantityFormat& format) +std::string UnitsApi::toNumber(const Quantity& quantity, const QuantityFormat& format) { return toNumber(quantity.getValue(), format); } -std::string UnitsApi::toNumber(double value, const QuantityFormat& format) +std::string UnitsApi::toNumber(const double value, const QuantityFormat& format) { std::stringstream ss; @@ -156,31 +123,6 @@ std::string UnitsApi::toNumber(double value, const QuantityFormat& format) return ss.str(); } -// return true if the current user schema uses multiple units for length (ex. Ft/In) -bool UnitsApi::isMultiUnitLength() -{ - return UserPrefSystem->isMultiUnitLength(); -} - -// return true if the current user schema uses multiple units for angles (ex. DMS) -bool UnitsApi::isMultiUnitAngle() -{ - return UserPrefSystem->isMultiUnitAngle(); -} - -std::string UnitsApi::getBasicLengthUnit() -{ - return UserPrefSystem->getBasicLengthUnit(); -} - -// === static translation methods ========================================== - -std::string -UnitsApi::schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) -{ - return UserPrefSystem->schemaTranslate(quant, factor, unitString); -} - double UnitsApi::toDouble(PyObject* args, const Base::Unit& u) { if (PyUnicode_Check(args)) { @@ -203,34 +145,30 @@ double UnitsApi::toDouble(PyObject* args, const Base::Unit& u) throw Base::UnitsMismatchError("Wrong parameter type!"); } -Quantity UnitsApi::toQuantity(PyObject* args, const Base::Unit& u) +std::string +UnitsApi::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) { - double d {}; - if (PyUnicode_Check(args)) { - std::string str(PyUnicode_AsUTF8(args)); - // Parse the string - Quantity q = Quantity::parse(str); - d = q.getValue(); - } - else if (PyFloat_Check(args)) { - d = PyFloat_AsDouble(args); - } - else if (PyLong_Check(args)) { - d = static_cast(PyLong_AsLong(args)); - } - else { - throw Base::UnitsMismatchError("Wrong parameter type!"); - } - - return Quantity(d, u); + return schemas->currentSchema()->translate(quant, factor, unitString); } -void UnitsApi::setDecimals(int prec) +std::string UnitsApi::schemaTranslate(const Quantity& quant) { - UserPrefDecimals = prec; + double dummy1 {}; // to satisfy GCC + std::string dummy2; + return schemas->currentSchema()->translate(quant, dummy1, dummy2); } -int UnitsApi::getDecimals() +void UnitsApi::setDecimals(const std::size_t prec) { - return UserPrefDecimals; + decimals = prec; +} + +size_t UnitsApi::getDecimals() +{ + return decimals; +} + +size_t UnitsApi::getDefDecimals() +{ + return schemas->getDecimals(); } diff --git a/src/Base/UnitsApi.h b/src/Base/UnitsApi.h index 3a0b7e19f8..d5a6d95af3 100644 --- a/src/Base/UnitsApi.h +++ b/src/Base/UnitsApi.h @@ -20,13 +20,12 @@ * * ***************************************************************************/ - #ifndef BASE_UNITSAPI_H #define BASE_UNITSAPI_H -#include -#include #include "UnitsSchema.h" +#include "UnitsSchemas.h" +#include "UnitsSchemasData.h" #include "Quantity.h" @@ -37,96 +36,71 @@ using PyMethodDef = struct PyMethodDef; namespace Base { -using UnitsSchemaPtr = std::unique_ptr; -/** - * The UnitsApi - */ + class BaseExport UnitsApi { - Q_DECLARE_TR_FUNCTIONS(UnitsApi) - public: - /** set Schema - * set the UnitsSchema of the Application - * this a represented by a class of type UnitSchema which - * defines a set of standard units for that schema and rules - * for representative strings. - */ - static void setSchema(UnitSystem s); - /// return the active schema - static UnitSystem getSchema() - { - return currentSystem; - } - /// Returns a brief description of a schema - static QString getDescription(UnitSystem); + static void init(); + static std::unique_ptr createSchema(std::size_t num); + static void setSchema(const std::string& name); + static void setSchema(std::size_t num); static std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString); - static std::string schemaTranslate(const Base::Quantity& quant) - { // to satisfy GCC - double dummy1 {}; - std::string dummy2; - return UnitsApi::schemaTranslate(quant, dummy1, dummy2); - } + schemaTranslate(const Quantity& quant, double& factor, std::string& unitString); - /** Get a number as string for a quantity of a given format. - * The string is a number in C locale (i.e. the decimal separator is always a dot) and if - * needed represented in scientific notation. The string also includes the unit of the quantity. - */ - static std::string toString(const Base::Quantity& q, - const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); - /** Get a number as string for a quantity of a given format. - * The string is a number in C locale (i.e. the decimal separator is always a dot) and if - * needed represented in scientific notation. The string doesn't include the unit of the - * quantity. - */ - static std::string toNumber(const Base::Quantity& q, - const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); - /** Get a number as string for a double of a given format. - * The string is a number in C locale (i.e. the decimal separator is always a dot) and if - * needed represented in scientific notation. The string doesn't include the unit of the - * quantity. - */ - static std::string toNumber(double value, - const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); + static std::string schemaTranslate(const Quantity& quant); + + /** + * toString & toNumber: + * Quantity to string. Optionally apply format + * The string is a number in C locale (i.e. the decimal separator is always a dot) + * Scientific notation (if needed). + */ + + /** INCLUDES unit */ + static std::string + toString(const Quantity& quantity, + const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)); + + /** Does NOT include unit */ + static std::string + toNumber(const Quantity& quantity, + const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)); + + /** Does NOT include unit */ + static std::string + toNumber(double value, const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)); - /// generate a value for a quantity with default user preferred system static double toDouble(PyObject* args, const Base::Unit& u = Base::Unit()); - /// generate a value for a quantity with default user preferred system - static Quantity toQuantity(PyObject* args, const Base::Unit& u = Base::Unit()); - // set the number of decimals - static void setDecimals(int); - // get the number of decimals - static int getDecimals(); - //@} + static void setDecimals(std::size_t); + static std::size_t getDecimals(); + static std::size_t getDefDecimals(); - // double Result; + static std::vector getDescriptions(); + static std::vector getNames(); - // return true if the current user schema uses multiple units for length (ex. Ft/In) - static bool isMultiUnitLength(); + static std::size_t count(); - // return true if the current user schema uses multiple units for angles (ex. DMS) static bool isMultiUnitAngle(); - - // return the basic unit of measure for length in the current user schema. + static bool isMultiUnitLength(); static std::string getBasicLengthUnit(); + static std::size_t getFractDenominator(); + static std::size_t getDefSchemaNum() + { + return schemas->spec().num; + } // Python interface static PyMethodDef Methods[]; - /// return an instance of the given enum value - static UnitsSchemaPtr createSchema(UnitSystem s); - protected: - static UnitsSchemaPtr UserPrefSystem; - static UnitSystem currentSystem; - /// number of decimals for floats - static int UserPrefDecimals; + static inline auto schemas = + std::make_unique(UnitsSchemasData::unitSchemasDataPack); + static inline std::size_t decimals {2}; + static inline std::size_t denominator {2}; -protected: // the python API wrapper methods static PyObject* sParseQuantity(PyObject* self, PyObject* args); static PyObject* sListSchemas(PyObject* self, PyObject* args); @@ -138,5 +112,4 @@ protected: } // namespace Base - #endif // BASE_UNITSAPI_H diff --git a/src/Base/UnitsApiPy.cpp b/src/Base/UnitsApiPy.cpp index 730d915f43..f6a0d49870 100644 --- a/src/Base/UnitsApiPy.cpp +++ b/src/Base/UnitsApiPy.cpp @@ -20,9 +20,7 @@ * * ***************************************************************************/ - #include "PreCompiled.h" - #ifndef _PreComp_ #include #endif @@ -39,10 +37,9 @@ using namespace Base; //************************************************************************** // Python stuff of UnitsApi -// UnitsApi Methods PyMethodDef UnitsApi::Methods[] = { {"parseQuantity", - UnitsApi::sParseQuantity, + sParseQuantity, METH_VARARGS, "parseQuantity(string) -> Base.Quantity()\n\n" "calculate a mathematical expression with units to a quantity object. \n" @@ -51,27 +48,27 @@ PyMethodDef UnitsApi::Methods[] = { "or for more complex espressions:\n" "parseQuantity('sin(pi)/50.0 m/s^2')\n"}, {"listSchemas", - UnitsApi::sListSchemas, + sListSchemas, METH_VARARGS, "listSchemas() -> a tuple of schemas\n\n" "listSchemas(int) -> description of the given schema\n\n"}, {"getSchema", - UnitsApi::sGetSchema, + sGetSchema, METH_VARARGS, "getSchema() -> int\n\n" "The int is the position of the tuple returned by listSchemas"}, {"setSchema", - UnitsApi::sSetSchema, + sSetSchema, METH_VARARGS, "setSchema(int) -> None\n\n" "Sets the current schema to the given number, if possible"}, {"schemaTranslate", - UnitsApi::sSchemaTranslate, + sSchemaTranslate, METH_VARARGS, "schemaTranslate(Quantity, int) -> tuple\n\n" "Translate a quantity to a given schema"}, {"toNumber", - UnitsApi::sToNumber, + sToNumber, METH_VARARGS, "toNumber(Quantity or float, [format='g', decimals=-1]) -> str\n\n" "Convert a quantity or float to a string"}, @@ -86,30 +83,32 @@ PyObject* UnitsApi::sParseQuantity(PyObject* /*self*/, PyObject* args) return nullptr; } - Quantity rtn; - std::string str(pstr); + const std::string str {pstr}; PyMem_Free(pstr); try { - rtn = Quantity::parse(str); + return new QuantityPy(new Quantity(Quantity::parse(str))); } - catch (const Base::ParserError&) { - PyErr_Format(PyExc_ValueError, "invalid unit expression \n"); + catch (const ParserError&) { + PyErr_Format(PyExc_ValueError, + "invalid unit expression: '%s'\n", + std::string {pstr}.c_str()); return nullptr; } - - return new QuantityPy(new Quantity(rtn)); } PyObject* UnitsApi::sListSchemas(PyObject* /*self*/, PyObject* args) { + auto names = UnitsApi::getNames(); + const int num = static_cast(names.size()); + if (PyArg_ParseTuple(args, "")) { - int num = static_cast(UnitSystem::NumUnitSystemTypes); - Py::Tuple tuple(num); - for (int i = 0; i < num; i++) { - const auto description { - UnitsApi::getDescription(static_cast(i)).toStdString()}; - tuple.setItem(i, Py::String(description.c_str())); - } + Py::Tuple tuple {num}; + + auto addItem = [&, i {0}](const std::string& name) mutable { + tuple.setItem(i++, Py::String {name.c_str()}); + }; + + std::for_each(names.begin(), names.end(), addItem); return Py::new_reference_to(tuple); } @@ -117,14 +116,12 @@ PyObject* UnitsApi::sListSchemas(PyObject* /*self*/, PyObject* args) PyErr_Clear(); int index {}; if (PyArg_ParseTuple(args, "i", &index)) { - int num = static_cast(UnitSystem::NumUnitSystemTypes); if (index < 0 || index >= num) { PyErr_SetString(PyExc_ValueError, "invalid schema value"); return nullptr; } - const auto description { - UnitsApi::getDescription(static_cast(index)).toStdString()}; + const auto description = schemas->descriptions().at(index); return Py_BuildValue("s", description.c_str()); } @@ -138,20 +135,21 @@ PyObject* UnitsApi::sGetSchema(PyObject* /*self*/, PyObject* args) return nullptr; } - return Py_BuildValue("i", static_cast(currentSystem)); + return Py_BuildValue("i", count()); } PyObject* UnitsApi::sSetSchema(PyObject* /*self*/, PyObject* args) { PyErr_Clear(); int index {}; - if (PyArg_ParseTuple(args, "i", &index)) { - int num = static_cast(UnitSystem::NumUnitSystemTypes); - if (index < 0 || index >= num) { + if (PyArg_ParseTuple(args, "i", &index) != 0) { + + if (index < 0 || index >= static_cast(count())) { PyErr_SetString(PyExc_ValueError, "invalid schema value"); return nullptr; } - setSchema(static_cast(index)); + + schemas->select(index); } Py_Return; } @@ -160,27 +158,26 @@ PyObject* UnitsApi::sSchemaTranslate(PyObject* /*self*/, PyObject* args) { PyObject* py {}; int index {}; - if (!PyArg_ParseTuple(args, "O!i", &(QuantityPy::Type), &py, &index)) { + if (!PyArg_ParseTuple(args, "O!i", &QuantityPy::Type, &py, &index)) { return nullptr; } - Quantity quant; - quant = *static_cast(py)->getQuantityPtr(); - - std::unique_ptr schema(createSchema(static_cast(index))); - if (!schema) { - PyErr_SetString(PyExc_ValueError, "invalid schema value"); + if (index < 0 || index >= static_cast(count())) { + PyErr_SetString(PyExc_ValueError, + std::string {"invalid schema index:" + std::to_string(index)}.c_str()); return nullptr; } + const Quantity quant {*static_cast(py)->getQuantityPtr()}; + double factor {}; - std::string uus; - std::string uss = schema->schemaTranslate(quant, factor, uus); + std::string unitStr; + const std::string unitStrLocalised = schemaTranslate(quant, factor, unitStr); - Py::Tuple res(3); - res[0] = Py::String(uss, "utf-8"); - res[1] = Py::Float(factor); - res[2] = Py::String(uus, "utf-8"); + Py::Tuple res {3}; + res[0] = Py::String {unitStrLocalised, "utf-8"}; + res[1] = Py::Float {factor}; + res[2] = Py::String {unitStr, "utf-8"}; return Py::new_reference_to(res); } diff --git a/src/Base/UnitsSchema.cpp b/src/Base/UnitsSchema.cpp index bb544f3259..c576d65919 100644 --- a/src/Base/UnitsSchema.cpp +++ b/src/Base/UnitsSchema.cpp @@ -1,49 +1,142 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#include "PreCompiled.h" -#ifdef __GNUC__ -#include -#endif - -#include -#include - -#include "Quantity.h" -#include "UnitsSchema.h" - -using namespace Base; - -std::string UnitsSchema::toLocale(const Base::Quantity& quant, - double factor, - const std::string& unitString) const -{ - QLocale Lc; - const QuantityFormat& format = quant.getFormat(); - if (format.option != QuantityFormat::None) { - int opt = format.option; - Lc.setNumberOptions(static_cast(opt)); - } - - QString Ln = Lc.toString((quant.getValue() / factor), format.toFormat(), format.precision); - return QStringLiteral("%1 %2").arg(Ln, QString::fromStdString(unitString)).toStdString(); -} +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#include "PreCompiled.h" + +#include +#include +#include + +#include +#include + +#include "Quantity.h" +#include "UnitsSchema.h" +#include "UnitsSchemasData.h" +#include "UnitsSchemasSpecs.h" +#include "Exception.h" +#include "Quantity.h" + +using Base::UnitsSchema; +using Base::UnitsSchemaSpec; + + +UnitsSchema::UnitsSchema(UnitsSchemaSpec spec) + : spec {std::move(spec)} +{} + +std::string UnitsSchema::translate(const Quantity& quant) const +{ // to satisfy GCC + double dummy1 {}; + std::string dummy2; + return translate(quant, dummy1, dummy2); +} + +std::string +UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitString) const +{ + if (spec.translationSpecs.empty()) { + return toLocale(quant, 1.0, unitString); + } + + const auto unitName = quant.getUnit().getTypeString(); + + if (spec.translationSpecs.count(unitName) == 0) { + // no schema-level translation. Use defaults. + factor = 1.0; + unitString = quant.getUnit().getString(); + + return toLocale(quant, factor, unitString); + } + + const auto value = quant.getValue(); + + auto isSuitable = [&](const UnitTranslationSpec& row) { + return row.threshold > value || row.threshold == 0; // zero indicates default + }; + + auto unitSpecs = spec.translationSpecs.at(unitName); + const auto unitSpec = std::find_if(unitSpecs.begin(), unitSpecs.end(), isSuitable); + if (unitSpec == unitSpecs.end()) { + throw RuntimeError("Suitable threshhold not found. Schema: " + spec.name + + " value: " + std::to_string(value)); + } + + if (unitSpec->factor == 0) { + return UnitsSchemasData::runSpecial(unitSpec->unitString, value); + } + + factor = unitSpec->factor; + unitString = unitSpec->unitString; + + return toLocale(quant, factor, unitString); +} + +std::string +UnitsSchema::toLocale(const Quantity& quant, const double factor, const std::string& unitString) +{ + QLocale Lc; + const QuantityFormat& format = quant.getFormat(); + if (format.option != QuantityFormat::None) { + int opt = format.option; + Lc.setNumberOptions(static_cast(opt)); + } + + std::string valueString = + Lc.toString((quant.getValue() / factor), format.toFormat(), format.precision).toStdString(); + + return fmt::format( + "{}{}{}", + valueString, + unitString.empty() || unitString == "°" || unitString == "″" || unitString == "′" ? "" + : " ", + unitString); +} + +bool UnitsSchema::isMultiUnitLength() const +{ + return spec.isMultUnitLen; +} + +bool UnitsSchema::isMultiUnitAngle() const +{ + return spec.isMultUnitAngle; +} + +std::string UnitsSchema::getBasicLengthUnit() const +{ + return spec.basicLengthUnitStr; +} + +std::string UnitsSchema::getName() const +{ + return spec.name; +} + +std::string UnitsSchema::getDescription() const +{ + return spec.description; +} + +int UnitsSchema::getNum() const +{ + return static_cast(spec.num); +} diff --git a/src/Base/UnitsSchema.h b/src/Base/UnitsSchema.h index 117b46e86a..6587d5359b 100644 --- a/src/Base/UnitsSchema.h +++ b/src/Base/UnitsSchema.h @@ -24,78 +24,41 @@ #define BASE_UNITSSCHEMA_H #include +#include + +#include "UnitsSchemasSpecs.h" +#include "Base/Quantity.h" namespace Base { class Quantity; -/** Units systems */ -enum class UnitSystem -{ - SI1 = 0, /** internal (mm,kg,s) SI system - (http://en.wikipedia.org/wiki/International_System_of_Units) */ - SI2 = 1, /** MKS (m,kg,s) SI system */ - Imperial1 = 2, /** the Imperial system (http://en.wikipedia.org/wiki/Imperial_units) */ - ImperialDecimal = 3, /** Imperial with length in inch only */ - Centimeters = 4, /** All lengths in centimeters, areas and volumes in square/cubic meters */ - ImperialBuilding = 5, /** All lengths in feet + inches + fractions */ - MmMin = 6, /** Lengths in mm, Speed in mm/min. Angle in degrees. Useful for small parts & CNC */ - ImperialCivil = 7, /** Lengths in ft, Speed in ft/s. Used in Civil Eng in North America */ - FemMilliMeterNewton = 8, /** Lengths in mm, Mass in t, TimeSpan in s, thus force is in N */ - MeterDecimal = 9, /** Lengths in metres always */ - NumUnitSystemTypes // must be the last item! -}; - - -/** The UnitSchema class - * The subclasses of this class define the stuff for a - * certain units schema. +/** + * An individual schema object */ class UnitsSchema { public: - UnitsSchema() = default; - UnitsSchema(const UnitsSchema&) = default; - UnitsSchema(UnitsSchema&&) = default; - UnitsSchema& operator=(const UnitsSchema&) = default; - UnitsSchema& operator=(UnitsSchema&&) = default; - virtual ~UnitsSchema() = default; - /** Gets called if this schema gets activated. - * Here it's theoretically possible that you can change the static factors - * for certain units (e.g. mi = 1,8km instead of mi=1.6km). - */ - virtual void setSchemaUnits() - {} - /// If you use setSchemaUnits() you also have to impment this method to undo your changes! - virtual void resetSchemaUnits() - {} + explicit UnitsSchema(UnitsSchemaSpec spec); + UnitsSchema() = delete; - /// This method translates the quantity in a string as the user may expect it. - virtual std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) = 0; + [[nodiscard]] bool isMultiUnitLength() const; + [[nodiscard]] bool isMultiUnitAngle() const; + [[nodiscard]] std::string getBasicLengthUnit() const; + [[nodiscard]] std::string getName() const; + [[nodiscard]] std::string getDescription() const; + [[nodiscard]] int getNum() const; - std::string - toLocale(const Base::Quantity& quant, double factor, const std::string& unitString) const; + std::string translate(const Quantity& quant) const; + std::string translate(const Quantity& quant, double& factor, std::string& unitString) const; - // return true if this schema uses multiple units for length (ex. Ft/In) - virtual bool isMultiUnitLength() const - { - return false; - } +private: + [[nodiscard]] static std::string + toLocale(const Quantity& quant, double factor, const std::string& unitString); - // return true if this schema uses multiple units for angles (ex. DMS) - virtual bool isMultiUnitAngle() const - { - return false; - } - - // return the basic length unit for this schema - virtual std::string getBasicLengthUnit() const - { - return {"mm"}; - } + UnitsSchemaSpec spec; }; -} // namespace Base +} // namespace Base #endif // BASE_UNITSSCHEMA_H diff --git a/src/Base/UnitsSchemaCentimeters.cpp b/src/Base/UnitsSchemaCentimeters.cpp deleted file mode 100644 index f1b45119ca..0000000000 --- a/src/Base/UnitsSchemaCentimeters.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2016 Yorik van Havre * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#include -#endif - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaCentimeters.h" - -using namespace Base; - -std::string UnitsSchemaCentimeters::schemaTranslate(const Base::Quantity& quant, - double& factor, - std::string& unitString) -{ - static std::array>, 7> unitSpecs {{ - {Unit::Length, {"cm", 10.0}}, - {Unit::Area, {"m^2", 1000000.0}}, - {Unit::Volume, {"m^3", 1000000000.0}}, - {Unit::Power, {"W", 1000000.0}}, - {Unit::ElectricPotential, {"V", 1000000.0}}, - {Unit::HeatFlux, {"W/m^2", 1.0}}, - {Unit::Velocity, {"mm/min", 1.0 / 60}}, - }}; - - const auto unit = quant.getUnit(); - const auto spec = std::find_if(unitSpecs.begin(), unitSpecs.end(), [&](const auto& pair) { - return pair.first == unit; - }); - - if (spec != std::end(unitSpecs)) { - unitString = spec->second.first; - factor = spec->second.second; - } - else { - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaCentimeters.h b/src/Base/UnitsSchemaCentimeters.h deleted file mode 100644 index afe555bb3e..0000000000 --- a/src/Base/UnitsSchemaCentimeters.h +++ /dev/null @@ -1,48 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2016 Yorik van Havre * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMACENTIMETERS_H -#define BASE_UNITSSCHEMACENTIMETERS_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/** - * The UnitSchema class - */ -class UnitsSchemaCentimeters: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - - std::string getBasicLengthUnit() const override - { - return {"cm"}; - } -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMACENTIMETERS_H diff --git a/src/Base/UnitsSchemaFemMilliMeterNewton.cpp b/src/Base/UnitsSchemaFemMilliMeterNewton.cpp deleted file mode 100644 index 602f825304..0000000000 --- a/src/Base/UnitsSchemaFemMilliMeterNewton.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * Copyright (c) 2020 Bernd Hahnebach * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#include -#endif - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaFemMilliMeterNewton.h" - -using namespace Base; - -std::string UnitsSchemaFemMilliMeterNewton::schemaTranslate(const Quantity& quant, - double& factor, - std::string& unitString) -{ - static std::array>, 2> unitSpecs {{ - {Unit::Length, {"mm", 1.0}}, - {Unit::Mass, {"t", 1e3}}, - }}; - - const auto unit = quant.getUnit(); - const auto spec = std::find_if(unitSpecs.begin(), unitSpecs.end(), [&](const auto& pair) { - return pair.first == unit; - }); - - if (spec != std::end(unitSpecs)) { - unitString = spec->second.first; - factor = spec->second.second; - } - else { - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaFemMilliMeterNewton.h b/src/Base/UnitsSchemaFemMilliMeterNewton.h deleted file mode 100644 index 313139b17f..0000000000 --- a/src/Base/UnitsSchemaFemMilliMeterNewton.h +++ /dev/null @@ -1,47 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * Copyright (c) 2020 Bernd Hahnebach * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMAFEMMLLIMETERNEWTON_H -#define BASE_UNITSSCHEMAFEMMLLIMETERNEWTON_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/* Milli metric / Newton / Seconds unit schema for use in FEM. - * Lengths are always in mm. - * Mass is in t. - * TimeSpann in S. - * Thus the Force is in Newton - */ -class UnitsSchemaFemMilliMeterNewton: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAFEMMLLIMETERNEWTON_H diff --git a/src/Base/UnitsSchemaImperial1.cpp b/src/Base/UnitsSchemaImperial1.cpp deleted file mode 100644 index 49f36e322f..0000000000 --- a/src/Base/UnitsSchemaImperial1.cpp +++ /dev/null @@ -1,400 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#include -#endif -#ifdef __GNUC__ -#include -#endif - -#include "Quantity.h" -#include "UnitsSchemaImperial1.h" - -using namespace Base; - -std::string UnitsSchemaImperial1::schemaTranslate(const Quantity& quant, - double& factor, - std::string& unitString) -{ - double UnitValue = std::abs(quant.getValue()); - Unit unit = quant.getUnit(); - // for imperial user/programmer mind; UnitValue is in internal system, that means - // mm/kg/s. And all combined units have to be calculated from there! - - // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - if (UnitValue < 0.00000254) { // smaller then 0.001 thou -> inch and scientific notation - unitString = "in"; - factor = 25.4; - } - else if (UnitValue < 2.54) { // smaller then 0.1 inch -> Thou (mil) - unitString = "thou"; - factor = 0.0254; - } - else if (UnitValue < 304.8) { - unitString = "\""; - factor = 25.4; - } - else if (UnitValue < 914.4) { - unitString = "\'"; - factor = 304.8; - } - else if (UnitValue < 1609344.0) { - unitString = "yd"; - factor = 914.4; - } - else if (UnitValue < 1609344000.0) { - unitString = "mi"; - factor = 1609344.0; - } - else { // bigger then 1000 mi -> scientific notation - unitString = "in"; - factor = 25.4; - } - } - else if (unit == Unit::Angle) { - unitString = "\xC2\xB0"; - factor = 1.0; - } - else if (unit == Unit::Area) { - // TODO: Cascade for the Areas - // default action for all cases without special treatment: - unitString = "in^2"; - factor = 645.16; - } - else if (unit == Unit::Volume) { - // TODO: Cascade for the Volume - // default action for all cases without special treatment: - unitString = "in^3"; - factor = 16387.064; - } - else if (unit == Unit::Mass) { - // TODO: Cascade for the weights - // default action for all cases without special treatment: - unitString = "lb"; - factor = 0.45359237; - } - else if (unit == Unit::Pressure) { - if (UnitValue < 6894.744) { // psi is the smallest - unitString = "psi"; - factor = 6.894744825494; - } - else if (UnitValue < 6894744.825) { - unitString = "ksi"; - factor = 6894.744825494; - } - else { // bigger then 1000 ksi -> psi + scientific notation - unitString = "psi"; - factor = 6.894744825494; - } - } - else if (unit == Unit::Stiffness) { // Conversion to lbf/in - unitString = "lbf/in"; - factor = 4.448222 / 0.0254; - } - else if (unit == Unit::Velocity) { - unitString = "in/min"; - factor = 25.4 / 60; - } - else { - // default action for all cases without special treatment: - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} - -std::string UnitsSchemaImperialDecimal::schemaTranslate(const Base::Quantity& quant, - double& factor, - std::string& unitString) -{ - Unit unit = quant.getUnit(); - // for imperial user/programmer mind; UnitValue is in internal system, that means - // mm/kg/s. And all combined units have to be calculated from there! - - // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - unitString = "in"; - factor = 25.4; - } - else if (unit == Unit::Angle) { - unitString = "\xC2\xB0"; - factor = 1.0; - } - else if (unit == Unit::Area) { - // TODO: Cascade for the Areas - // default action for all cases without special treatment: - unitString = "in^2"; - factor = 645.16; - } - else if (unit == Unit::Volume) { - // TODO: Cascade for the Volume - // default action for all cases without special treatment: - unitString = "in^3"; - factor = 16387.064; - } - else if (unit == Unit::Mass) { - // TODO: Cascade for the weights - // default action for all cases without special treatment: - unitString = "lb"; - factor = 0.45359237; - } - else if (unit == Unit::Pressure) { - unitString = "psi"; - factor = 6.894744825494; - } - else if (unit == Unit::Stiffness) { - unitString = "lbf/in"; - factor = 4.448222 / 0.0254; - } - else if (unit == Unit::Velocity) { - unitString = "in/min"; - factor = 25.4 / 60; - } - else if (unit == Unit::Acceleration) { - unitString = "in/min^2"; - factor = 25.4 / 3600; - } - else { - // default action for all cases without special treatment: - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} - -std::string UnitsSchemaImperialBuilding::schemaTranslate(const Quantity& quant, - double& factor, - std::string& unitString) -{ - // this schema expresses distances in feet + inches + fractions - // ex: 3'- 4 1/4" with proper rounding - Unit unit = quant.getUnit(); - if (unit == Unit::Length) { - unitString = "in"; - factor = 25.4; - - // Total number of inches to format - double totalInches = std::abs(quant.getValue()) / factor; - - // minimum denominator (8 for 1/8, 16 for 1/16, etc) - int minden {}; - - // Outputs - int feet {}; // whole feet - int inches {}; // whole inches - int num {}, den {}; // numerator and denominator of fractional val - std::stringstream output; // output stream - - // Intermediate values - int ntot {}; // total fractional units - int a {}, b {}, d {}; // used to compute greatest common denominator - int tmp {}; // temporary variable for GCD - - // Get the current user specified minimum denominator - minden = quant.getFormat().getDenominator(); - - // Compute and round the total number of fractional units - ntot = static_cast(std::round(totalInches * static_cast(minden))); - - // If this is zero, nothing to do but return - if (ntot == 0) { - return "0"; - } - - // Compute the whole number of feet and remaining units - feet = static_cast(std::floor(ntot / (12 * minden))); - ntot = ntot - 12 * minden * feet; - - // Compute the remaining number of whole inches - inches = static_cast(std::floor(ntot / minden)); - - // Lastly the fractional quantities - num = ntot - inches * minden; - den = minden; - - // If numerator is not zero, compute greatest common divisor and reduce - // fraction - if (num != 0) { - // initialize - a = num; - b = den; - while (b != 0) { - tmp = a % b; - - a = b; - b = tmp; - } - d = a; - - num /= d; - den /= d; - } - - // Process into string. Start with negative sign if quantity is less - // than zero - char plusOrMinus {}; - if (quant.getValue() < 0) { - output << "-"; - plusOrMinus = '-'; - } - else { - plusOrMinus = '+'; - } - - bool trailingNumber = false; - // Print feet if we have any - if (feet != 0) { - output << feet << "'"; - trailingNumber = true; - } - // Print whole inches if we have any - if (inches != 0) { - if (trailingNumber) { - output << " "; - } - output << inches << "\""; - trailingNumber = true; - } - // Print fractional inches if we have any - if (num != 0) { - if (trailingNumber) { - output << " " << plusOrMinus << " "; - } - output << num << "/" << den << "\""; - } - - // Done! - return output.str(); - } - else if (unit == Unit::Angle) { - unitString = "\xC2\xB0"; - factor = 1.0; - } - else if (unit == Unit::Area) { - unitString = "sqft"; - factor = 92903.04; - } - else if (unit == Unit::Volume) { - unitString = "cft"; - factor = 28316846.592; - } - else if (unit == Unit::Velocity) { - unitString = "in/min"; - factor = 25.4 / 60; - } - else { - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} - -std::string UnitsSchemaImperialCivil::schemaTranslate(const Base::Quantity& quant, - double& factor, - std::string& unitString) -{ - Unit unit = quant.getUnit(); - // for imperial user/programmer mind; UnitValue is in internal system, that means - // mm/kg/s. And all combined units have to be calculated from there! - - // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - unitString = "ft"; // always ft - factor = 304.8; // 12 * 25.4 - } - else if (unit == Unit::Area) { - unitString = "ft^2"; // always sq.ft - factor = 92903.04; - } - else if (unit == Unit::Volume) { - unitString = "ft^3"; // always cu. ft - factor = 28316846.592; - } - else if (unit == Unit::Mass) { - unitString = "lb"; // always lbs. - factor = 0.45359237; - } - else if (unit == Unit::Pressure) { - unitString = "psi"; - factor = 6.894744825494; - } - else if (unit == Unit::Stiffness) { - unitString = "lbf/in"; - factor = 4.448222 / 0.0254; - } - else if (unit == Unit::Velocity) { - unitString = "mph"; - factor = 447.04; // 1mm/sec => mph - } - // this schema expresses angles in degrees + minutes + seconds - else if (unit == Unit::Angle) { - unitString = "deg"; - std::string degreeString = "\xC2\xB0"; // degree symbol - std::string minuteString = "\xE2\x80\xB2"; // prime symbol - std::string secondString = "\xE2\x80\xB3"; // double prime symbol - factor = 1.0; // 1deg = 1"\xC2\xB0 " - - double totalDegrees = quant.getValue() / factor; - double wholeDegrees = std::floor(totalDegrees); - double sumMinutes = totalDegrees * 60.0; // quant as minutes - double rawMinutes = sumMinutes - wholeDegrees * 60.0; - double wholeMinutes = std::floor(rawMinutes); - double sumSeconds = totalDegrees * 3600.0; // quant as seconds - double rawSeconds = sumSeconds - (wholeDegrees * 3600.0) - (wholeMinutes * 60); - - int outDeg = static_cast(wholeDegrees); - int outMin = static_cast(wholeMinutes); - int outSec = static_cast(std::round(rawSeconds)); - - std::stringstream output; - output << outDeg << degreeString; - if ((outMin > 0) || (outSec > 0)) { - output << outMin << minuteString; - } - if (outSec > 0) { - output << outSec << secondString; - } - // uncomment this for decimals on seconds - // if (remainSeconds < (1.0 * pow(10.0,-Base::UnitsApi::getDecimals())) ) { - // //NOP too small to display - // } else { - // output << std::setprecision(Base::UnitsApi::getDecimals()) << std::fixed << - // rawSeconds << secondString.toStdString(); - // } - return output.str(); - } - else { - // default action for all cases without special treatment: - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaImperial1.h b/src/Base/UnitsSchemaImperial1.h deleted file mode 100644 index fe4f10eff5..0000000000 --- a/src/Base/UnitsSchemaImperial1.h +++ /dev/null @@ -1,105 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMAIMPERIAL1_H -#define BASE_UNITSSCHEMAIMPERIAL1_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/** The schema class for the imperial unit system - * Here are the definitions for the imperial unit system. - * It also defines how the value/units get printed. - */ -class UnitsSchemaImperial1: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - std::string getBasicLengthUnit() const override - { - return {"in"}; - } -}; - -/** The schema class for the imperial unit system - * Here are the definitions for the imperial unit system. - * It also defines how the value/units get printed. - */ -class UnitsSchemaImperialDecimal: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - std::string getBasicLengthUnit() const override - { - return {"in"}; - } -}; - -/** The schema class for the imperial unit system - * Here are the definitions for the imperial unit system. - * It also defines how the value/units get printed. - */ -class UnitsSchemaImperialBuilding: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - std::string getBasicLengthUnit() const override - { - return {"ft"}; - } - - // return true if this schema uses multiple units for length (ex. Ft/In) - bool isMultiUnitLength() const override - { - return true; - } -}; - -/** The schema class for Civil Engineering in the imperial unit system - * All measurements in ft, ft^2, ft^3, ft/sec. - * Pressure is in psi. - */ -class UnitsSchemaImperialCivil: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - std::string getBasicLengthUnit() const override - { - return {"ft"}; - } - - // return true if this schema uses multiple units for angles (ex. DMS) - bool isMultiUnitAngle() const override - { - return true; - } -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAIMPERIAL1_H diff --git a/src/Base/UnitsSchemaInternal.cpp b/src/Base/UnitsSchemaInternal.cpp deleted file mode 100644 index f06286ff3e..0000000000 --- a/src/Base/UnitsSchemaInternal.cpp +++ /dev/null @@ -1,671 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#endif -#ifdef __GNUC__ -#include -#endif - - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaInternal.h" - -using namespace Base; - -std::string -UnitsSchemaInternal::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) -{ - double UnitValue = std::abs(quant.getValue()); - Unit unit = quant.getUnit(); - - // In order to get the right factor always express the target - // units as internal units where length is in mm and mass in kg - // Example: - // For W/mm/K we get the factor of 1000000.0 because - // W/mm/K = kg*m^2/s^3/mm/K - // = 10e6 * kg*mm^2/s^3/mm/K - // = 10e6 * kg*mm/s^3/K - - // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - if (UnitValue < 1e-6) { // smaller than 0.001 nm -> scientific notation - unitString = "mm"; - factor = 1.0; - } - else if (UnitValue < 1e-3) { - unitString = "nm"; - factor = 1e-6; - } - else if (UnitValue < 0.1) { - unitString = "\xC2\xB5m"; - factor = 1e-3; - } - else if (UnitValue < 1e4) { - unitString = "mm"; - factor = 1.0; - } - else if (UnitValue < 1e7) { - unitString = "m"; - factor = 1e3; - } - else if (UnitValue < 1e10) { - unitString = "km"; - factor = 1e6; - } - else { // bigger than 1000 km -> scientific notation - unitString = "m"; - factor = 1e3; - } - } - else if (unit == Unit::Area) { - if (UnitValue < 100) { - unitString = "mm^2"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "cm^2"; - factor = 100; - } - else if (UnitValue < 1e12) { - unitString = "m^2"; - factor = 1e6; - } - else { // bigger than 1 square kilometer - unitString = "km^2"; - factor = 1e12; - } - } - else if (unit == Unit::Volume) { - if (UnitValue < 1e3) { // smaller than 1 ul - unitString = "mm^3"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "ml"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "l"; - factor = 1e6; - } - else { // bigger than 1000 l - unitString = "m^3"; - factor = 1e9; - } - } - else if (unit == Unit::Angle) { - // TODO: Cascade for the Areas - // default action for all cases without special treatment: - unitString = "\xC2\xB0"; - factor = 1.0; - } - else if (unit == Unit::Mass) { - if (UnitValue < 1e-6) { - unitString = "\xC2\xB5g"; - factor = 1e-9; - } - else if (UnitValue < 1e-3) { - unitString = "mg"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "g"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "kg"; - factor = 1.0; - } - else { - unitString = "t"; - factor = 1e3; - } - } - else if (unit == Unit::Density) { - if (UnitValue < 0.0001) { - unitString = "kg/m^3"; - factor = 1e-9; - } - else if (UnitValue < 1.0) { - unitString = "kg/cm^3"; - factor = 0.001; - } - else { - unitString = "kg/mm^3"; - factor = 1.0; - } - } - else if (unit == Unit::ThermalConductivity) { - if (UnitValue > 1e6) { - unitString = "W/mm/K"; - factor = 1e6; - } - else { - unitString = "W/m/K"; - factor = 1000.0; - } - } - else if (unit == Unit::ThermalExpansionCoefficient) { - if (UnitValue < 0.001) { - unitString = "\xC2\xB5m/m/K"; // micro-meter/meter/K - factor = 1e-6; - } - else { - unitString = "mm/mm/K"; - factor = 1.0; - } - } - else if (unit == Unit::VolumetricThermalExpansionCoefficient) { - if (UnitValue < 0.001) { - unitString = "mm^3/m^3/K"; - factor = 1e-9; - } - else { - unitString = "m^3/m^3/K"; - factor = 1.0; - } - } - else if (unit == Unit::SpecificHeat) { - unitString = "J/kg/K"; - factor = 1e6; - } - else if (unit == Unit::ThermalTransferCoefficient) { - unitString = "W/m^2/K"; - factor = 1.0; - } - else if ((unit == Unit::Pressure) || (unit == Unit::Stress)) { - if (UnitValue < 10.0) { // Pa is the smallest - unitString = "Pa"; - factor = 0.001; - } - else if (UnitValue < 10000.0) { - unitString = "kPa"; - factor = 1.0; - } - else if (UnitValue < 10000000.0) { - unitString = "MPa"; - factor = 1000.0; - } - else if (UnitValue < 10000000000.0) { - unitString = "GPa"; - factor = 1e6; - } - else { // bigger -> scientific notation - unitString = "Pa"; - factor = 0.001; - } - } - else if ((unit == Unit::Stiffness)) { - if (UnitValue < 1) { // mN/m is the smallest - unitString = "mN/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "N/m"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "kN/m"; - factor = 1e3; - } - else { - unitString = "MN/m"; - factor = 1e6; - } - } - else if ((unit == Unit::StiffnessDensity)) { - if (UnitValue < 1e-3) { - unitString = "Pa/m"; - factor = 1e-6; - } - else if (UnitValue < 1) { - unitString = "kPa/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "MPa/m"; - factor = 1.0; - } - else { - unitString = "GPa/m"; - factor = 1e3; - } - } - else if (unit == Unit::Force) { - if (UnitValue < 1e3) { - unitString = "mN"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "N"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "kN"; - factor = 1e6; - } - else { - unitString = "MN"; - factor = 1e9; - } - } - // else if (unit == Unit::Moment) { - // if (UnitValue < 1e6) { - // unitString = "mNm"; - // factor = 1e3; - // } - // else if (UnitValue < 1e9) { - // unitString = "Nm"; - // factor = 1e6; - // } - // else if (UnitValue < 1e12) { - // unitString = "kNm"; - // factor = 1e9; - // } - // else { - // unitString = "MNm"; - // factor = 1e12; - // } - // } - else if (unit == Unit::Power) { - if (UnitValue < 1e6) { - unitString = "mW"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "W"; - factor = 1e6; - } - else { - unitString = "kW"; - factor = 1e9; - } - } - else if (unit == Unit::ElectricPotential) { - if (UnitValue < 1e6) { - unitString = "mV"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "V"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kV"; - factor = 1e9; - } - else { // > 1000 kV scientificc notation - unitString = "V"; - factor = 1e6; - } - } - else if (unit == Unit::Work) { - if (UnitValue < 1.602176634e-10) { - unitString = "eV"; - factor = 1.602176634e-13; - } - else if (UnitValue < 1.602176634e-7) { - unitString = "keV"; - factor = 1.602176634e-10; - } - else if (UnitValue < 1.602176634e-4) { - unitString = "MeV"; - factor = 1.602176634e-7; - } - else if (UnitValue < 1e6) { - unitString = "mJ"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "J"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kJ"; - factor = 1e9; - } - else if (UnitValue < 3.6e+15) { - unitString = "kWh"; - factor = 3.6e+12; - } - else { // bigger than 1000 kWh -> scientific notation - unitString = "J"; - factor = 1e6; - } - } - else if (unit == Unit::SpecificEnergy) { - unitString = "m^2/s^2"; - factor = 1e6; - } - else if (unit == Unit::HeatFlux) { - unitString = "W/m^2"; - factor = 1; // unit signature (0,1,-3,0,0) is length independent - } - else if (unit == Unit::ElectricCharge) { - unitString = "C"; - factor = 1.0; - } - else if (unit == Unit::SurfaceChargeDensity) { - if (UnitValue <= 1e-4) { - unitString = "C/m^2"; - factor = 1e-6; - } - else if (UnitValue <= 1e-2) { - unitString = "C/cm^2"; - factor = 1e-2; - } - else { - unitString = "C/mm^2"; - factor = 1; - } - } - else if (unit == Unit::VolumeChargeDensity) { - if (UnitValue <= 1e-4) { - unitString = "C/m^3"; - factor = 1e-9; - } - else if (UnitValue <= 1e-2) { - unitString = "C/cm^3"; - factor = 1e-3; - } - else { - unitString = "C/mm^3"; - factor = 1; - } - } - else if (unit == Unit::CurrentDensity) { - if (UnitValue <= 1e-4) { - unitString = "A/m^2"; - factor = 1e-6; - } - else if (UnitValue <= 1e-2) { - unitString = "A/cm^2"; - factor = 1e-2; - } - else { - unitString = "A/mm^2"; - factor = 1; - } - } - else if (unit == Unit::MagneticFluxDensity) { - if (UnitValue <= 1e-3) { - unitString = "G"; - factor = 1e-4; - } - else { - unitString = "T"; - factor = 1.0; - } - } - else if (unit == Unit::MagneticFieldStrength) { - unitString = "A/m"; - factor = 1e-3; - } - else if (unit == Unit::MagneticFlux) { - unitString = "Wb"; - factor = 1e6; - } - else if (unit == Unit::Magnetization) { - unitString = "A/m"; - factor = 1e-3; - } - else if (unit == Unit::ElectromagneticPotential) { - unitString = "Wb/m"; - factor = 1e3; - } - else if (unit == Unit::ElectricalConductance) { - if (UnitValue < 1e-9) { - unitString = "\xC2\xB5S"; - factor = 1e-12; - } - else if (UnitValue < 1e-6) { - unitString = "mS"; - factor = 1e-9; - } - else { - unitString = "S"; - factor = 1e-6; - } - } - else if (unit == Unit::ElectricalResistance) { - if (UnitValue < 1e9) { - unitString = "Ohm"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kOhm"; - factor = 1e9; - } - else { - unitString = "MOhm"; - factor = 1e12; - } - } - else if (unit == Unit::ElectricalConductivity) { - if (UnitValue < 1e-3) { - unitString = "mS/m"; - factor = 1e-12; - } - else if (UnitValue < 1.0) { - unitString = "S/m"; - factor = 1e-9; - } - else if (UnitValue < 1e3) { - unitString = "kS/m"; - factor = 1e-6; - } - else { - unitString = "MS/m"; - factor = 1e-3; - } - } - else if (unit == Unit::ElectricalCapacitance) { - if (UnitValue < 1e-15) { - unitString = "pF"; - factor = 1e-18; - } - else if (UnitValue < 1e-12) { - unitString = "nF"; - factor = 1e-15; - } - else if (UnitValue < 1e-9) { - // \x reads everything to the end, therefore split - unitString = "\xC2\xB5" - "F"; - factor = 1e-12; - } - else if (UnitValue < 1e-6) { - unitString = "mF"; - factor = 1e-9; - } - else { - unitString = "F"; - factor = 1e-6; - } - } - else if (unit == Unit::ElectricalInductance) { - if (UnitValue < 1.0) { - unitString = "nH"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "\xC2\xB5H"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "mH"; - factor = 1e3; - } - else { - unitString = "H"; - factor = 1e6; - } - } - else if (unit == Unit::VacuumPermittivity) { - unitString = "F/m"; - factor = 1e-9; - } - else if (unit == Unit::Frequency) { - if (UnitValue < 1e3) { - unitString = "Hz"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "kHz"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "MHz"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "GHz"; - factor = 1e9; - } - else { - unitString = "THz"; - factor = 1e12; - } - } - else if (unit == Unit::Velocity) { - unitString = "mm/s"; - factor = 1.0; - } - else if (unit == Unit::DynamicViscosity) { - unitString = "Pa*s"; - factor = 0.001; - } - else if (unit == Unit::KinematicViscosity) { - if (UnitValue < 1e3) { - unitString = "mm^2/s"; - factor = 1.0; - } - else { - unitString = "m^2/s"; - factor = 1e6; - } - } - else if (unit == Unit::VolumeFlowRate) { - if (UnitValue < 1e3) { - unitString = "mm^3/s"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "ml/s"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "l/s"; - factor = 1e6; - } - else { - unitString = "m^3/s"; - factor = 1e9; - } - } - else if (unit == Unit::DissipationRate) { - unitString = "W/kg"; - factor = 1e6; - } - else if (unit == Unit::InverseLength) { - if (UnitValue < 1e-6) { // smaller than 0.001 1/km -> scientific notation - unitString = "1/m"; - factor = 1e-3; - } - else if (UnitValue < 1e-3) { - unitString = "1/km"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "1/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "1/mm"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "1/\xC2\xB5m"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "1/nm"; - factor = 1e6; - } - else { // larger -> scientific notation - unitString = "1/m"; - factor = 1e-3; - } - } - else if (unit == Unit::InverseArea) { - if (UnitValue < 1e-12) { // smaller than 0.001 1/km^2 -> scientific notation - unitString = "1/m^2"; - factor = 1e-6; - } - else if (UnitValue < 1e-6) { - unitString = "1/km^2"; - factor = 1e-12; - } - else if (UnitValue < 1.0) { - unitString = "1/m^2"; - factor = 1e-6; - } - else if (UnitValue < 1e2) { - unitString = "1/cm^2"; - factor = 1e-2; - } - else { - unitString = "1/mm^2"; - factor = 1.0; - } - } - else if (unit == Unit::InverseVolume) { - if (UnitValue < 1e-6) { - unitString = "1/m^3"; - factor = 1e-9; - } - else if (UnitValue < 1e-3) { - unitString = "1/l"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "1/ml"; - factor = 1e-3; - } - else { - unitString = "1/mm^3"; - factor = 1.0; - } - } - else { - // default action for all cases without special treatment: - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaInternal.h b/src/Base/UnitsSchemaInternal.h deleted file mode 100644 index 0231112d60..0000000000 --- a/src/Base/UnitsSchemaInternal.h +++ /dev/null @@ -1,45 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMAINTERNAL_H -#define BASE_UNITSSCHEMAINTERNAL_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/** The standard units schema - * Here is defined what internal (base) units FreeCAD uses. - * FreeCAD uses a mm/kg/deg scala. - * Also it defines how the units get presented. - */ -class UnitsSchemaInternal: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAINTERNAL_H diff --git a/src/Base/UnitsSchemaMKS.cpp b/src/Base/UnitsSchemaMKS.cpp deleted file mode 100644 index 42ea0b0c79..0000000000 --- a/src/Base/UnitsSchemaMKS.cpp +++ /dev/null @@ -1,634 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#endif -#ifdef __GNUC__ -#include -#endif - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaMKS.h" - -using namespace Base; - -std::string -UnitsSchemaMKS::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) -{ - double UnitValue = std::abs(quant.getValue()); - Unit unit = quant.getUnit(); - - // now do special treatment on all cases seems necessary: - if (unit == Unit::Length) { // Length handling ============================ - if (UnitValue < 1e-6) { // smaller than 0.001 nm -> scientific notation - unitString = "mm"; - factor = 1.0; - } - else if (UnitValue < 1e-3) { - unitString = "nm"; - factor = 1e-6; - } - else if (UnitValue < 0.1) { - unitString = "\xC2\xB5m"; - factor = 1e-3; - } - else if (UnitValue < 1e4) { - unitString = "mm"; - factor = 1.0; - } - else if (UnitValue < 1e7) { - unitString = "m"; - factor = 1e3; - } - else if (UnitValue < 1e10) { - unitString = "km"; - factor = 1e6; - } - else { // bigger than 1000 km -> scientific notation - unitString = "m"; - factor = 1e3; - } - } - else if (unit == Unit::Area) { - if (UnitValue < 100) { - unitString = "mm^2"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "cm^2"; - factor = 100; - } - else if (UnitValue < 1e12) { - unitString = "m^2"; - factor = 1e6; - } - else { // bigger than 1 square kilometer - unitString = "km^2"; - factor = 1e12; - } - } - else if (unit == Unit::Volume) { - if (UnitValue < 1e3) { // smaller than 1 ul - unitString = "mm^3"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "ml"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "l"; - factor = 1e6; - } - else { // bigger than 1000 l - unitString = "m^3"; - factor = 1e9; - } - } - else if (unit == Unit::Mass) { - if (UnitValue < 1e-6) { - unitString = "\xC2\xB5g"; - factor = 1e-9; - } - else if (UnitValue < 1e-3) { - unitString = "mg"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "g"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "kg"; - factor = 1.0; - } - else { - unitString = "t"; - factor = 1e3; - } - } - else if (unit == Unit::Density) { - if (UnitValue < 0.0001) { - unitString = "kg/m^3"; - factor = 0.000000001; - } - else if (UnitValue < 1.0) { - unitString = "kg/cm^3"; - factor = 0.001; - } - else { - unitString = "kg/mm^3"; - factor = 1.0; - } - } - else if (unit == Unit::Acceleration) { - unitString = "m/s^2"; - factor = 1000.0; - } - else if ((unit == Unit::Pressure) || (unit == Unit::Stress)) { - if (UnitValue < 10.0) { // Pa is the smallest - unitString = "Pa"; - factor = 0.001; - } - else if (UnitValue < 10000.0) { - unitString = "kPa"; - factor = 1.0; - } - else if (UnitValue < 10000000.0) { - unitString = "MPa"; - factor = 1000.0; - } - else if (UnitValue < 10000000000.0) { - unitString = "GPa"; - factor = 1000000.0; - } - else { // bigger then 1000 GPa -> scientific notation - unitString = "Pa"; - factor = 0.001; - } - } - else if ((unit == Unit::Stiffness)) { - if (UnitValue < 1) { // mN/m is the smallest - unitString = "mN/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "N/m"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "kN/m"; - factor = 1e3; - } - else { - unitString = "MN/m"; - factor = 1e6; - } - } - else if ((unit == Unit::StiffnessDensity)) { - if (UnitValue < 1e-3) { - unitString = "Pa/m"; - factor = 1e-6; - } - else if (UnitValue < 1) { - unitString = "kPa/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "MPa/m"; - factor = 1.0; - } - else { - unitString = "GPa/m"; - factor = 1e3; - } - } - else if (unit == Unit::ThermalConductivity) { - if (UnitValue > 1000000) { - unitString = "W/mm/K"; - factor = 1000000.0; - } - else { - unitString = "W/m/K"; - factor = 1000.0; - } - } - else if (unit == Unit::ThermalExpansionCoefficient) { - if (UnitValue < 0.001) { - unitString = "\xC2\xB5m/m/K"; - factor = 0.000001; - } - else { - unitString = "m/m/K"; - factor = 1.0; - } - } - else if (unit == Unit::VolumetricThermalExpansionCoefficient) { - if (UnitValue < 0.001) { - unitString = "mm^3/m^3/K"; - factor = 1e-9; - } - else { - unitString = "m^3/m^3/K"; - factor = 1.0; - } - } - else if (unit == Unit::SpecificHeat) { - unitString = "J/kg/K"; - factor = 1000000.0; - } - else if (unit == Unit::ThermalTransferCoefficient) { - unitString = "W/m^2/K"; - factor = 1.0; - } - else if (unit == Unit::Force) { - if (UnitValue < 1e3) { - unitString = "mN"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "N"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "kN"; - factor = 1e6; - } - else { - unitString = "MN"; - factor = 1e9; - } - } - // else if (unit == Unit::Moment) { - // if (UnitValue < 1e6) { - // unitString = "mNm"; - // factor = 1e3; - // } - // else if (UnitValue < 1e9) { - // unitString = "Nm"; - // factor = 1e6; - // } - // else if (UnitValue < 1e12) { - // unitString = "kNm"; - // factor = 1e9; - // } - // else { - // unitString = "MNm"; - // factor = 1e12; - // } - // } - else if (unit == Unit::Power) { - if (UnitValue < 1e6) { - unitString = "mW"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "W"; - factor = 1e6; - } - else { - unitString = "kW"; - factor = 1e9; - } - } - else if (unit == Unit::ElectricPotential) { - if (UnitValue < 1e6) { - unitString = "mV"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "V"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kV"; - factor = 1e9; - } - else { // > 1000 kV scientificc notation - unitString = "V"; - factor = 1e6; - } - } - else if (unit == Unit::ElectricCharge) { - unitString = "C"; - factor = 1.0; - } - else if (unit == Unit::SurfaceChargeDensity) { - unitString = "C/m^2"; - factor = 1e-6; - } - else if (unit == Unit::VolumeChargeDensity) { - unitString = "C/m^3"; - factor = 1e-9; - } - else if (unit == Unit::CurrentDensity) { - if (UnitValue <= 1e3) { - unitString = "A/m^2"; - factor = 1e-6; - } - else { - unitString = "A/mm^2"; - factor = 1; - } - } - else if (unit == Unit::MagneticFluxDensity) { - if (UnitValue <= 1e-3) { - unitString = "G"; - factor = 1e-4; - } - else { - unitString = "T"; - factor = 1.0; - } - } - else if (unit == Unit::MagneticFieldStrength) { - unitString = "A/m"; - factor = 1e-3; - } - else if (unit == Unit::MagneticFlux) { - unitString = "Wb"; - factor = 1e6; - } - else if (unit == Unit::Magnetization) { - unitString = "A/m"; - factor = 1e-3; - } - else if (unit == Unit::ElectromagneticPotential) { - unitString = "Wb/m"; - factor = 1e3; - } - else if (unit == Unit::ElectricalConductance) { - if (UnitValue < 1e-9) { - unitString = "\xC2\xB5S"; - factor = 1e-12; - } - else if (UnitValue < 1e-6) { - unitString = "mS"; - factor = 1e-9; - } - else { - unitString = "S"; - factor = 1e-6; - } - } - else if (unit == Unit::ElectricalResistance) { - if (UnitValue < 1e9) { - unitString = "Ohm"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kOhm"; - factor = 1e9; - } - else { - unitString = "MOhm"; - factor = 1e12; - } - } - else if (unit == Unit::ElectricalConductivity) { - if (UnitValue < 1e-3) { - unitString = "mS/m"; - factor = 1e-12; - } - else if (UnitValue < 1.0) { - unitString = "S/m"; - factor = 1e-9; - } - else if (UnitValue < 1e3) { - unitString = "kS/m"; - factor = 1e-6; - } - else { - unitString = "MS/m"; - factor = 1e-3; - } - } - else if (unit == Unit::ElectricalCapacitance) { - if (UnitValue < 1e-15) { - unitString = "pF"; - factor = 1e-18; - } - else if (UnitValue < 1e-12) { - unitString = "nF"; - factor = 1e-15; - } - else if (UnitValue < 1e-9) { - // \x reads everything to the end, therefore split - unitString = "\xC2\xB5" - "F"; - factor = 1e-12; - } - else if (UnitValue < 1e-6) { - unitString = "mF"; - factor = 1e-9; - } - else { - unitString = "F"; - factor = 1e-6; - } - } - else if (unit == Unit::ElectricalInductance) { - if (UnitValue < 1e-6) { - unitString = "nH"; - factor = 1e-3; - } - else if (UnitValue < 1e-3) { - unitString = "\xC2\xB5H"; - factor = 1.0; - } - else if (UnitValue < 1.0) { - unitString = "mH"; - factor = 1e3; - } - else { - unitString = "H"; - factor = 1e6; - } - } - else if (unit == Unit::VacuumPermittivity) { - unitString = "F/m"; - factor = 1e-9; - } - else if (unit == Unit::Work) { - if (UnitValue < 1.602176634e-10) { - unitString = "eV"; - factor = 1.602176634e-13; - } - else if (UnitValue < 1.602176634e-7) { - unitString = "keV"; - factor = 1.602176634e-10; - } - else if (UnitValue < 1.602176634e-4) { - unitString = "MeV"; - factor = 1.602176634e-7; - } - else if (UnitValue < 1e6) { - unitString = "mJ"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "J"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "kJ"; - factor = 1e9; - } - else if (UnitValue < 3.6e+15) { - unitString = "kWh"; - factor = 3.6e+12; - } - else { // bigger than 1000 kWh -> scientific notation - unitString = "J"; - factor = 1e6; - } - } - else if (unit == Unit::SpecificEnergy) { - unitString = "m^2/s^2"; - factor = 1000000; - } - else if (unit == Unit::HeatFlux) { - unitString = "W/m^2"; - factor = 1.0; - } - else if (unit == Unit::Frequency) { - if (UnitValue < 1e3) { - unitString = "Hz"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "kHz"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "MHz"; - factor = 1e6; - } - else if (UnitValue < 1e12) { - unitString = "GHz"; - factor = 1e9; - } - else { - unitString = "THz"; - factor = 1e12; - } - } - else if (unit == Unit::Velocity) { - unitString = "m/s"; - factor = 1000.0; - } - else if (unit == Unit::DynamicViscosity) { - unitString = "Pa*s"; - factor = 0.001; - } - else if (unit == Unit::KinematicViscosity) { - unitString = "m^2/s"; - factor = 1e6; - } - else if (unit == Unit::VolumeFlowRate) { - if (UnitValue < 1e-3) { // smaller than 0.001 mm^3/s -> scientific notation - unitString = "m^3/s"; - factor = 1e9; - } - else if (UnitValue < 1e3) { - unitString = "mm^3/s"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "ml/s"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "l/s"; - factor = 1e6; - } - else { - unitString = "m^3/s"; - factor = 1e9; - } - } - else if (unit == Unit::DissipationRate) { - unitString = "W/kg"; - factor = 1e6; - } - else if (unit == Unit::InverseLength) { - if (UnitValue < 1e-6) { // smaller than 0.001 1/km -> scientific notation - unitString = "1/m"; - factor = 1e-3; - } - else if (UnitValue < 1e-3) { - unitString = "1/km"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "1/m"; - factor = 1e-3; - } - else if (UnitValue < 1e3) { - unitString = "1/mm"; - factor = 1.0; - } - else if (UnitValue < 1e6) { - unitString = "1/\xC2\xB5m"; - factor = 1e3; - } - else if (UnitValue < 1e9) { - unitString = "1/nm"; - factor = 1e6; - } - else { // larger -> scientific notation - unitString = "1/m"; - factor = 1e-3; - } - } - else if (unit == Unit::InverseArea) { - if (UnitValue < 1e-12) { // smaller than 0.001 1/km^2 -> scientific notation - unitString = "1/m^2"; - factor = 1e-6; - } - else if (UnitValue < 1e-6) { - unitString = "1/km^2"; - factor = 1e-12; - } - else if (UnitValue < 1.0) { - unitString = "1/m^2"; - factor = 1e-6; - } - else if (UnitValue < 1e2) { - unitString = "1/cm^2"; - factor = 1e-2; - } - else { - unitString = "1/mm^2"; - factor = 1.0; - } - } - else if (unit == Unit::InverseVolume) { - if (UnitValue < 1e-6) { - unitString = "1/m^3"; - factor = 1e-9; - } - else if (UnitValue < 1e-3) { - unitString = "1/l"; - factor = 1e-6; - } - else if (UnitValue < 1.0) { - unitString = "1/ml"; - factor = 1e-3; - } - else { - unitString = "1/mm^3"; - factor = 1.0; - } - } - else { - // default action for all cases without special treatment: - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaMKS.h b/src/Base/UnitsSchemaMKS.h deleted file mode 100644 index d6fc11c95f..0000000000 --- a/src/Base/UnitsSchemaMKS.h +++ /dev/null @@ -1,43 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMAMKS_H -#define BASE_UNITSSCHEMAMKS_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/** - * The UnitSchema class - */ -class UnitsSchemaMKS: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAMKS_H diff --git a/src/Base/UnitsSchemaMeterDecimal.cpp b/src/Base/UnitsSchemaMeterDecimal.cpp deleted file mode 100644 index 52a6a9ca41..0000000000 --- a/src/Base/UnitsSchemaMeterDecimal.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/*************************************************************************** - * Copyright (c) WandererFan * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -/* Metric units schema intended for design of large objects - * Lengths are always in metres. - * Areas are always in square metres - * Volumes are always in cubic metres - * Angles in decimal degrees (use degree symbol) - * Velocities in m/sec - */ - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#include -#endif - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaMeterDecimal.h" - -using namespace Base; - -std::string UnitsSchemaMeterDecimal::schemaTranslate(const Base::Quantity& quant, - double& factor, - std::string& unitString) -{ - static std::array>, 7> unitSpecs {{ - {Unit::Length, {"m", 1e3}}, - {Unit::Area, {"m^2", 1e6}}, - {Unit::Volume, {"m^3", 1e9}}, - {Unit::Power, {"W", 1000000}}, - {Unit::ElectricPotential, {"V", 1000000}}, - {Unit::HeatFlux, {"W/m^2", 1.0}}, - {Unit::Velocity, {"m/s", 1e3}}, - }}; - - const auto unit = quant.getUnit(); - const auto spec = std::find_if(unitSpecs.begin(), unitSpecs.end(), [&](const auto& pair) { - return pair.first == unit; - }); - - if (spec != std::end(unitSpecs)) { - unitString = spec->second.first; - factor = spec->second.second; - } - else { - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} diff --git a/src/Base/UnitsSchemaMmMin.h b/src/Base/UnitsSchemaMmMin.h deleted file mode 100644 index 1f6a0262a7..0000000000 --- a/src/Base/UnitsSchemaMmMin.h +++ /dev/null @@ -1,45 +0,0 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -#ifndef BASE_UNITSSCHEMAMMMIN_H -#define BASE_UNITSSCHEMAMMMIN_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/* Metric units schema intended for design of small parts and for CNC - * Lengths are always in mm. - * Angles in degrees (use degree symbol) - * Velocities in mm/min (as used in g-code). - */ -class UnitsSchemaMmMin: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAMMMIN_H diff --git a/src/Base/UnitsSchemas.cpp b/src/Base/UnitsSchemas.cpp new file mode 100644 index 0000000000..f79e1d4317 --- /dev/null +++ b/src/Base/UnitsSchemas.cpp @@ -0,0 +1,145 @@ +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#include +#include +#include +#include + +#include + +#include "UnitsSchemas.h" +#include "Exception.h" +#include "Quantity.h" +#include "UnitsApi.h" +#include "UnitsSchema.h" +#include "UnitsSchemasSpecs.h" +#include "UnitsSchemasData.h" + +using Base::Quantity; +using Base::UnitsSchema; +using Base::UnitsSchemas; +using Base::UnitsSchemaSpec; + +UnitsSchemas::UnitsSchemas(const UnitsSchemasDataPack& pack) + : pack {pack} + , denominator {pack.defDenominator} + , decimals {pack.defDecimals} +{} + +size_t UnitsSchemas::count() const +{ + return pack.specs.size(); +} + +std::vector UnitsSchemas::getVec(const std::function& fn) +{ + std::vector vec; + std::transform(pack.specs.begin(), pack.specs.end(), std::back_inserter(vec), fn); + + return vec; +} + +std::vector UnitsSchemas::names() +{ + return getVec([](const UnitsSchemaSpec& spec) { + return spec.name; + }); +} + +std::vector UnitsSchemas::descriptions() +{ + return getVec([](const UnitsSchemaSpec& spec) { + return QCoreApplication::translate("UnitsApi", spec.description).toStdString(); + }); +} + +std::size_t UnitsSchemas::getDecimals() const +{ + return pack.defDecimals; +} + +std::size_t UnitsSchemas::defFractDenominator() const +{ + return pack.defDenominator; +} + +void UnitsSchemas::setdefFractDenominator(const std::size_t size) +{ + denominator = size; +} + +void UnitsSchemas::select() +{ + makeCurr(spec()); +} + +void UnitsSchemas::select(const std::string_view& name) +{ + makeCurr(spec(name)); +} + +void UnitsSchemas::select(const std::size_t num) +{ + makeCurr(spec(num)); +} + +UnitsSchema* UnitsSchemas::currentSchema() const +{ + return current.get(); +} + +void UnitsSchemas::makeCurr(const UnitsSchemaSpec& spec) +{ + current = std::make_unique(spec); +} + +UnitsSchemaSpec UnitsSchemas::findSpec(const std::function& fn) +{ + const auto found = std::find_if(pack.specs.begin(), pack.specs.end(), fn); + + if (found == pack.specs.end()) { + throw RuntimeError {"UnitSchemaSpec not found"}; + } + + return *found; +} + +UnitsSchemaSpec UnitsSchemas::spec() +{ + return findSpec([](const UnitsSchemaSpec& spec) { + return spec.isDefault; + }); +} + +UnitsSchemaSpec UnitsSchemas::spec(const std::string_view& name) +{ + return findSpec([&name](const UnitsSchemaSpec& spec) { + return spec.name == name; + }); +} + +UnitsSchemaSpec UnitsSchemas::spec(const std::size_t num) +{ + return findSpec([&num](const UnitsSchemaSpec& spec) { + return spec.num == num; + }); +} diff --git a/src/Base/UnitsSchemas.h b/src/Base/UnitsSchemas.h new file mode 100644 index 0000000000..38e4aafffc --- /dev/null +++ b/src/Base/UnitsSchemas.h @@ -0,0 +1,77 @@ +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#ifndef SRC_BASE_UNITSSCHEMAS_H +#define SRC_BASE_UNITSSCHEMAS_H + +#include +#include +#include + +#include "UnitsSchema.h" +#include "UnitsSchemasSpecs.h" + +namespace Base +{ + +/** + * The interface to schema specifications + * Has pointer to current schema + */ +class UnitsSchemas +{ +public: + explicit UnitsSchemas(const UnitsSchemasDataPack& pack); + + /** Make a schema and set as current*/ + void select(); // default + void select(const std::string_view& name); + void select(std::size_t num); + + /** Get a schema specification*/ + UnitsSchemaSpec spec(); // default, or the first spec + UnitsSchemaSpec spec(const std::string_view& name); + UnitsSchemaSpec spec(std::size_t num); + + size_t count() const; + std::vector names(); + std::vector descriptions(); + std::size_t getDecimals() const; + std::size_t defFractDenominator() const; + void setdefFractDenominator(std::size_t size); + + UnitsSchema* currentSchema() const; + +private: + /** DRY utils */ + std::vector getVec(const std::function& fn); + UnitsSchemaSpec findSpec(const std::function& fn); + void makeCurr(const UnitsSchemaSpec& spec); + + UnitsSchemasDataPack pack; + std::unique_ptr current {std::make_unique(spec())}; + std::size_t denominator; + std::size_t decimals; +}; + + +} // namespace Base +#endif // SRC_BASE_UNITSSCHEMAS_H diff --git a/src/Base/UnitsSchemasData.h b/src/Base/UnitsSchemasData.h new file mode 100644 index 0000000000..0c8ab3ca87 --- /dev/null +++ b/src/Base/UnitsSchemasData.h @@ -0,0 +1,749 @@ +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#ifndef BASE_UNITSSCHEMASDATA_H +#define BASE_UNITSSCHEMASDATA_H + +#include +#include + +#include + +#include "fmt/format.h" +#include "fmt/ranges.h" + +#include "UnitsSchemasSpecs.h" + +/** + * UnitSchemas raw data + */ + +namespace Base::UnitsSchemasData +{ + +constexpr std::size_t defDecimals {2}; +constexpr std::size_t defDenominator {8}; + +// NOLINTBEGIN +// clang-format off +inline const UnitsSchemaSpec s0 +{ 6, "MmMin", "mm" , false, false , QT_TRANSLATE_NOOP("UnitsApi", "Metric small parts & CNC (mm, mm/min)"), false, + { + { "Length", {{ 0 , "mm" , 1.0 }}}, + { "Angle", {{ 0 , "°" , 1.0 }}}, + { "Velocity", {{ 0 , "mm/min" , 1.0 / 60.0 }}} + } +}; + +inline const UnitsSchemaSpec s1 +{ 9, "MeterDecimal", "m", false, false, QT_TRANSLATE_NOOP("UnitsApi", "Meter decimal (m, m², m³)"), false, + { + { "Length", {{ 0 , "m" , 1e3 }}}, + { "Area", {{ 0 , "m²" , 1e6 }}}, + { "Volume", {{ 0 , "m³" , 1e9 }}}, + { "Power", {{ 0 , "W" , 1e6 }}}, + { "ElectricPotential", {{ 0 , "V" , 1e6 }}}, + { "HeatFlux", {{ 0 , "W/m²" , 1.0 }}}, + { "Velocity", {{ 0 , "m/s" , 1e3 }}} + } +}; + +inline const UnitsSchemaSpec s2 +{ 3, "ImperialDecimal", "in", false, false, QT_TRANSLATE_NOOP("UnitsApi", "Imperial decimal (in, lb)"), false, + { + { "Length", {{ 0 , "in" , 25.4 }}}, + { "Angle", {{ 0 , "°" , 1.0 }}}, + { "Area", {{ 0 , "in²" , 645.16 }}}, + { "Volume", {{ 0 , "in³" , 16387.064 }}}, + { "Mass", {{ 0 , "lb" , 0.45359237 }}}, + { "Pressure", {{ 0 , "psi" , 6.894744825494 }}}, + { "Stiffness", {{ 0 , "lbf/in" , 4.448222 / 0.0254 }}}, + { "Velocity", {{ 0 , "in/min" , 25.4 / 60 }}}, + { "Acceleration", {{ 0 , "in/min²" , 25.4 / 3600 }}} + } +}; + +inline const UnitsSchemaSpec s3 +{ 0, "Internal", "m", false, false, QT_TRANSLATE_NOOP("UnitsApi", "Internal (m, m², m³)"), true, + { + { "Length", { + { 1e-6 , "mm" , 1.0 }, + { 1e-3 , "nm" , 1e-6 }, + { 1e-1 , "μm" , 1e-3 }, + { 1e4 , "mm" , 1.0 }, + { 1e7 , "m" , 1e3 }, + { 1e10 , "mm" , 1e6 }, + { 0 , "m" , 1.0 }} + }, + { "Area", { + { 1e2 , "mm²" , 1.0 }, + { 1e6 , "cm²" , 1e2 }, + { 1e12 , "m²" , 1e6 }, + { 0 , "km²" , 1e12 }} + }, + { "Volume", { + { 1e3 , "mm³" , 1.0 }, + { 1e6 , "ml" , 1e3 }, + { 1e9 , "l" , 1e6 }, + { 0 , "m³" , 1e9 }} + }, + { "Angle", { + { 0 , "°" , 1.0 }} + }, + { "Mass", { + { 1e-6 , "μg" , 1.0 }, + { 1e-3 , "mg" , 1e-6 }, + { 1.0 , "g" , 1e-3 }, + { 1e3 , "kg" , 1.0 }, + { 0 , "t" , 1e3 }} + }, + { "Density", { + { 1e-4 , "kg/m³" , 1e-9 }, + { 1.0 , "kg/cm³" , 1e-3 }, + { 0 , "kg/mm³" , 1.0 }} + }, + { "ThermalConductivity", { + { 1e6 , "W/m/K" , 1e6 }, + { 0 , "W/mm/K" , 1e3 }} + }, + { "ThermalExpansionCoefficient", { + { 1e-3 , "μm/m/K" , 1e-6 }, + { 0 , "mm/mm/K" , 1.0 }} + }, + { "VolumetricThermalExpansionCoefficient", { + { 1e-3 , "mm³/m³/K" , 1e-9 }, + { 0 , "m³/m³/K" , 1.0 }} + }, + { "SpecificHeat", { + { 0 , "J/kg/K" , 1e6 }} + }, + { "ThermalTransferCoefficient", { + { 0 , "W/m²/K" , 1.0 }} + }, + { "Pressure", { + { 10.0 , "Pa" , 1e-3 }, + { 1e4 , "kPa" , 1.0 }, + { 1e7 , "MPa" , 1e3 }, + { 1e10 , "GPa" , 1e6 }, + { 0 , "Pa" , 1e-3 }} + }, + { "Stress", { + { 10.0 , "Pa" , 1e-3 }, + { 1e4 , "kPa" , 1.0 }, + { 1e7 , "MPa" , 1e3 }, + { 1e10 , "GPa" , 1e6 }, + { 0 , "Pa" , 1e-3 }} + }, + { "Stiffness", { + { 1e-3 , "Pa/m" , 1e-6 }, + { 1 , "mN/m" , 1e-3 }, + { 1e3 , "N/m" , 1.0 }, + { 1e6 , "kN/m" , 1e3 }, + { 0 , "MN/m" , 1e6 }} + }, + { "StiffnessDensity", { + { 1 , "kPa/m" , 1e-3 }, + { 1e3 , "MPa/m" , 1.0 }, + { 1e3 , "mN" , 1.0 }, + { 0 , "GPa/m" , 1e3 }} + }, + { "Force", { + { 1e6 , "N" , 1e3 }, + { 1e9 , "kN" , 1e6 }, + { 0 , "MN" , 1e9 }} + }, + { "Power", { + { 1e6 , "mW" , 1e3 }, + { 1e9 , "W" , 1e6 }, + { 0 , "kW" , 1e9 }} + }, + { "ElectricPotential", { + { 1e6 , "mV" , 1e3 }, + { 1e9 , "V" , 1e6 }, + { 1e12 , "kV" , 1e9 }, + { 0 , "V" , 1e6 }} + }, + { "Work", { + { 1.602176634e-10 , "eV" , 1.602176634e-13 }, + { 1.602176634e-7 , "keV" , 1.602176634e-10 }, + { 1.602176634e-4 , "MeV" , 1.602176634e-7 }, + { 1e6 , "mJ" , 1e3 }, + { 1e9 , "J" , 1e6 }, + { 1e12 , "kJ" , 1e9 }, + { 3.6e+15 , "kWh" , 3.6e+12 }, + { 0 , "J" , 1e6 }} + }, + { "SpecificEnergy", { + { 0 , "m²/s²" , 1e6 }} + }, + { "HeatFlux", { + { 0 , "W/m²" , 1.0 }} + }, + { "ElectricCharge", { + { 0 , "C" , 1.0 }} + }, + { "SurfaceChargeDensity", { + { 1e-4 , "C/m²" , 1e-6 }, + { 1e-2 , "C/cm²" , 1e-2 }, + { 0 , "C/mm²" , 1.0 }} + }, + { "VolumeChargeDensity", { + { 1e-4 , "C/m³" , 1e-9 }, + { 1e-2 , "C/cm³" , 1e-3 }, + { 0 , "C/mm³" , 1.0 }} + }, + { "CurrentDensity", { + { 1e-4 , "A/m²" , 1e-6 }, + { 1e-2 , "A/cm²" , 1e-2 }, + { 0 , "A/mm²" , 1 }} + }, + { "MagneticFluxDensity", { + { 1e-3 , "G" , 1e-4 }, + { 0 , "T" , 1.0 }} + }, + { "MagneticFieldStrength", { + { 0 , "A/m" , 1e-3 }} + }, + { "MagneticFlux", { + { 0 , "Wb" , 1e6 }} + }, + { "Magnetization", { + { 0 , "A/m" , 1e-3 }} + }, + { "ElectricalConductance", { + { 1e-9 , "μS" , 1e-12 }, + { 1e-6 , "mS" , 1e-9 }, + { 0 , "S" , 1e-6 }} + }, + { "ElectricalResistance", { + { 1e9 , "Ohm" , 1e6 }, + { 1e12 , "kOhm" , 1e9 }, + { 0 , "MOhm" , 1e12 }} + }, + { "ElectricalConductivity", { + { 0 , "MS/m" , 1e-3 }, + { 1e-3 , "mS/m" , 1e-12 }, + { 1.0 , "S/m" , 1e-9 }, + { 1e3 , "kS/m" , 1e-6 }} + }, + { "ElectricalCapacitance", { + { 1e-15 , "pF" , 1e-18 }, + { 1e-12 , "nF" , 1e-15 }, + { 1e-9 , "μF" , 1e-12 }, + { 1e-6 , "mF" , 1e-9 }, + { 0 , "F" , 1e-6 }} + }, + { "ElectricalInductance", { + { 1.0 , "nH" , 1e-3 }, + { 1e3 , "μH" , 1.0 }, + { 1e6 , "mH" , 1e3 }, + { 0 , "H" , 1e6 }} + }, + { "VacuumPermittivity", { + { 0 , "F/m" , 1e-9 }} + }, + { "Frequency", { + { 1e3 , "Hz" , 1.0 }, + { 1e6 , "kHz" , 1e3 }, + { 1e9 , "MHz" , 1e6 }, + { 1e12 , "GHz" , 1e9 }, + { 0 , "THz" , 1e12 }} + }, + { "Velocity", { + { 0 , "mm/s" , 1.0 }} + }, + { "DynamicViscosity", { + { 0 , "Pa*s" , 1e-3 }} + }, + { "KinematicViscosity", { + { 1e3 , "mm²/s" , 1.0 }, + { 0 , "m²/s" , 1e6 }} + }, + { "VolumeFlowRate", { + { 1e3 , "mm³/s" , 1.0 }, + { 1e6 , "ml/s" , 1e3 }, + { 1e9 , "l/s" , 1e6 }, + { 0 , "m³/s" , 1e9 }} + }, + { "DissipationRate", { + { 0 , "W/kg" , 1e6 }} + }, + { "InverseLength", { + { 1e-6 , "1/m" , 1e-3 }, + { 1e-3 , "1/km" , 1e-6 }, + { 1.0 , "1/m" , 1e-3 }, + { 1e3 , "1/mm" , 1.0 }, + { 1e6 , "1/μm" , 1e3 }, + { 1e9 , "1/nm" , 1e6 }, + { 0 , "1/m" , 1e-3 }} + }, + { "InverseArea", { + { 1e-12 , "1/m²" , 1e-6 }, + { 1e-6 , "1/km²" , 1e-12 }, + { 1.0 , "1/m²" , 1e-6 }, + { 1e2 , "1/cm²" , 1e-2 }, + { 0 , "1/mm²" , 1.0 }} + }, + { "InverseVolume", { + { 1e-6 , "1/m³" , 1e-9 }, + { 1e-3 , "1/l" , 1e-6 }, + { 1.0 , "1/ml" , 1e-3 }, + { 0 , "1/mm³" , 1.0 }} + } + } +}; + +inline const UnitsSchemaSpec s4 +{ 1, "MKS", "m", false, false, QT_TRANSLATE_NOOP("UnitsApi", "MKS (m, kg, s, °)") , false, + { + { "Length", { + { 1e-6 , "mm" , 1.0 }, + { 1e-3 , "nm" , 1e-6 }, + { 0.1 , "μm" , 1e-3 }, + { 1e4 , "mm" , 1.0 }, + { 1e7 , "m" , 1e3 }, + { 1e10 , "km" , 1e6 }, + { 0 , "m" , 1e3 }} + }, + { "Area", { + { 100 , "mm²" , 1.0 }, + { 1e6 , "cm²" , 100 }, + { 1e12 , "m²" , 1e6 }, + { 0 , "km²" , 1e12 }} + }, + { "Volume", { + { 1e3 , "mm³" , 1.0 }, + { 1e6 , "ml" , 1e3 }, + { 1e9 , "l" , 1e6 }, + { 0 , "m³" , 1e9 }} + }, + { "Mass", { + { 1e-6 , "μg" , 1e-9 }, + { 1e-3 , "mg" , 1e-6 }, + { 1.0 , "g" , 1e-3 }, + { 1e3 , "kg" , 1.0 }, + { 0 , "t" , 1e3 }} + }, + { "Density", { + { 0.0001 , "kg/m³" , 0.000000001 }, + { 1.0 , "kg/cm³" , 0.001 }, + { 0 , "kg/mm³" , 1.0 }} + }, + { "Acceleration", { + { 0 , "m/s²" , 1000.0 }} + }, + { "Pressure", { + { 10.0 , "Pa" , 0.001 }, + { 10'000.0 , "kPa" , 1.0 }, + { 10'000'000.0 , "MPa" , 1'000.0 }, + { 10'000'000'000.0 , "GPa" , 1'000'000.0 }, + { 0 , "Pa" , 1000.0 }} + }, + { "Stress", { + { 10.0 , "Pa" , 0.001 }, + { 10'000.0 , "kPa" , 1.0 }, + { 10'000'000.0 , "MPa" , 1'000.0 }, + { 10'000'000'000.0 , "GPa" , 1'000'000.0 }, + { 0 , "Pa" , 0.001 }} + }, + { "Stiffness", { + { 1 , "mN/m" , 1e-3 }, + { 1e3 , "N/m" , 1.0 }, + { 1e6 , "kN/m" , 1e3 }, + { 0 , "MN/m" , 1e6 }} + }, + { "StiffnessDensity", { + { 1e-3 , "Pa/m" , 1e-6 }, + { 1 , "kPa/m" , 1e-3 }, + { 1e3 , "MPa/m" , 1.0 }, + { 0 , "GPa/m" , 1e3 }} + }, + { "ThermalConductivity", { + { 1'000'000 , "W/mm/K" , 1'000'000.0 }, + { 0 , "W/m/K" , 1'000.0 }} + }, + { "ThermalExpansionCoefficient", { + { 0.001 , "μm/m/K" , 0.000001 }, + { 0 , "m/m/K" , 1.0 }} + }, + { "VolumetricThermalExpansionCoefficient", { + { 0.001 , "mm³/m³/K" , 1e-9 }, + { 0 , "m³/m³/K" , 1.0 }} + }, + { "SpecificHeat", { + { 0 , "J/kg/K" , 1'000'000.0 }} + }, + { "ThermalTransferCoefficient", { + { 0 , "W/m²/K" , 1.0 }} + }, + { "Force", { + { 1e3 , "mN" , 1.0 }, + { 1e6 , "N" , 1e3 }, + { 1e9 , "kN" , 1e6 }, + { 0 , "MN" , 1e9 }} + }, + { "Power", { + { 1e6 , "mW" , 1e3 }, + { 1e9 , "W" , 1e6 }, + { 0 , "kW" , 1e9 }} + }, + { "ElectricPotential", { + { 1e6 , "mV" , 1e3 }, + { 1e9 , "V" , 1e6 }, + { 1e12 , "kV" , 1e9 }, + { 0 , "V" , 1e6 }} + }, + { "ElectricCharge", { + { 0 , "C" , 1.0 }} + }, + { "SurfaceChargeDensity", { + { 0 , "C/m²" , 1e-6 }} + }, + { "VolumeChargeDensity", { + { 0 , "C/m³" , 1e-9 }} + }, + { "CurrentDensity", { + { 1e3 , "A/m²" , 1e-6 }, + { 0 , "A/mm²" , 1.0 }} + }, + { "MagneticFluxDensity", { + { 1e-3 , "G" , 1e-4 }, + { 0 , "T" , 1.0 }} + }, + { "MagneticFieldStrength", { + { 0 , "A/m" , 1e-3 }} + }, + { "MagneticFlux", { + { 0 , "Wb" , 1e6 }} + }, + { "Magnetization", { + { 0 , "A/m" , 1e-3 }} + }, + { "ElectricalConductance", { + { 1e-9 , "μS" , 1e-12 }, + { 1e-6 , "mS" , 1e-9 }, + { 0 , "S" , 1e-6 }} + }, + { "ElectricalResistance", { + { 1e9 , "Ohm" , 1e6 }, + { 1e12 , "kOhm" , 1e9 }, + { 0 , "MOhm" , 1e12 }} + }, + { "ElectricalConductivity", { + { 1e-3 , "mS/m" , 1e-12 }, + { 1.0 , "S/m" , 1e-9 }, + { 1e3 , "kS/m" , 1e-6 }, + { 0 , "MS/m" , 1e-3 }} + }, + { "ElectricalCapacitance", { + { 1e-15 , "pF" , 1e-18 }, + { 1e-12 , "nF" , 1e-15 }, + { 1e-9 , "μ" "F" , 1e-12 }, + { 1e-6 , "mF" , 1e-9 }, + { 0 , "F" , 1e-6 }} + }, + { "ElectricalInductance", { + { 1e-6 , "nH" , 1e-3 }, + { 1e-3 , "μH" , 1.0 }, + { 1.0 , "mH" , 1e3 }, + { 0 , "H" , 1e6 }} + }, + { "VacuumPermittivity", { + { 0 , "F/m" , 1e-9 }} + }, + { "Work", { + { 1.602176634e-10 , "eV" , 1.602176634e-13 }, + { 1.602176634e-7 , "keV" , 1.602176634e-10 }, + { 1.602176634e-4 , "MeV" , 1.602176634e-7 }, + { 1e6 , "mJ" , 1e3 }, + { 1e9 , "J" , 1e6 }, + { 1e12 , "kJ" , 1e9 }, + { 3.6e+15 , "kWh" , 3.6e+12 }, + { 0 , "J" , 1e6 }} + }, + { "SpecificEnergy", { + { 0 , "m²/s²" , 1000000 }} + }, + { "HeatFlux", { + { 0 , "W/m²" , 1.0 }} + }, + { "Frequency", { + { 1e3 , "Hz" , 1.0 }, + { 1e6 , "kHz" , 1e3 }, + { 1e9 , "MHz" , 1e6 }, + { 1e12 , "GHz" , 1e9 }, + { 0 , "THz" , 1e12 }} + }, + { "Velocity", { + { 0 , "m/s" , 1000.0 }} + }, + { "DynamicViscosity", { + { 0 , "Pa*s" , 0.001 }} + }, + { "KinematicViscosity", { + { 0 , "m²/s" , 1e6 }} + }, + { "VolumeFlowRate", { + { 1e-3 , "m³/s" , 1e9 }, + { 1e3 , "mm³/s" , 1.0 }, + { 1e6 , "ml/s" , 1e3 }, + { 1e9 , "l/s" , 1e6 }, + { 0 , "m³/s" , 1e9 }} + }, + { "DissipationRate", { + { 0 , "W/kg" , 1e6 }} + }, + { "InverseLength", { + { 1e-6 , "1/m" , 1e-3 }, + { 1e-3 , "1/km" , 1e-6 }, + { 1.0 , "1/m" , 1e-3 }, + { 1e3 , "1/mm" , 1.0 }, + { 1e6 , "1/μm" , 1e3 }, + { 1e9 , "1/nm" , 1e6 }, + { 0 , "1/m" , 1e-3 }} + }, + { "InverseArea", { + { 1e-12 , "1/m²" , 1e-6 }, + { 1e-6 , "1/km²" , 1e-12 }, + { 1.0 , "1/m²" , 1e-6 }, + { 1e2 , "1/cm²" , 1e-2 }, + { 0 , "1/mm²" , 1.0 }} + }, + { "InverseVolume", { + { 1e-6 , "1/m³" , 1e-9 }, + { 1e-3 , "1/l" , 1e-6 }, + { 1.0 , "1/ml" , 1e-3 }, + { 0 , "1/mm³" , 1.0 }} + } + } +}; + +inline const UnitsSchemaSpec s5 +{ 4, "Centimeter", "cm", false, false, QT_TRANSLATE_NOOP("UnitsApi", "Building Euro (cm, m², m³)") , false, + { + { "Length", { + { 0 , "cm" , 10.0 }} + }, + { "Area", { + { 0 , "m²" , 1e6 }} + }, + { "Volume", { + { 0 , "m³" , 1e9 }} + }, + { "Power", { + { 0 , "W" , 1e6 }} + }, + { "ElectricPotential", { + { 0 , "V" , 1e6 }} + }, + { "HeatFlux", { + { 0 , "W/m²" , 1.0 }} + }, + { "Velocity", { + { 0 , "mm/min" , 1.0 / 60 }} + } + } +}; + +inline const UnitsSchemaSpec s6 +{ 8, "FEM", "mm", false , false , QT_TRANSLATE_NOOP("UnitsApi", "FEM (mm, N, s)"), false, + { + { "Length", { + { 0 , "mm" , 1.0 }} + }, + { "Mass", { + { 0 , "t" , 1e3 }} + } + } +}; + +inline const UnitsSchemaSpec s7 +{ 2, "Imperial", "in", false, false, QT_TRANSLATE_NOOP("UnitsApi", "US customary (in, lb)"), false, + { + { "Length", { + { 0.00000254 , "in" , 25.4 }, + { 2.54 , "thou" , 0.0254 }, + { 304.8 , "″" , 25.4 }, + { 914.4 , "′" , 304.8 }, + { 1'609'344.0 , "yd" , 914.4 }, + { 1'609'344'000.0 , "mi" , 1'609'344.0 }, + { 0 , "in" , 25.4 }} + }, + { "Angle", { + { 0 , "°" , 1.0 }} + }, + { "Area", { + { 0 , "in²" , 645.16 }} + }, + { "Volume", { + { 0 , "in³" , 16'387.064 }} + }, + { "Mass", { + { 0 , "lb" , 0.45359237 }} + }, + { "Pressure", { + { 6'894.744 , "psi" , 6.894744825494 }, + { 6'894'744.825 , "ksi" , 6'894.744825494 }, + { 0 , "psi" , 6.894744825494 }} + }, + { "Stiffness", { + { 0 , "lbf/in" , 4.448222 / 0.0254 }} + }, + { "Velocity", { + { 0 , "in/min" , 25.4 / 60 }} + } + } +}; + +inline const UnitsSchemaSpec s8 +{ 5, "ImperialBuilding", "ft", true, false , QT_TRANSLATE_NOOP("UnitsApi", "Building US (ft-in, sqft, cft)"), false, + { + { "Length" , {{ 0 , "toFractional" , 0 }}}, // <== ! + { "Angle" , {{ 0 , "°" , 1.0 }}}, + { "Area" , {{ 0 , "sqft" , 92'903.04 }}}, + { "Volume" , {{ 0 , "cft" , 28'316'846.592 }}}, + { "Velocity" , {{ 0 , "in/min" , 25.4 / 60 }}} + } +}; + +inline const UnitsSchemaSpec s9 +{ 7, "ImperialCivil", "ft", false, true, QT_TRANSLATE_NOOP("UnitsApi", "Imperial for Civil Eng (ft, ft/s)"), false, + { + { "Angle" , {{ 0 , "toDMS" , 0 }}} // <== ! + } +}; + +// clang-format on +// NOLINTEND +inline const std::vector schemaSpecs {s3, s4, s5, s6, s7, s8, s9, s0, s1, s2}; + +/** + * Special functions + * + * A schema unit can have custom formatting via a special function + * Such functions must be included here and also registered in special functions caller (below) + */ + +/** utility function for toFractional */ +inline std::size_t greatestCommonDenominator(const std::size_t a, const std::size_t b) +{ + return b == 0 ? a : greatestCommonDenominator(b, a % b); // Euclid's algorithm +} + +/** + * double -> [feet′][inches[-fraction]″], e.g.: 3′4-1/4″ + */ +inline std::string toFractional(const double value) +{ + constexpr auto inchPerFoot {12}; + constexpr auto mmPerInch {25.4}; + + auto numFractUnits = + static_cast(std::round(std::abs(value) / mmPerInch * defDenominator)); + if (numFractUnits == 0) { + return "0"; + } + + const auto feet = + static_cast(std::floor(numFractUnits / (inchPerFoot * defDenominator))); + numFractUnits = numFractUnits - (inchPerFoot * defDenominator * feet); + const auto inches = static_cast(std::floor(numFractUnits / defDenominator)); + const std::size_t fractNumerator = numFractUnits - (defDenominator * inches); + + const std::size_t common_denom = greatestCommonDenominator(fractNumerator, defDenominator); + const std::size_t numerator = fractNumerator / common_denom; + const std::size_t denominator = defDenominator / common_denom; + + std::vector resultParts {}; + if (inches > 0) { + resultParts.push_back(fmt::format("{}", inches)); + if (numerator == 0) { + resultParts.emplace_back("″"); + } + } + if (numerator > 0) { + if (inches > 0) { + resultParts.emplace_back("-"); + } + resultParts.push_back(fmt::format("{}/{}″", numerator, denominator)); + } + + return fmt::format("{}{}{}", + value < 0 ? "-" : "", + feet > 0 ? fmt::format("{}′", feet) : "", + fmt::join(resultParts, "")); +} + +/** + * double -> degrees°[minutes′[seconds″]] + */ +inline std::string toDms(const double value) +{ + constexpr auto dmsRatio {60.0}; + + auto calc = [&](const double total) -> std::pair { + const double whole = std::floor(total); + return {static_cast(whole), dmsRatio * (total - whole)}; + }; + + auto [degrees, totalMinutes] = calc(value); + std::string out = fmt::format("{}°", degrees); + + if (totalMinutes > 0) { + auto [minutes, totalSeconds] = calc(totalMinutes); + out += fmt::format("{}′", minutes); + + if (totalSeconds > 0) { + out += fmt::format("{}″", std::round(totalSeconds)); + } + } + + return out; +} + + +/** + * Special functions caller + */ + +inline const std::map> specials // clang-format off +{ + { + { "toDMS" , [](const double val) { return toDms(val); }}, + { "toFractional" , [](const double val) { return toFractional(val); }} + } +}; // clang-format on + +inline std::string runSpecial(const std::string& name, const double value) +{ + return specials.contains(name) ? specials.at(name)(value) : ""; +} + + +/** + * Build data pack + */ + +inline const UnitsSchemasDataPack unitSchemasDataPack {schemaSpecs, defDecimals, defDenominator}; + + +} // namespace Base::UnitsSchemasData +#endif // BASE_UNITSSCHEMASDATA_H diff --git a/src/Base/UnitsSchemaMeterDecimal.h b/src/Base/UnitsSchemasSpecs.h similarity index 53% rename from src/Base/UnitsSchemaMeterDecimal.h rename to src/Base/UnitsSchemasSpecs.h index c3302602b9..b642385d37 100644 --- a/src/Base/UnitsSchemaMeterDecimal.h +++ b/src/Base/UnitsSchemasSpecs.h @@ -1,54 +1,69 @@ -/*************************************************************************** - * Copyright (c) 2023 WandererFan * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - -/* Metric units schema intended for design of large objects - * Lengths are always in metres. - * Angles in degrees (use degree symbol) - * Velocities in m/sec - */ - -#ifndef BASE_UNITSSCHEMAMETERS_H -#define BASE_UNITSSCHEMAMETERS_H - -#include "UnitsSchema.h" - -namespace Base -{ - -/** - * The UnitSchema class - */ -class UnitsSchemaMeterDecimal: public UnitsSchema -{ -public: - std::string - schemaTranslate(const Base::Quantity& quant, double& factor, std::string& unitString) override; - - std::string getBasicLengthUnit() const override - { - return {"m"}; - } -}; - -} // namespace Base - -#endif // BASE_UNITSSCHEMAMETRES_H +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#ifndef UNITSCHEMASPECS_H +#define UNITSCHEMASPECS_H + +#include +#include +#include +#include + +namespace Base +{ + + +struct UnitTranslationSpec +{ + double threshold {1}; + std::string unitString; + double factor {1}; + std::function fn {nullptr}; +}; + +struct UnitsSchemaSpec +{ + std::size_t num; + std::string name; + std::string basicLengthUnitStr; + bool isMultUnitLen {false}; + bool isMultUnitAngle {false}; + const char* description; + bool isDefault {false}; + + /** + * Applicable spec is the first with threshold > value under test + * Special case: Threshold = 0 : default + * Special case: Factor = 0 : unitString contains name of special function to run + */ + std::map> translationSpecs; +}; + +struct UnitsSchemasDataPack +{ + std::vector specs; + size_t defDecimals; + size_t defDenominator; +}; + + +} // namespace Base +#endif // UNITSCHEMASPECS_H diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp b/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp index 4ad1006204..6cec21e5d0 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp @@ -40,18 +40,18 @@ Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) Gui::GuiNativeEvent::~GuiNativeEvent() { if (spnav_close()) - Base::Console().Log("Couldn't disconnect from spacenav daemon\n"); + Base::Console().log("Couldn't disconnect from spacenav daemon\n"); else - Base::Console().Log("Disconnected from spacenav daemon\n"); + Base::Console().log("Disconnected from spacenav daemon\n"); } void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) { Q_UNUSED(window) if (spnav_open() == -1) { - Base::Console().Log("Couldn't connect to spacenav daemon. Please ignore if you don't have a spacemouse.\n"); + Base::Console().log("Couldn't connect to spacenav daemon. Please ignore if you don't have a spacemouse.\n"); } else { - Base::Console().Log("Connected to spacenav daemon\n"); + Base::Console().log("Connected to spacenav daemon\n"); QSocketNotifier* SpacenavNotifier = new QSocketNotifier(spnav_fd(), QSocketNotifier::Read, this); connect(SpacenavNotifier, SIGNAL(activated(int)), this, SLOT(pollSpacenav())); mainApp->setSpaceballPresent(true); diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp index f6bd8a955f..97d2cbb153 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp @@ -58,21 +58,21 @@ Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) Gui::GuiNativeEvent::~GuiNativeEvent() { if (spnav_close()) - Base::Console().Log("Couldn't disconnect from spacenav daemon\n"); + Base::Console().log("Couldn't disconnect from spacenav daemon\n"); else - Base::Console().Log("Disconnected from spacenav daemon\n"); + Base::Console().log("Disconnected from spacenav daemon\n"); } void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) { if (!QX11Info::isPlatformX11()) { - Base::Console().Log("Application is not running on X11\n"); + Base::Console().log("Application is not running on X11\n"); return; } if (spnav_x11_open(QX11Info::display(), window->winId()) == -1) { - Base::Console().Log("Couldn't connect to spacenav daemon on X11. Please ignore if you don't have a spacemouse.\n"); + Base::Console().log("Couldn't connect to spacenav daemon on X11. Please ignore if you don't have a spacemouse.\n"); } else { - Base::Console().Log("Connected to spacenav daemon on X11\n"); + Base::Console().log("Connected to spacenav daemon on X11\n"); mainApp->setSpaceballPresent(true); mainApp->installNativeEventFilter(new Gui::RawInputEventFilter(&xcbEventFilter)); } @@ -138,7 +138,7 @@ bool Gui::GuiNativeEvent::xcbEventFilter(void *xcb_void, long* result) return true; } default: - Base::Console().Log("Unknown spaceball event\n"); + Base::Console().log("Unknown spaceball event\n"); return true; } // end switch (navEvent.type) { } diff --git a/src/Gui/3Dconnexion/GuiNativeEventMac.cpp b/src/Gui/3Dconnexion/GuiNativeEventMac.cpp index c64462646f..776a05b9c3 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventMac.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventMac.cpp @@ -59,7 +59,7 @@ Gui::GuiNativeEvent::tdx_drv_handler(io_connect_t connection, static bool firstTime = true; if (firstTime) { firstTime = false; - Base::Console().Log("Call connexion handler\n"); + Base::Console().log("Call connexion handler\n"); } Q_UNUSED(connection) //printf("tdx_drv_handler\n"); @@ -75,7 +75,7 @@ Gui::GuiNativeEvent::tdx_drv_handler(io_connect_t connection, * assigned id when the connection to the driver was established. */ //printf("msg->client: %d, tdxClientID: %d\n", msg->client, tdxClientID); - Base::Console().Log("msg->client: %d, msg->command: %d\n", msg->client, msg->command); + Base::Console().log("msg->client: %d, msg->command: %d\n", msg->client, msg->command); if (msg->client == tdxClientID) { switch (msg->command) { @@ -139,7 +139,7 @@ Gui::GuiNativeEvent::~GuiNativeEvent() if (tdxClientID) UnregisterConnexionClient(tdxClientID); CleanupConnexionHandlers(); - Base::Console().Log("Disconnected from 3Dconnexion driver\n"); + Base::Console().log("Disconnected from 3Dconnexion driver\n"); } } @@ -150,7 +150,7 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) /* make sure the framework is installed */ if (SetConnexionHandlers == NULL) { - Base::Console().Log("3Dconnexion framework not found!\n"); + Base::Console().log("3Dconnexion framework not found!\n"); return; } /* install 3dx message handler in order to receive driver events */ @@ -158,7 +158,7 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) assert(err == 0); if (err) { - Base::Console().Log("Error installing 3Dconnexion handler\n"); + Base::Console().log("Error installing 3Dconnexion handler\n"); return; } /* register our app with the driver */ @@ -169,7 +169,7 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) kConnexionMaskAll ); if (tdxClientID == 0) { - Base::Console().Log("Couldn't connect to 3Dconnexion driver\n"); + Base::Console().log("Couldn't connect to 3Dconnexion driver\n"); return; } @@ -177,7 +177,7 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) SetConnexionClientMask(tdxClientID, kConnexionMaskAll); SetConnexionClientButtonMask(tdxClientID, kConnexionMaskAllButtons); - Base::Console().Log("3Dconnexion driver initialized. Client ID: %d\n", tdxClientID); + Base::Console().log("3Dconnexion driver initialized. Client ID: %d\n", tdxClientID); mainApp->setSpaceballPresent(true); } diff --git a/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp b/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp index fab331926a..8ab68da1e9 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp @@ -262,7 +262,7 @@ Gui::GuiNativeEvent::~GuiNativeEvent() { if (gMouseInput == this) { gMouseInput = 0; - Base::Console().Log("3Dconnexion device detached.\n"); + Base::Console().log("3Dconnexion device detached.\n"); } } @@ -277,14 +277,14 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *mainWindow) gMouseInput = this; qApp->installNativeEventFilter( new Gui::RawInputEventFilter(Gui::GuiNativeEvent::RawInputEventFilter)); - Base::Console().Log("3Dconnexion device initialized.\n"); + Base::Console().log("3Dconnexion device initialized.\n"); } else { - Base::Console().Log("3Dconnexion device is attached, but not initialized.\n"); + Base::Console().log("3Dconnexion device is attached, but not initialized.\n"); } } else { - Base::Console().Log("3Dconnexion device not attached.\n"); + Base::Console().log("3Dconnexion device not attached.\n"); } } diff --git a/src/Gui/Action.cpp b/src/Gui/Action.cpp index 2c940ca0a7..395095c408 100644 --- a/src/Gui/Action.cpp +++ b/src/Gui/Action.cpp @@ -553,7 +553,7 @@ QList ActionGroup::actions() const int ActionGroup::checkedAction() const { auto checked = groupAction()->checkedAction(); - + return actions().indexOf(checked); } @@ -680,7 +680,7 @@ void WorkbenchGroup::refreshWorkbenchList() QString tip = Application::Instance->workbenchToolTip(wbName); QAction* action = getOrCreateAction(wbName); - + groupAction()->addAction(action); action->setText(name); @@ -1083,7 +1083,7 @@ void RecentMacrosAction::setFiles(const QStringList& files) " Recent Macros menu -> Keyboard Modifiers this should be Ctrl+Shift+" " by default, if this is now blank then you should revert it back to" " Ctrl+Shift+ by pressing both keys at the same time."); - Base::Console().Warning("%s\n", qPrintable(msgMain)); + Base::Console().warning("%s\n", qPrintable(msgMain)); } } @@ -1143,7 +1143,7 @@ void RecentMacrosAction::activateFile(int id) // handle SystemExit exceptions Base::PyGILStateLocker locker; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } } diff --git a/src/Gui/Application.cpp b/src/Gui/Application.cpp index bf26e49e1b..1fbef607ed 100644 --- a/src/Gui/Application.cpp +++ b/src/Gui/Application.cpp @@ -586,7 +586,7 @@ Application::Application(bool GUIenabled) Application::~Application() { - Base::Console().Log("Destruct Gui::Application\n"); + Base::Console().log("Destruct Gui::Application\n"); #ifdef USE_3DCONNEXION_NAVLIB delete pNavlibInterface; #endif @@ -681,7 +681,7 @@ void Application::open(const char* FileName, const char* Module) } catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow - e.ReportException(); + e.reportException(); } } else { @@ -780,7 +780,7 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch } catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow - e.ReportException(); + e.reportException(); } } else { @@ -852,7 +852,7 @@ void Application::exportTo(const char* FileName, const char* DocName, const char } catch (const Base::PyException& e) { // Usually thrown if the file is invalid somehow - e.ReportException(); + e.reportException(); wc.restoreCursor(); QMessageBox::critical(getMainWindow(), QObject::tr("Export failed"), @@ -917,7 +917,7 @@ void Application::slotDeleteDocument(const App::Document& Doc) { std::map::iterator doc = d->documents.find(&Doc); if (doc == d->documents.end()) { - Base::Console().Log("GUI document '%s' already deleted\n", Doc.getName()); + Base::Console().log("GUI document '%s' already deleted\n", Doc.getName()); return; } @@ -1007,7 +1007,7 @@ void Application::checkForRecomputes() { try { doc->recompute({}, false, &hasError); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); hasError = true; } } @@ -1072,12 +1072,12 @@ void Application::slotActiveDocument(const App::Document& Doc) "User parameter:BaseApp/Preferences/Units"); if (!hGrp->GetBool("IgnoreProjectSchema")) { int userSchema = Doc.UnitSystem.getValue(); - Base::UnitsApi::setSchema(static_cast(userSchema)); + Base::UnitsApi::setSchema(userSchema); getMainWindow()->setUserSchema(userSchema); Application::Instance->onUpdate(); } else { // set up Unit system default - Base::UnitsApi::setSchema((Base::UnitSystem)hGrp->GetInt("UserSchema", 0)); + Base::UnitsApi::setSchema(hGrp->GetInt("UserSchema", 0)); Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); } signalActiveDocument(*doc->second); @@ -1159,20 +1159,20 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } catch (const std::exception& e) { - Base::Console().Error( + Base::Console().error( "Unhandled std::exception caught in Application::onLastWindowClosed.\n" "The error message is: %s\n", e.what()); } catch (...) { - Base::Console().Error( + Base::Console().error( "Unhandled unknown exception caught in Application::onLastWindowClosed.\n"); } } @@ -1339,7 +1339,7 @@ void Application::setActiveDocument(Gui::Document* pcDocument) Base::Interpreter().runString(nameGui.c_str()); } catch (const Base::Exception& e) { - Base::Console().Warning(e.what()); + Base::Console().warning(e.what()); return; } @@ -1347,12 +1347,12 @@ void Application::setActiveDocument(Gui::Document* pcDocument) // May be useful for error detection if (d->activeDocument) { App::Document* doc = d->activeDocument->getDocument(); - Base::Console().Log("Active document is %s (at %p)\n", + Base::Console().log("Active document is %s (at %p)\n", doc->getName(), static_cast(doc)); } else { - Base::Console().Log("No active document\n"); + Base::Console().log("No active document\n"); } #endif @@ -1435,7 +1435,7 @@ void Application::viewActivated(MDIView* pcView) { #ifdef FC_DEBUG // May be useful for error detection - Base::Console().Log("Active view is %s (at %p)\n", + Base::Console().log("Active view is %s (at %p)\n", (const char*)pcView->windowTitle().toUtf8(), static_cast(pcView)); #endif @@ -1683,12 +1683,12 @@ bool Application::activateWorkbench(const char* name) match = rx.match(msg); } - Base::Console().Error("%s\n", (const char*)msg.toUtf8()); + Base::Console().error("%s\n", (const char*)msg.toUtf8()); if (!d->startingUp) { - Base::Console().Error("%s\n", e.getStackTrace().c_str()); + Base::Console().error("%s\n", e.getStackTrace().c_str()); } else { - Base::Console().Log("%s\n", e.getStackTrace().c_str()); + Base::Console().log("%s\n", e.getStackTrace().c_str()); } if (!d->startingUp) { @@ -1979,20 +1979,20 @@ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QSt case QtInfoMsg: case QtDebugMsg: #ifdef FC_DEBUG - Base::Console().Message("%s\n", output.constData()); + Base::Console().message("%s\n", output.constData()); #else // do not stress user with Qt internals but write to log file if enabled - Base::Console().Log("%s\n", output.constData()); + Base::Console().log("%s\n", output.constData()); #endif break; case QtWarningMsg: - Base::Console().Warning("%s\n", output.constData()); + Base::Console().warning("%s\n", output.constData()); break; case QtCriticalMsg: - Base::Console().Error("%s\n", output.constData()); + Base::Console().error("%s\n", output.constData()); break; case QtFatalMsg: - Base::Console().Error("%s\n", output.constData()); + Base::Console().error("%s\n", output.constData()); abort(); // deliberately core dump } #ifdef FC_OS_WIN32 @@ -2010,13 +2010,13 @@ void messageHandlerCoin(const SoError* error, void* /*userdata*/) const char* msg = error->getDebugString().getString(); switch (dbg->getSeverity()) { case SoDebugError::INFO: - Base::Console().Message("%s\n", msg); + Base::Console().message("%s\n", msg); break; case SoDebugError::WARNING: - Base::Console().Warning("%s\n", msg); + Base::Console().warning("%s\n", msg); break; default: // error - Base::Console().Error("%s\n", msg); + Base::Console().error("%s\n", msg); break; } #ifdef FC_OS_WIN32 @@ -2027,7 +2027,7 @@ void messageHandlerCoin(const SoError* error, void* /*userdata*/) } else if (error) { const char* msg = error->getDebugString().getString(); - Base::Console().Log(msg); + Base::Console().log(msg); } } @@ -2046,7 +2046,7 @@ void Application::initApplication() { static bool init = false; if (init) { - Base::Console().Error("Tried to run Gui::Application::initApplication() twice!\n"); + Base::Console().error("Tried to run Gui::Application::initApplication() twice!\n"); return; } @@ -2230,7 +2230,7 @@ void tryRunEventLoop(GUISingleApplication& mainApp) try { boost::interprocess::file_lock flock(filename.c_str()); if (flock.try_lock()) { - Base::Console().Log("Init: Executing event loop...\n"); + Base::Console().log("Init: Executing event loop...\n"); QApplication::exec(); // Qt can't handle exceptions thrown from event handlers, so we need @@ -2246,13 +2246,13 @@ void tryRunEventLoop(GUISingleApplication& mainApp) fi.deleteFile(); } else { - Base::Console().Warning("Failed to create a file lock for the IPC.\n" + Base::Console().warning("Failed to create a file lock for the IPC.\n" "The application will be terminated\n"); } } catch (const boost::interprocess::interprocess_exception& e) { QString msg = QString::fromLocal8Bit(e.what()); - Base::Console().Warning("Failed to create a file lock for the IPC: %s\n", + Base::Console().warning("Failed to create a file lock for the IPC: %s\n", msg.toUtf8().constData()); } } @@ -2263,18 +2263,18 @@ void runEventLoop(GUISingleApplication& mainApp) tryRunEventLoop(mainApp); } catch (const Base::SystemExitException&) { - Base::Console().Message("System exit\n"); + Base::Console().message("System exit\n"); throw; } catch (const std::exception& e) { // catching nasty stuff coming out of the event loop - Base::Console().Error("Event loop left through unhandled exception: %s\n", e.what()); + Base::Console().error("Event loop left through unhandled exception: %s\n", e.what()); App::Application::destructObserver(); throw; } catch (...) { // catching nasty stuff coming out of the event loop - Base::Console().Error("Event loop left through unknown unhandled exception\n"); + Base::Console().error("Event loop left through unknown unhandled exception\n"); App::Application::destructObserver(); throw; } @@ -2286,7 +2286,7 @@ void Application::runApplication() StartupProcess::setupApplication(); // A new QApplication - Base::Console().Log("Init: Creating Gui::Application and QApplication\n"); + Base::Console().log("Init: Creating Gui::Application and QApplication\n"); int argc = App::Application::GetARGC(); GUISingleApplication mainApp(argc, App::Application::GetARGV()); @@ -2328,7 +2328,7 @@ void Application::runApplication() QTimer::singleShot(0, &mw, SLOT(delayedStartup())); // run the Application event loop - Base::Console().Log("Init: Entering event loop\n"); + Base::Console().log("Init: Entering event loop\n"); // boot phase reference point // https://forum.freecad.org/viewtopic.php?f=10&t=21665 @@ -2342,7 +2342,7 @@ void Application::runApplication() runEventLoop(mainApp); - Base::Console().Log("Finish: Event loop left\n"); + Base::Console().log("Finish: Event loop left\n"); } bool Application::hiddenMainWindow() @@ -2502,7 +2502,7 @@ QString Application::replaceVariablesInQss(QString qssText) qssText = qssText.replace(QStringLiteral("@ThemeAccentColor2"), accentColor2); qssText = qssText.replace(QStringLiteral("@ThemeAccentColor3"), accentColor3); - // Base::Console().Warning("%s\n", qssText.toStdString()); + // Base::Console().warning("%s\n", qssText.toStdString()); return qssText; } @@ -2519,7 +2519,7 @@ void Application::checkForDeprecatedSettings() ->GetBool("UseFCBakExtension", true); if (!useFCBakExtension) { // TODO: This should be translated - Base::Console().Warning("The `.FCStd#` backup format is deprecated and may " + Base::Console().warning("The `.FCStd#` backup format is deprecated and may " "be removed in future versions.\n" "To update, check the 'Preferences->General->Document->Use " "date and FCBak extension' option.\n"); @@ -2544,7 +2544,7 @@ void Application::checkForPreviousCrashes() } catch (const boost::interprocess::interprocess_exception& e) { QString msg = QString::fromLocal8Bit(e.what()); - Base::Console().Warning("Failed check for previous crashes because of IPC error: %s\n", + Base::Console().warning("Failed check for previous crashes because of IPC error: %s\n", msg.toUtf8().constData()); } } @@ -2602,7 +2602,7 @@ App::Document* Application::reopen(App::Document* doc) if (name == v.first->FileName.getValue()) { doc = const_cast(v.first); } - if (untouchedDocs.count(v.second)) { + if (untouchedDocs.contains(v.second)) { if (!v.second->isModified()) { continue; } @@ -2672,4 +2672,4 @@ void Application::getVerboseDPIStyleInfo(QTextStream& str) { << "/" << QApplication::primaryScreen()->devicePixelRatio() << "\n"; -} \ No newline at end of file +} diff --git a/src/Gui/ApplicationPy.cpp b/src/Gui/ApplicationPy.cpp index 6384187a62..f198251d75 100644 --- a/src/Gui/ApplicationPy.cpp +++ b/src/Gui/ApplicationPy.cpp @@ -661,7 +661,7 @@ PyObject* ApplicationPy::sOpen(PyObject * /*self*/, PyObject *args) FileHandler handler(fileName); if (!handler.openFile()) { QString ext = handler.extension(); - Base::Console().Error("File type '%s' not supported\n", ext.toLatin1().constData()); + Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData()); } } PY_CATCH; @@ -685,7 +685,7 @@ PyObject* ApplicationPy::sInsert(PyObject * /*self*/, PyObject *args) FileHandler handler(fileName); if (!handler.importFile(std::string(DocName ? DocName : ""))) { QString ext = handler.extension(); - Base::Console().Error("File type '%s' not supported\n", ext.toLatin1().constData()); + Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData()); } } PY_CATCH; @@ -787,7 +787,7 @@ PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) } } else { - Base::Console().Error("File type '%s' not supported\n", ext.toLatin1().constData()); + Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData()); } } PY_CATCH; @@ -806,7 +806,7 @@ PyObject* ApplicationPy::sSendActiveView(PyObject * /*self*/, PyObject *args) const char* ppReturn = nullptr; if (!Application::Instance->sendMsgToActiveView(psCommandStr,&ppReturn)) { if (!Base::asBoolean(suppress)) { - Base::Console().Warning("Unknown view command: %s\n",psCommandStr); + Base::Console().warning("Unknown view command: %s\n",psCommandStr); } } @@ -830,7 +830,7 @@ PyObject* ApplicationPy::sSendFocusView(PyObject * /*self*/, PyObject *args) const char* ppReturn = nullptr; if (!Application::Instance->sendMsgToFocusView(psCommandStr,&ppReturn)) { if (!Base::asBoolean(suppress)) { - Base::Console().Warning("Unknown view command: %s\n",psCommandStr); + Base::Console().warning("Unknown view command: %s\n",psCommandStr); } } diff --git a/src/Gui/Assistant.cpp b/src/Gui/Assistant.cpp index 947d40c6c0..d4f577da8d 100644 --- a/src/Gui/Assistant.cpp +++ b/src/Gui/Assistant.cpp @@ -106,7 +106,7 @@ bool Assistant::startAssistant() static bool first = true; if (first) { - Base::Console().Log("Help file at %s\n", (const char*)qhc.toUtf8()); + Base::Console().log("Help file at %s\n", (const char*)qhc.toUtf8()); first = false; } @@ -175,13 +175,13 @@ bool Assistant::startAssistant() void Assistant::readyReadStandardOutput() { QByteArray data = proc->readAllStandardOutput(); - Base::Console().Log("Help view: %s\n", data.constData()); + Base::Console().log("Help view: %s\n", data.constData()); } void Assistant::readyReadStandardError() { QByteArray data = proc->readAllStandardError(); - Base::Console().Log("Help view: %s\n", data.constData()); + Base::Console().log("Help view: %s\n", data.constData()); } #include "moc_Assistant.cpp" diff --git a/src/Gui/AutoSaver.cpp b/src/Gui/AutoSaver.cpp index e3c2d18408..6228221486 100644 --- a/src/Gui/AutoSaver.cpp +++ b/src/Gui/AutoSaver.cpp @@ -222,7 +222,7 @@ void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver) } } - Base::Console().Log("Save AutoRecovery file in %fs\n", Base::TimeElapsed::diffTimeF(startTime,Base::TimeElapsed())); + Base::Console().log("Save AutoRecovery file in %fs\n", Base::TimeElapsed::diffTimeF(startTime,Base::TimeElapsed())); hGrp->SetBool("SaveThumbnail",save); } } @@ -238,7 +238,7 @@ void AutoSaver::timerEvent(QTimerEvent * event) break; } catch (...) { - Base::Console().Error("Failed to auto-save document '%s'\n", it.first.c_str()); + Base::Console().error("Failed to auto-save document '%s'\n", it.first.c_str()); } } } diff --git a/src/Gui/BitmapFactory.cpp b/src/Gui/BitmapFactory.cpp index 0bb4f6c5eb..dfbe670102 100644 --- a/src/Gui/BitmapFactory.cpp +++ b/src/Gui/BitmapFactory.cpp @@ -271,7 +271,7 @@ QPixmap BitmapFactoryInst::pixmap(const char* name) const return icon; } - Base::Console().Warning("Cannot find icon: %s\n", name); + Base::Console().warning("Cannot find icon: %s\n", name); return QPixmap(Gui::BitmapFactory().pixmapFromSvg("help-browser", QSize(16, 16))); } diff --git a/src/Gui/CallTips.cpp b/src/Gui/CallTips.cpp index 44e2599489..159d16d4bc 100644 --- a/src/Gui/CallTips.cpp +++ b/src/Gui/CallTips.cpp @@ -392,7 +392,7 @@ void CallTipsList::extractTipsFromObject(Py::Object& obj, Py::List& list, QMapposition.setValue(basePosition - viewAdjust + riftPosition); - //Base::Console().Log("Eye(%d) Pos: %f, %f, %f ViewAdjust: %f, %f, %f \n",eye, eyePose[eye].Position.x, + //Base::Console().log("Eye(%d) Pos: %f, %f, %f ViewAdjust: %f, %f, %f \n",eye, eyePose[eye].Position.x, // eyePose[eye].Position.y, // eyePose[eye].Position.z, // eyeRenderDesc[eye].ViewAdjust.x, diff --git a/src/Gui/Command.cpp b/src/Gui/Command.cpp index c434a9cfe6..4c01a4040c 100644 --- a/src/Gui/Command.cpp +++ b/src/Gui/Command.cpp @@ -402,7 +402,7 @@ void Command::invoke(int i, TriggerSource trigger) // Do not query _pcAction since it isn't created necessarily #ifdef FC_LOGUSERACTION - Base::Console().Log("CmdG: %s\n",sName); + Base::Console().log("CmdG: %s\n",sName); #endif _invoke(i, bCanLog && !_busy); @@ -473,29 +473,29 @@ void Command::_invoke(int id, bool disablelog) throw; } catch (Base::PyException &e) { - e.ReportException(); + e.reportException(); } catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException e; - e.ReportException(); + e.reportException(); } catch (Base::AbortException&) { } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); // Pop-up a dialog for FreeCAD-specific exceptions QMessageBox::critical(Gui::getMainWindow(), QObject::tr("Exception"), QLatin1String(e.what())); } catch (std::exception &e) { - Base::Console().Error("C++ exception thrown (%s)\n", e.what()); + Base::Console().error("C++ exception thrown (%s)\n", e.what()); } catch (const char* e) { - Base::Console().Error("%s\n", e); + Base::Console().error("%s\n", e); } #ifndef FC_DEBUG catch (...) { - Base::Console().Error("Gui::Command::activated(%d): Unknown C++ exception thrown\n", id); + Base::Console().error("Gui::Command::activated(%d): Unknown C++ exception thrown\n", id); } #endif } @@ -667,7 +667,7 @@ void Command::_doCommand(const char *file, int line, DoCmd_Type eType, const cha QByteArray format = cmd.toUtf8(); #ifdef FC_LOGUSERACTION - Base::Console().Log("CmdC: %s\n", format.constData()); + Base::Console().log("CmdC: %s\n", format.constData()); #endif _runCommand(file,line,eType,format.constData()); @@ -721,7 +721,7 @@ void Command::_runCommand(const char *file, int line, DoCmd_Type eType, const ch Base::Interpreter().runString(sCmd); } catch(Py::Exception &) { - Base::PyException::ThrowException(); + Base::PyException::throwException(); } } @@ -955,7 +955,7 @@ void Command::printConflictingAccelerators() const { auto cmd = Application::Instance->commandManager().checkAcceleratorForConflicts(sAccel, this); if (cmd) - Base::Console().Warning("Accelerator conflict between %s (%s) and %s (%s)\n", sName, sAccel, cmd->sName, cmd->sAccel); + Base::Console().warning("Accelerator conflict between %s (%s) and %s (%s)\n", sName, sAccel, cmd->sName, cmd->sAccel); } Action * Command::createAction() @@ -1322,11 +1322,11 @@ void PythonCommand::activated(int iMsg) } } catch (const Base::PyException& e) { - Base::Console().Error("Running the Python command '%s' failed:\n%s\n%s", + Base::Console().error("Running the Python command '%s' failed:\n%s\n%s", sName, e.getStackTrace().c_str(), e.what()); } catch (const Base::Exception&) { - Base::Console().Error("Running the Python command '%s' failed, try to resume",sName); + Base::Console().error("Running the Python command '%s' failed, try to resume",sName); } } else { @@ -1395,7 +1395,7 @@ Action * PythonCommand::createAction() } } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } return pcAction; @@ -1559,7 +1559,7 @@ void PythonGroupCommand::activated(int iMsg) catch(Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException e; - Base::Console().Error("Running the Python command '%s' failed:\n%s\n%s", + Base::Console().error("Running the Python command '%s' failed:\n%s\n%s", sName, e.getStackTrace().c_str(), e.what()); } } @@ -1645,7 +1645,7 @@ Action * PythonGroupCommand::createAction() catch(Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException e; - Base::Console().Error("createAction() of the Python command '%s' failed:\n%s\n%s", + Base::Console().error("createAction() of the Python command '%s' failed:\n%s\n%s", sName, e.getStackTrace().c_str(), e.what()); } @@ -1878,9 +1878,9 @@ bool CommandManager::addTo(const char* Name, QWidget *pcWidget) if (_sCommands.find(Name) == _sCommands.end()) { // Print in release mode only a log message instead of an error message to avoid to annoy the user #ifdef FC_DEBUG - Base::Console().Error("CommandManager::addTo() try to add an unknown command (%s) to a widget!\n",Name); + Base::Console().error("CommandManager::addTo() try to add an unknown command (%s) to a widget!\n",Name); #else - Base::Console().Warning("Unknown command '%s'\n",Name); + Base::Console().warning("Unknown command '%s'\n",Name); #endif return false; } @@ -1977,7 +1977,7 @@ const Command* Gui::CommandManager::checkAcceleratorForConflicts(const char* acc if (newCombo.isEmpty()) return nullptr; auto newSequence = QKeySequence::fromString(newCombo); - if (newSequence.count() == 0) + if (newSequence.isEmpty()) return nullptr; // Does this command shortcut conflict with other commands already defined? @@ -1998,7 +1998,7 @@ const Command* Gui::CommandManager::checkAcceleratorForConflicts(const char* acc if (existingCombo.isEmpty()) continue; auto existingSequence = QKeySequence::fromString(existingCombo); - if (existingSequence.count() == 0) + if (existingSequence.isEmpty()) continue; // Exact match diff --git a/src/Gui/CommandDoc.cpp b/src/Gui/CommandDoc.cpp index bec6a42af0..3fc5199174 100644 --- a/src/Gui/CommandDoc.cpp +++ b/src/Gui/CommandDoc.cpp @@ -1365,7 +1365,7 @@ void StdCmdDelete::activated(int iMsg) for(auto &sel : sels) { auto obj = sel.getObject(); if (obj == nullptr){ - Base::Console().DeveloperWarning("StdCmdDelete::activated", + Base::Console().developerWarning("StdCmdDelete::activated", "App::DocumentObject pointer is nullptr\n"); continue; } @@ -1443,7 +1443,7 @@ void StdCmdDelete::activated(int iMsg) } catch (const Base::Exception& e) { QMessageBox::critical(getMainWindow(), QObject::tr("Delete failed"), QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); } catch (...) { QMessageBox::critical(getMainWindow(), QObject::tr("Delete failed"), QStringLiteral("Unknown error")); @@ -1954,7 +1954,7 @@ protected: abortCommand(); QMessageBox::critical(getMainWindow(), QObject::tr("Failed to paste expressions"), QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/CommandFeat.cpp b/src/Gui/CommandFeat.cpp index 3252ba52c6..a16c801daf 100644 --- a/src/Gui/CommandFeat.cpp +++ b/src/Gui/CommandFeat.cpp @@ -293,7 +293,7 @@ void StdCmdSendToPythonConsole::activated(int iMsg) } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/CommandLink.cpp b/src/Gui/CommandLink.cpp index d0c1baea59..4eea6d8b81 100644 --- a/src/Gui/CommandLink.cpp +++ b/src/Gui/CommandLink.cpp @@ -195,7 +195,7 @@ void StdCmdLinkMakeGroup::activated(int option) { QMessageBox::critical(getMainWindow(), QObject::tr("Create link group failed"), QString::fromLatin1(e.what())); Command::abortCommand(); - e.ReportException(); + e.reportException(); } } @@ -260,7 +260,7 @@ void StdCmdLinkMake::activated(int) { Command::abortCommand(); QMessageBox::critical(getMainWindow(), QObject::tr("Create link failed"), QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); } } @@ -335,7 +335,7 @@ void StdCmdLinkMakeRelative::activated(int) { Command::abortCommand(); QMessageBox::critical(getMainWindow(), QObject::tr("Failed to create relative link"), QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); } return; } @@ -403,7 +403,7 @@ static void linkConvert(bool unlink) { auto obj = info.obj.getObject(); if(!parent || !obj || !parentVp) continue; - if(!recomputeSet.count(parent)) + if(!recomputeSet.contains(parent)) recomputeSet.emplace(parent,parent); auto doc = parent->getDocument(); App::DocumentObject *replaceObj; @@ -463,7 +463,7 @@ static void linkConvert(bool unlink) { Command::abortCommand(); auto title = unlink?QObject::tr("Unlink failed"):QObject::tr("Replace link failed"); QMessageBox::critical(getMainWindow(), title, QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); return; } } @@ -593,7 +593,7 @@ void StdCmdLinkImport::activated(int) { Command::abortCommand(); QMessageBox::critical(getMainWindow(), QObject::tr("Failed to import links"), QString::fromLatin1(e.what())); - e.ReportException(); + e.reportException(); } } @@ -633,7 +633,7 @@ void StdCmdLinkImportAll::activated(int) { QMessageBox::critical(getMainWindow(), QObject::tr("Failed to import all links"), QString::fromLatin1(e.what())); Command::abortCommand(); - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/CommandT.h b/src/Gui/CommandT.h index 6294f32702..5715c48dfb 100644 --- a/src/Gui/CommandT.h +++ b/src/Gui/CommandT.h @@ -262,10 +262,10 @@ void cmdAppDocumentArgs(const App::Document* doc, const std::string& cmd, Args&& doc->getName(), _cmd.c_str()); } catch (const std::exception& e) { - Base::Console().DeveloperError(doc->Label.getStrValue(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(doc->Label.getStrValue(),"%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().DeveloperError(doc->Label.getStrValue(),"App.getDocument('%s').%s\n", + Base::Console().developerError(doc->Label.getStrValue(),"App.getDocument('%s').%s\n", doc->getName(), _cmd.c_str()); throw; } @@ -385,10 +385,10 @@ void cmdAppObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Ar obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); } catch (const std::exception& e) { - Base::Console().DeveloperError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().DeveloperError(obj->getFullLabel(),"App.getDocument('%s').getObject('%s').%s\n", + Base::Console().developerError(obj->getFullLabel(),"App.getDocument('%s').getObject('%s').%s\n", obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); throw; } @@ -410,10 +410,10 @@ void cmdGuiObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Ar obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); } catch (const std::exception& e) { - Base::Console().DeveloperError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().DeveloperError(obj->getFullLabel(),"Gui.getDocument('%s').getObject('%s').%s\n", + Base::Console().developerError(obj->getFullLabel(),"Gui.getDocument('%s').getObject('%s').%s\n", obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); throw; } @@ -443,10 +443,10 @@ void doCommandT(Gui::Command::DoCmd_Type cmdType, const std::string& cmd, Args&& Gui::Command::doCommand(cmdType,"%s", _cmd.c_str()); } catch (const std::exception& e) { - Base::Console().DeveloperError("doCommandT","%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError("doCommandT","%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().DeveloperError("doCommandT","%s\n", _cmd.c_str()); + Base::Console().developerError("doCommandT","%s\n", _cmd.c_str()); throw; } } diff --git a/src/Gui/CommandTest.cpp b/src/Gui/CommandTest.cpp index 00f3888803..1828080a13 100644 --- a/src/Gui/CommandTest.cpp +++ b/src/Gui/CommandTest.cpp @@ -588,7 +588,7 @@ public: } this->deleteLater(); - Base::Console().Message("Thread with %d steps finished\n",this->steps); + Base::Console().message("Thread with %d steps finished\n",this->steps); } private: @@ -728,7 +728,7 @@ public: int matchLog{0}; int matchCritical{0}; TestConsoleObserver() = default; - void SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) override{ (void) notifiername; @@ -765,7 +765,7 @@ public: void run() override { for (int i=0; i<10; i++) - Base::Console().Message("Write a message to the console output.\n"); + Base::Console().message("Write a message to the console output.\n"); } }; @@ -775,7 +775,7 @@ public: void run() override { for (int i=0; i<10; i++) - Base::Console().Warning("Write a warning to the console output.\n"); + Base::Console().warning("Write a warning to the console output.\n"); } }; @@ -785,7 +785,7 @@ public: void run() override { for (int i=0; i<10; i++) - Base::Console().Error("Write an error to the console output.\n"); + Base::Console().error("Write an error to the console output.\n"); } }; @@ -795,7 +795,7 @@ public: void run() override { for (int i=0; i<10; i++) - Base::Console().Log("Write a log to the console output.\n"); + Base::Console().log("Write a log to the console output.\n"); } }; @@ -805,7 +805,7 @@ public: void run() override { for (int i=0; i<10; i++) - Base::Console().Critical("Write a critical message to the console output.\n"); + Base::Console().critical("Write a critical message to the console output.\n"); } }; @@ -815,17 +815,17 @@ void CmdTestConsoleOutput::activated(int iMsg) { Q_UNUSED(iMsg); TestConsoleObserver obs; - Base::Console().AttachObserver(&obs); + Base::Console().attachObserver(&obs); QThreadPool::globalInstance()->start(new ConsoleMessageTask); QThreadPool::globalInstance()->start(new ConsoleWarningTask); QThreadPool::globalInstance()->start(new ConsoleErrorTask); QThreadPool::globalInstance()->start(new ConsoleLogTask); QThreadPool::globalInstance()->start(new ConsoleCriticalTask); QThreadPool::globalInstance()->waitForDone(); - Base::Console().DetachObserver(&obs); + Base::Console().detachObserver(&obs); if (obs.matchMsg > 0 || obs.matchWrn > 0 || obs.matchErr > 0 || obs.matchLog > 0 || obs.matchCritical > 0) { - Base::Console().Error("Race condition in Console class\n"); + Base::Console().error("Race condition in Console class\n"); } } diff --git a/src/Gui/CommandView.cpp b/src/Gui/CommandView.cpp index 42d6fcd2cd..c2498240ad 100644 --- a/src/Gui/CommandView.cpp +++ b/src/Gui/CommandView.cpp @@ -2523,7 +2523,7 @@ void StdCmdViewIvIssueCamPos::activated(int iMsg) Temp += Temp2; Temp += "\")"; - Base::Console().Message("%s\n",Temp2.c_str()); + Base::Console().message("%s\n",Temp2.c_str()); getGuiApplication()->macroManager()->addLine(MacroManager::Gui,Temp.c_str()); } @@ -2612,7 +2612,7 @@ public: { if (currentSelectionHandler) { - Base::Console().Message("SelectionCallbackHandler: A selection handler already active."); + Base::Console().message("SelectionCallbackHandler: A selection handler already active."); return; } diff --git a/src/Gui/DAGView/DAGModel.cpp b/src/Gui/DAGView/DAGModel.cpp index 887ba29922..f27aa085b0 100644 --- a/src/Gui/DAGView/DAGModel.cpp +++ b/src/Gui/DAGView/DAGModel.cpp @@ -546,7 +546,7 @@ void Model::updateSlot() } catch(const boost::not_a_dag &) { - Base::Console().Error("not a dag exception in DAGView::Model::updateSlot()\n"); + Base::Console().error("not a dag exception in DAGView::Model::updateSlot()\n"); //do not continuously report an error for cyclic graphs graphDirty = false; return; @@ -1096,7 +1096,7 @@ void Model::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) contextMenu.addAction(editingFinishedAction); } - if (contextMenu.actions().count() > 0) + if (!contextMenu.actions().isEmpty()) contextMenu.exec(event->screenPos()); } diff --git a/src/Gui/Dialogs/DlgAddProperty.cpp b/src/Gui/Dialogs/DlgAddProperty.cpp index af04c125e3..330949e3cc 100644 --- a/src/Gui/Dialogs/DlgAddProperty.cpp +++ b/src/Gui/Dialogs/DlgAddProperty.cpp @@ -138,12 +138,12 @@ void DlgAddProperty::accept() (*it)->addDynamicProperty(type.c_str(),name.c_str(), group.c_str(),ui->edtDoc->toPlainText().toUtf8().constData()); } catch(Base::Exception &e) { - e.ReportException(); + e.reportException(); for(auto it2=containers.begin();it2!=it;++it2) { try { (*it2)->removeDynamicProperty(name.c_str()); } catch(Base::Exception &e) { - e.ReportException(); + e.reportException(); } } QMessageBox::critical(getMainWindow(), diff --git a/src/Gui/Dialogs/DlgAddPropertyVarSet.cpp b/src/Gui/Dialogs/DlgAddPropertyVarSet.cpp index 525dd99804..94011897c6 100644 --- a/src/Gui/Dialogs/DlgAddPropertyVarSet.cpp +++ b/src/Gui/Dialogs/DlgAddPropertyVarSet.cpp @@ -460,7 +460,7 @@ bool DlgAddPropertyVarSet::createProperty() group.c_str(), doc.c_str()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); critical(QObject::tr("Add property"), QObject::tr("Failed to add property to '%1': %2").arg( QString::fromLatin1(varSet->getFullName().c_str()), diff --git a/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp b/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp index 5336840d02..70a92a304a 100644 --- a/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp +++ b/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp @@ -186,7 +186,7 @@ void ButtonModel::load3DConnexionButtons(const char *RequiredDeviceName) catch (const std::exception& e) { // We don't mind not finding the file to be opened - Base::Console().Warning("%s\n", e.what()); + Base::Console().warning("%s\n", e.what()); } } @@ -201,7 +201,7 @@ QVariant ButtonModel::data (const QModelIndex &index, int role) const GroupVector groupVector = spaceballButtonGroup()->GetGroups(); if (index.row() >= (int)groupVector.size()) { - Base::Console().Log("index error in ButtonModel::data\n"); + Base::Console().log("index error in ButtonModel::data\n"); return {}; } if (role == Qt::DisplayRole) @@ -913,7 +913,7 @@ QStringList DlgCustomizeSpaceball::getModels() catch (const std::exception& e) { // We don't mind not finding the file to be opened - Base::Console().Warning("%s\n", e.what()); + Base::Console().warning("%s\n", e.what()); } return modelList; diff --git a/src/Gui/Dialogs/DlgMacroExecute.ui b/src/Gui/Dialogs/DlgMacroExecute.ui index 3be506ef36..8ddbff5ac7 100644 --- a/src/Gui/Dialogs/DlgMacroExecute.ui +++ b/src/Gui/Dialogs/DlgMacroExecute.ui @@ -313,42 +313,55 @@ - - - - User macros location: - - - - 9 - - - 9 - - - 9 - - - 9 - - - 6 - - - - - Qt::StrongFocus - - - Gui::FileChooser::Directory - - - - - - + + + + User macros location: + + + + 9 + + + 9 + + + 9 + + + 9 + + + 6 + + + + + Qt::StrongFocus + + + Gui::FileChooser::Mode::Directory + + + + + + + true + + + Open folder with macros in system file manager. + + + Open folder + + + + + + @@ -371,6 +384,7 @@ toolbarButton addonsButton fileChooser + folderButton diff --git a/src/Gui/Dialogs/DlgMacroExecuteImp.cpp b/src/Gui/Dialogs/DlgMacroExecuteImp.cpp index 24f793d5b8..1c7649a24b 100644 --- a/src/Gui/Dialogs/DlgMacroExecuteImp.cpp +++ b/src/Gui/Dialogs/DlgMacroExecuteImp.cpp @@ -22,6 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include @@ -152,6 +153,8 @@ void DlgMacroExecuteImp::setupConnections() this, &DlgMacroExecuteImp::onToolbarButtonClicked); connect(ui->addonsButton, &QPushButton::clicked, this, &DlgMacroExecuteImp::onAddonsButtonClicked); + connect(ui->folderButton, &QPushButton::clicked, + this, &DlgMacroExecuteImp::onFolderButtonClicked); connect(ui->userMacroListBox, &QTreeWidget::currentItemChanged, this, &DlgMacroExecuteImp::onUserMacroListBoxCurrentItemChanged); connect(ui->systemMacroListBox, &QTreeWidget::currentItemChanged, @@ -396,7 +399,7 @@ void DlgMacroExecuteImp::accept() // handle SystemExit exceptions Base::PyGILStateLocker locker; Base::PyException e; - e.ReportException(); + e.reportException(); getMainWindow()->unsetCursor(); } } @@ -645,7 +648,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto groupBox7 = setupCustomMacrosPage->findChild(QStringLiteral("GroupBox7")); if (!groupBox7) { - Base::Console().Warning("Toolbar walkthrough: Unable to find groupBox7\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find groupBox7\n"); // just warn when not a fatal error } else { @@ -658,7 +661,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto buttonAddAction = setupCustomMacrosPage->findChild(QStringLiteral("buttonAddAction")); if (!buttonAddAction) { - Base::Console().Warning("Toolbar walkthrough: Unable to find buttonAddAction\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find buttonAddAction\n"); } else { buttonAddAction->setStyleSheet(QStringLiteral("color:red")); @@ -667,7 +670,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto macroListBox = setupCustomMacrosPage->findChild(QStringLiteral("actionMacros")); if (!macroListBox) { - Base::Console().Warning("Toolbar walkthrough: Unable to find actionMacros combo box\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find actionMacros combo box\n"); } else { int macroIndex = macroListBox->findText(fn); // fn is the macro filename @@ -678,7 +681,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto menuText = setupCustomMacrosPage->findChild(QStringLiteral("actionMenu")); if (!menuText) { - Base::Console().Warning("Toolbar walkthrough: Unable to find actionMenu menuText\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find actionMenu menuText\n"); } else { menuText->setText(bareFileName); // user can fill in other fields, e.g. tooltip @@ -714,7 +717,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto moveActionRightButton = setupToolbarPage->findChild(QStringLiteral("moveActionRightButton")); if (!moveActionRightButton) { - Base::Console().Warning("Toolbar walkthrough: Unable to find moveActionRightButton\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find moveActionRightButton\n"); } else { moveActionRightButton->setStyleSheet(QStringLiteral("background-color: red")); @@ -728,7 +731,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto workbenchBox = setupToolbarPage->findChild(QStringLiteral("workbenchBox")); if (!workbenchBox) { - Base::Console().Warning("Toolbar walkthrough: Unable to find workbenchBox\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find workbenchBox\n"); } else { /** find the Global workbench and select it for the user **/ @@ -739,14 +742,14 @@ Note: your changes will be applied when you next switch workbenches\n")); setupToolbarPage->activateWorkbenchBox(globalIdx); } else { - Base::Console().Warning("Toolbar walkthrough: Unable to find Global workbench\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find Global workbench\n"); } if (!hasCustomToolbar) { auto newButton = setupToolbarPage->findChild(QStringLiteral("newButton")); if (!newButton) { - Base::Console().Warning("Toolbar walkthrough: Unable to find newButton\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find newButton\n"); } else { newButton->setStyleSheet(QStringLiteral("color:red")); @@ -760,7 +763,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto label = setupToolbarPage->findChild(QStringLiteral("label")); if (!label) { - Base::Console().Warning("Toolbar walkthrough: Unable to find label\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find label\n"); } else { label->setText(instructions2); @@ -770,7 +773,7 @@ Note: your changes will be applied when you next switch workbenches\n")); /** find Macros category and select it for the user **/ auto categoryBox = setupToolbarPage->findChild(QStringLiteral("categoryBox")); if (!categoryBox) { - Base::Console().Warning("Toolbar walkthrough: Unable to find categoryBox\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find categoryBox\n"); } else { int macrosIdx = categoryBox->findText(tr("Macros")); @@ -778,7 +781,7 @@ Note: your changes will be applied when you next switch workbenches\n")); categoryBox->setCurrentIndex(macrosIdx); } else { - Base::Console().Warning("Toolbar walkthrough: Unable to find Macros in categoryBox\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find Macros in categoryBox\n"); } } @@ -786,7 +789,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto toolbarTreeWidget = setupToolbarPage->findChild(QStringLiteral("toolbarTreeWidget")); if (!toolbarTreeWidget) { - Base::Console().Warning("Toolbar walkthrough: Unable to find toolbarTreeWidget\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find toolbarTreeWidget\n"); } else { toolbarTreeWidget->expandAll(); @@ -799,7 +802,7 @@ Note: your changes will be applied when you next switch workbenches\n")); auto commandTreeWidget = setupToolbarPage->findChild(QStringLiteral("commandTreeWidget")); if (!commandTreeWidget) { - Base::Console().Warning("Toolbar walkthrough: Unable to find commandTreeWidget\n"); + Base::Console().warning("Toolbar walkthrough: Unable to find commandTreeWidget\n"); } else { if (!hasMacroCommand) { // will be the last in the list, the one just created @@ -1064,4 +1067,14 @@ void DlgMacroExecuteImp::onAddonsButtonClicked() this->fillUpList(); } +/** + * convenience link button to open folder with macros + * from within macro dialog + */ +void DlgMacroExecuteImp::onFolderButtonClicked() +{ + QString path = QString::fromStdString(App::Application::getUserMacroDir()); + QUrl url = QUrl::fromLocalFile(path); + QDesktopServices::openUrl(url); +} #include "moc_DlgMacroExecuteImp.cpp" diff --git a/src/Gui/Dialogs/DlgMacroExecuteImp.h b/src/Gui/Dialogs/DlgMacroExecuteImp.h index 3be7b4b0a4..cf12d5add1 100644 --- a/src/Gui/Dialogs/DlgMacroExecuteImp.h +++ b/src/Gui/Dialogs/DlgMacroExecuteImp.h @@ -60,6 +60,7 @@ private: void onDuplicateButtonClicked(); void onToolbarButtonClicked(); void onAddonsButtonClicked(); + void onFolderButtonClicked(); void onUserMacroListBoxCurrentItemChanged(QTreeWidgetItem*); void onSystemMacroListBoxCurrentItemChanged(QTreeWidgetItem*); diff --git a/src/Gui/Dialogs/DlgObjectSelection.cpp b/src/Gui/Dialogs/DlgObjectSelection.cpp index a7cc6f5332..158a69bb15 100644 --- a/src/Gui/Dialogs/DlgObjectSelection.cpp +++ b/src/Gui/Dialogs/DlgObjectSelection.cpp @@ -280,7 +280,7 @@ void DlgObjectSelection::setItemState(App::DocumentObject *obj, if (ui->checkBoxAutoDeps->isChecked() && state == Qt::Checked) { // If an object is newly checked, check all its dependencies for (auto o : obj->getOutListRecursive()) { - if (!depSet.count(o) || itemChanged.count(o)) + if (!depSet.contains(o) || itemChanged.contains(o)) continue; auto itItem = itemMap.find(o); if (itItem == itemMap.end() || itItem->second[0]->checkState(0) == state) @@ -304,7 +304,7 @@ void DlgObjectSelection::setItemState(App::DocumentObject *obj, // If an object toggles state, we need to revisit all its in-list // object to update the partial/full checked state. for (auto o : obj->getInList()) { - if (!depSet.count(o) ||itemChanged.count(o)) + if (!depSet.contains(o) || itemChanged.contains(o)) continue; auto it = itemMap.find(o); if (it == itemMap.end() || it->second[0]->checkState(0) == state) @@ -312,7 +312,7 @@ void DlgObjectSelection::setItemState(App::DocumentObject *obj, int count = 0; int selcount = 0; for (auto sibling : o->getOutList()) { - if (!depSet.count(sibling)) + if (!depSet.contains(sibling)) continue; ++count; auto it = itemMap.find(sibling); @@ -511,7 +511,7 @@ void DlgObjectSelection::checkItemChanged() { std::sort(outlist.begin(), outlist.end()); for (const auto &v : itemMap) { - if (itemChanged.count(v.first) == 0 && v.second[0]->checkState(0) == Qt::Unchecked) + if (!itemChanged.contains(v.first) && v.second[0]->checkState(0) == Qt::Unchecked) continue; if (auto obj = v.first.getObject()) { if (!std::binary_search(outlist.begin(), outlist.end(), obj)) @@ -598,7 +598,7 @@ void DlgObjectSelection::onItemSelectionChanged() { for (auto obj : sels) obj->getInListEx(inlist, true); for (auto it = inlist.begin(); it != inlist.end();) { - if (!depSet.count(*it) || std::binary_search(sels.begin(), sels.end(), *it)) + if (!depSet.contains(*it) || std::binary_search(sels.begin(), sels.end(), *it)) it = inlist.erase(it); else ++it; diff --git a/src/Gui/Dialogs/DlgOnlineHelpImp.cpp b/src/Gui/Dialogs/DlgOnlineHelpImp.cpp index 94f0808b98..c76cd2abf5 100644 --- a/src/Gui/Dialogs/DlgOnlineHelpImp.cpp +++ b/src/Gui/Dialogs/DlgOnlineHelpImp.cpp @@ -98,7 +98,7 @@ void DlgOnlineHelpImp::changeEvent(QEvent *e) void DlgOnlineHelpImp::onLineEditDownloadFileNameSelected( const QString& url ) { QDir dir(url); - if (dir.exists() && dir.count() == 0) { + if (dir.exists() && dir.isEmpty()) { QMessageBox::critical(this, tr("Access denied"), tr("Access denied to '%1'\n\n" "Specify another directory, please.").arg(url)); } diff --git a/src/Gui/Dialogs/DlgPreferencesImp.cpp b/src/Gui/Dialogs/DlgPreferencesImp.cpp index 45b6656b94..d451d534e1 100644 --- a/src/Gui/Dialogs/DlgPreferencesImp.cpp +++ b/src/Gui/Dialogs/DlgPreferencesImp.cpp @@ -317,8 +317,7 @@ void DlgPreferencesImp::createPageInGroup(PreferencesPageItem *groupItem, const PreferencePage* page = createPreferencePage(pageName, groupItem->data(GroupNameRole).toString().toStdString()); if (!page) { - Base::Console().Warning("%s is not a preference page\n", pageName.c_str()); - + Base::Console().warning("%s is not a preference page\n", pageName.c_str()); return; } @@ -344,11 +343,11 @@ void DlgPreferencesImp::createPageInGroup(PreferencesPageItem *groupItem, const addSizeHint(page); } catch (const Base::Exception& e) { - Base::Console().Error("Base exception thrown for '%s'\n", pageName.c_str()); - e.ReportException(); + Base::Console().error("Base exception thrown for '%s'\n", pageName.c_str()); + e.reportException(); } catch (const std::exception& e) { - Base::Console().Error("C++ exception thrown for '%s' (%s)\n", pageName.c_str(), e.what()); + Base::Console().error("C++ exception thrown for '%s' (%s)\n", pageName.c_str(), e.what()); } } diff --git a/src/Gui/Dialogs/DlgProjectInformationImp.cpp b/src/Gui/Dialogs/DlgProjectInformationImp.cpp index ab0281447d..465c04106c 100644 --- a/src/Gui/Dialogs/DlgProjectInformationImp.cpp +++ b/src/Gui/Dialogs/DlgProjectInformationImp.cpp @@ -37,7 +37,7 @@ #include "MainWindow.h" -#if 0 // needed for Qt's lupdate utility +#if 0 // needed for Qt's lupdate utility qApp->translate("Gui::Dialog::DlgSettingsDocument", "All rights reserved"); qApp->translate("Gui::Dialog::DlgSettingsDocument", "Creative Commons Attribution"); qApp->translate("Gui::Dialog::DlgSettingsDocument", "Creative Commons Attribution-ShareAlike"); @@ -64,8 +64,12 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), _doc(doc), ui(new Ui_DlgProjectInformation) +DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, + QWidget* parent, + Qt::WindowFlags fl) + : QDialog(parent, fl) + , _doc(doc) + , ui(new Ui_DlgProjectInformation) { ui->setupUi(this); ui->lineEditName->setText(QString::fromUtf8(doc->Label.getValue())); @@ -79,11 +83,12 @@ DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, QWidget* ui->lineEditCompany->setText(QString::fromUtf8(doc->Company.getValue())); // Load comboBox with unit systems - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - ui->comboBox_unitSystem->addItem(item, i); - } + auto addDesc = [&, index {0}](const std::string& item) mutable { + ui->comboBox_unitSystem->addItem(QString::fromStdString(item), index++); + }; + const auto descriptions = Base::UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), addDesc); + ui->comboBox_unitSystem->setCurrentIndex(doc->UnitSystem.getValue()); // load comboBox with license names @@ -114,11 +119,15 @@ DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, QWidget* QStringList lines = comment.split(QLatin1String("\\n"), Qt::KeepEmptyParts); QString text = lines.join(QLatin1String("\n")); - ui->textEditComment->setPlainText( text ); - connect(ui->pushButtonOpenURL, &QPushButton::clicked, - this, &DlgProjectInformationImp::open_url); - connect(ui->comboLicense, qOverload(&QComboBox::currentIndexChanged), - this, &DlgProjectInformationImp::onLicenseTypeChanged); + ui->textEditComment->setPlainText(text); + connect(ui->pushButtonOpenURL, + &QPushButton::clicked, + this, + &DlgProjectInformationImp::open_url); + connect(ui->comboLicense, + qOverload(&QComboBox::currentIndexChanged), + this, + &DlgProjectInformationImp::onLicenseTypeChanged); } /** @@ -148,8 +157,8 @@ void DlgProjectInformationImp::accept() _doc->LicenseURL.setValue(ui->lineEditLicenseURL->text().toUtf8()); // Replace newline escape sequence through '\\n' string - QStringList lines = ui->textEditComment->toPlainText().split - (QLatin1String("\n"), Qt::KeepEmptyParts); + QStringList lines = + ui->textEditComment->toPlainText().split(QLatin1String("\n"), Qt::KeepEmptyParts); QString text = lines.join(QLatin1String("\\n")); _doc->Comment.setValue(text.isEmpty() ? QByteArray() : text.toUtf8()); @@ -159,8 +168,9 @@ void DlgProjectInformationImp::accept() void DlgProjectInformationImp::onLicenseTypeChanged(int index) { - const char* url {index >= 0 && index < App::countOfLicenses ? App::licenseItems.at(index).at(App::posnOfUrl) - : _doc->LicenseURL.getValue()}; + const char* url {index >= 0 && index < App::countOfLicenses + ? App::licenseItems.at(index).at(App::posnOfUrl) + : _doc->LicenseURL.getValue()}; ui->lineEditLicenseURL->setText(QString::fromLatin1(url)); } diff --git a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp index 5f9df07c99..10e9f9f375 100644 --- a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp +++ b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp @@ -99,7 +99,7 @@ void DlgRevertToBackupConfigImp::accept() { auto items = ui->listWidget->selectedItems(); if (items.count() != 1) { - Base::Console().Error(tr("No selection in dialog, cannot load backup file").toStdString().c_str()); + Base::Console().error(tr("No selection in dialog, cannot load backup file").toStdString().c_str()); return; } auto item = items[0]; @@ -111,7 +111,7 @@ void DlgRevertToBackupConfigImp::accept() newParameters->GetGroup("BaseApp")->copyTo(baseAppGroup); } else { - Base::Console().Error("Preference Pack Internal Error: Invalid backup file location"); + Base::Console().error("Preference Pack Internal Error: Invalid backup file location"); } QDialog::accept(); diff --git a/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp b/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp index f63e080e2e..65947b6179 100644 --- a/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp +++ b/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp @@ -51,12 +51,12 @@ DlgUnitsCalculator::DlgUnitsCalculator(QWidget* parent, Qt::WindowFlags fl) ui->setupUi(this); this->setAttribute(Qt::WA_DeleteOnClose); - ui->comboBoxScheme->addItem(QStringLiteral("Preference system"), static_cast(-1)); - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - ui->comboBoxScheme->addItem(item, i); - } + ui->comboBoxScheme->addItem(QStringLiteral("Preference system"), -1); + auto addItem = [&, index {0}](const auto& item) mutable { + ui->comboBoxScheme->addItem(QString::fromStdString(item), index++); + }; + auto descriptions = Base::UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), addItem); // clang-format off connect(ui->unitsBox, qOverload(&QComboBox::activated), @@ -214,7 +214,7 @@ void DlgUnitsCalculator::onComboBoxSchemeActivated(int index) { int item = ui->comboBoxScheme->itemData(index).toInt(); if (item > 0) { - ui->quantitySpinBox->setSchema(static_cast(item)); + ui->quantitySpinBox->setSchema(item); } else { ui->quantitySpinBox->clearSchema(); diff --git a/src/Gui/Document.cpp b/src/Gui/Document.cpp index bbfcb7f0fb..d85f3ddb5c 100644 --- a/src/Gui/Document.cpp +++ b/src/Gui/Document.cpp @@ -946,7 +946,7 @@ void Document::slotNewObject(const App::DocumentObject& Obj) FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what()); } catch(Base::Exception &e){ - e.ReportException(); + e.reportException(); } #ifndef FC_DEBUG catch(...){ @@ -957,7 +957,7 @@ void Document::slotNewObject(const App::DocumentObject& Obj) try { pcProvider->reattach(const_cast(&Obj)); } catch(Base::Exception &e){ - e.ReportException(); + e.reportException(); } } @@ -1047,7 +1047,7 @@ void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Prop && (Prop.isDerivedFrom() // Issue ID 0004230 : getName() can return null in which case strstr() crashes || (Prop.getName() && strstr(Prop.getName(),"Scale"))) - && d->_editObjs.count(&Obj)) + && d->_editObjs.contains(&Obj)) { Base::Matrix4D mat; auto sobj = d->_editViewProviderParent->getObject()->getSubObject( @@ -1062,7 +1062,7 @@ void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Prop FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what()); } catch(Base::Exception& e){ - e.ReportException(); + e.reportException(); } catch(const std::exception& e){ FC_ERR("C++ exception in " << Obj.getFullName() << " thrown " << e.what()); @@ -1294,7 +1294,7 @@ static bool checkCanonicalPath(const std::map &docs) auto &d = paths[info.canonicalFilePath()]; d.push_back(doc); if (!warn && d.size() > 1) { - if (docs.count(d.front()) || docs.count(d.back())) + if (docs.contains(d.front()) || docs.contains(d.back())) warn = true; } } @@ -1315,7 +1315,7 @@ static bool checkCanonicalPath(const std::map &docs) for (auto &v : paths) { if (v.second.size() <= 1) continue; for (auto doc : v.second) { - if (docs.count(doc)) { + if (docs.contains(doc)) { FC_WARN("Physical path: " << v.first.toUtf8().constData()); for (auto d : v.second) FC_WARN(" Document: " << docName(d).toUtf8().constData() @@ -1441,7 +1441,7 @@ bool Document::save() } } catch (const Base::FileException& e) { - e.ReportException(); + e.reportException(); return askIfSavingFailed(QString::fromUtf8(e.what())); } catch (const Base::Exception& e) { @@ -1489,7 +1489,7 @@ bool Document::saveAs() getMainWindow()->appendRecentFile(fi.filePath()); } catch (const Base::FileException& e) { - e.ReportException(); + e.reportException(); return askIfSavingFailed(QString::fromUtf8(e.what())); } catch (const Base::Exception& e) { @@ -1511,7 +1511,7 @@ void Document::saveAll() docs = App::Document::getDependentDocuments(App::GetApplication().getDocuments(),true); } catch(Base::Exception &e) { - e.ReportException(); + e.reportException(); int ret = QMessageBox::critical(getMainWindow(), QObject::tr("Failed to save document"), QObject::tr("Documents contains cyclic dependencies. Do you still want to save them?"), QMessageBox::Yes,QMessageBox::No); @@ -1722,7 +1722,7 @@ void Document::RestoreDocFile(Base::Reader &reader) } } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } } @@ -2181,7 +2181,7 @@ void Document::detachView(Gui::BaseView* pcView, bool bPassiv) void Document::onUpdate() { #ifdef FC_LOGUPDATECHAIN - Base::Console().Log("Acti: Gui::Document::onUpdate()"); + Base::Console().log("Acti: Gui::Document::onUpdate()"); #endif std::list::iterator it; @@ -2198,7 +2198,7 @@ void Document::onUpdate() void Document::onRelabel() { #ifdef FC_LOGUPDATECHAIN - Base::Console().Log("Acti: Gui::Document::onRelabel()"); + Base::Console().log("Acti: Gui::Document::onRelabel()"); #endif std::list::iterator it; @@ -2256,8 +2256,7 @@ bool Document::canClose (bool checkModify, bool checkLink) bool ok = true; if (checkModify && isModified() && !getDocument()->testStatus(App::Document::PartialDoc)) { - const char *docName = getDocument()->Label.getValue(); - int res = getMainWindow()->confirmSave(docName, getActiveView()); + int res = getMainWindow()->confirmSave(getDocument(), getActiveView()); switch (res) { case MainWindow::ConfirmSaveResult::Cancel: @@ -2267,11 +2266,14 @@ bool Document::canClose (bool checkModify, bool checkLink) case MainWindow::ConfirmSaveResult::Save: ok = save(); if (!ok) { + const QString docName = QString::fromStdString(getDocument()->Label.getStrValue()); + const QString text = (!docName.isEmpty() + ? QObject::tr("Failed to save document '%1'. Would you like to cancel the closure?").arg(docName) + : QObject::tr("Document saving failed. Would you like to cancel the closure?")); int ret = QMessageBox::question( getActiveView(), - QObject::tr("Document not saved"), - QObject::tr("The document%1 could not be saved. Do you want to cancel closing it?") - .arg(docName?(QStringLiteral(" ")+QString::fromUtf8(docName)):QString()), + QObject::tr("Unable to save document"), + text, QMessageBox::Discard | QMessageBox::Cancel, QMessageBox::Discard); if (ret == QMessageBox::Discard) diff --git a/src/Gui/DocumentObserverPython.cpp b/src/Gui/DocumentObserverPython.cpp index c50e547bb4..ef05c42638 100644 --- a/src/Gui/DocumentObserverPython.cpp +++ b/src/Gui/DocumentObserverPython.cpp @@ -101,7 +101,7 @@ void DocumentObserverPython::slotCreatedDocument(const Gui::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -115,7 +115,7 @@ void DocumentObserverPython::slotDeletedDocument(const Gui::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -129,7 +129,7 @@ void DocumentObserverPython::slotRelabelDocument(const Gui::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -143,7 +143,7 @@ void DocumentObserverPython::slotRenameDocument(const Gui::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -157,7 +157,7 @@ void DocumentObserverPython::slotActivateDocument(const Gui::Document& Doc) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -171,7 +171,7 @@ void DocumentObserverPython::slotCreatedObject(const Gui::ViewProvider& Obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -185,7 +185,7 @@ void DocumentObserverPython::slotDeletedObject(const Gui::ViewProvider& Obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -206,7 +206,7 @@ void DocumentObserverPython::slotBeforeChangeObject(const Gui::ViewProvider& Obj } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -227,7 +227,7 @@ void DocumentObserverPython::slotChangedObject(const Gui::ViewProvider& Obj, } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -241,7 +241,7 @@ void DocumentObserverPython::slotInEdit(const Gui::ViewProviderDocumentObject& O } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -255,6 +255,6 @@ void DocumentObserverPython::slotResetEdit(const Gui::ViewProviderDocumentObject } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/DocumentRecovery.cpp b/src/Gui/DocumentRecovery.cpp index fa097b7cc6..539cddecbe 100644 --- a/src/Gui/DocumentRecovery.cpp +++ b/src/Gui/DocumentRecovery.cpp @@ -484,7 +484,7 @@ DocumentRecoveryPrivate::XmlConfig DocumentRecoveryPrivate::readXmlFile(const QS while (!child.isNull()) { QString name = child.localName(); const QString value = child.text(); - if (std::ranges::find(filter, name) != filter.end()) + if (filter.contains(name)) cfg[name] = value; child = child.nextSiblingElement(); } @@ -677,7 +677,7 @@ void DocumentRecoveryHandler::checkForPreviousCrashes(const std::functionhasFocus()) { diff --git a/src/Gui/EditorView.cpp b/src/Gui/EditorView.cpp index c62f278309..69fda4a503 100644 --- a/src/Gui/EditorView.cpp +++ b/src/Gui/EditorView.cpp @@ -718,7 +718,7 @@ void PythonEditorView::executeScript() // handle SystemExit exceptions Base::PyGILStateLocker locker; Base::PyException e; - e.ReportException(); + e.reportException(); getMainWindow()->unsetCursor(); } } diff --git a/src/Gui/ExpressionCompleter.cpp b/src/Gui/ExpressionCompleter.cpp index 44c0e65983..cb3e409545 100644 --- a/src/Gui/ExpressionCompleter.cpp +++ b/src/Gui/ExpressionCompleter.cpp @@ -341,7 +341,7 @@ public: if (idx >= 0 && idx < objSize) { obj = objs[idx / 2]; // if they are in the ignore list skip - if (inList.count(obj)) { + if (inList.contains(obj)) { return; } } @@ -430,7 +430,7 @@ public: const auto& objs = doc->getObjects(); objSize = (int)objs.size() * 2; // if invalid index, or in the ignore list bail out - if (idx < 0 || idx >= objSize || inList.count(obj)) { + if (idx < 0 || idx >= objSize || inList.contains(obj)) { return; } obj = objs[idx / 2]; diff --git a/src/Gui/GuiApplication.cpp b/src/Gui/GuiApplication.cpp index df39c0baf9..1df75a274f 100644 --- a/src/Gui/GuiApplication.cpp +++ b/src/Gui/GuiApplication.cpp @@ -71,7 +71,7 @@ GUIApplication::~GUIApplication() = default; bool GUIApplication::notify (QObject * receiver, QEvent * event) { if (!receiver) { - Base::Console().Log("GUIApplication::notify: Unexpected null receiver, event type: %d\n", + Base::Console().log("GUIApplication::notify: Unexpected null receiver, event type: %d\n", (int)event->type()); return false; } @@ -98,15 +98,15 @@ bool GUIApplication::notify (QObject * receiver, QEvent * event) return true; } catch (const Base::Exception& e) { - Base::Console().Error("Unhandled Base::Exception caught in GUIApplication::notify.\n" + Base::Console().error("Unhandled Base::Exception caught in GUIApplication::notify.\n" "The error message is: %s\n%s", e.what(), exceptionWarning); } catch (const std::exception& e) { - Base::Console().Error("Unhandled std::exception caught in GUIApplication::notify.\n" + Base::Console().error("Unhandled std::exception caught in GUIApplication::notify.\n" "The error message is: %s\n%s", e.what(), exceptionWarning); } catch (...) { - Base::Console().Error("Unhandled unknown exception caught in GUIApplication::notify.\n%s", + Base::Console().error("Unhandled unknown exception caught in GUIApplication::notify.\n%s", exceptionWarning); } @@ -129,11 +129,11 @@ bool GUIApplication::notify (QObject * receiver, QEvent * event) dump << " is child of\n"; } std::string str = dump.str(); - Base::Console().Log("%s",str.c_str()); + Base::Console().log("%s",str.c_str()); } } catch (...) { - Base::Console().Log("Invalid recipient and/or event in GUIApplication::notify\n"); + Base::Console().log("Invalid recipient and/or event in GUIApplication::notify\n"); } return true; @@ -232,10 +232,10 @@ public: } } if (server->isListening()) { - Base::Console().Log("Local server '%s' started\n", qPrintable(serverName)); + Base::Console().log("Local server '%s' started\n", qPrintable(serverName)); } else { - Base::Console().Log("Local server '%s' failed to start\n", qPrintable(serverName)); + Base::Console().log("Local server '%s' failed to start\n", qPrintable(serverName)); } } @@ -311,7 +311,7 @@ void GUISingleApplication::readFromSocket() while (socket->canReadLine()) { d_ptr->timer->stop(); QString message = in.readLine(); - Base::Console().Log("Received message: %s\n", message.toStdString()); + Base::Console().log("Received message: %s\n", message.toStdString()); d_ptr->messages.push_back(message); d_ptr->timer->start(1000); } diff --git a/src/Gui/GuiConsole.cpp b/src/Gui/GuiConsole.cpp index d9f073d3d3..72c15a8721 100644 --- a/src/Gui/GuiConsole.cpp +++ b/src/Gui/GuiConsole.cpp @@ -81,7 +81,7 @@ GUIConsole::~GUIConsole (void) FreeConsole(); } -void GUIConsole::SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, +void GUIConsole::sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) { (void) notifiername; @@ -121,7 +121,7 @@ void GUIConsole::SendLog(const std::string& notifiername, const std::string& msg // safely ignore GUIConsole::s_nMaxLines and GUIConsole::s_nRefCount GUIConsole::GUIConsole () = default; GUIConsole::~GUIConsole () = default; -void GUIConsole::SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, +void GUIConsole::sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) { (void) notifiername; diff --git a/src/Gui/GuiConsole.h b/src/Gui/GuiConsole.h index 1e27d437cd..6cb0d1fda7 100644 --- a/src/Gui/GuiConsole.h +++ b/src/Gui/GuiConsole.h @@ -47,9 +47,9 @@ public: GUIConsole(); /// Destructor ~GUIConsole() override; - void SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) override; - const char* Name() override {return "GUIConsole";} + const char* name() override {return "GUIConsole";} protected: static const unsigned int s_nMaxLines; diff --git a/src/Gui/Language/Translator.cpp b/src/Gui/Language/Translator.cpp index dff0d3d2a2..db05155a78 100644 --- a/src/Gui/Language/Translator.cpp +++ b/src/Gui/Language/Translator.cpp @@ -277,7 +277,7 @@ void Translator::setLocale(const std::string& language) const updateLocaleChange(); #ifdef FC_DEBUG - Base::Console().Log("Locale changed to %s => %s\n", qPrintable(loc.bcp47Name()), qPrintable(loc.name())); + Base::Console().log("Locale changed to %s => %s\n", qPrintable(loc.bcp47Name()), qPrintable(loc.name())); #endif } @@ -409,7 +409,7 @@ void Translator::enableDecimalPointConversion(bool on) } #if FC_DEBUG if (on && decimalPointConverter) { - Base::Console().Instance().Warning("Translator: decimal point converter is already installed\n"); + Base::Console().instance().warning("Translator: decimal point converter is already installed\n"); } #endif if (on && !decimalPointConverter) { diff --git a/src/Gui/MDIViewPyWrap.cpp b/src/Gui/MDIViewPyWrap.cpp index 0be622db10..f6ab727155 100644 --- a/src/Gui/MDIViewPyWrap.cpp +++ b/src/Gui/MDIViewPyWrap.cpp @@ -66,7 +66,7 @@ public: Base::PyGILStateLocker lock; PythonWrapper wrap; wrap.loadWidgetsModule(); - if (func.count("widget") == 0) { + if (!func.contains("widget")) { throw Py::AttributeError("Object has no attribute 'widget'"); } Py::Callable target(func.at("widget")); @@ -182,7 +182,7 @@ MDIViewPyWrap::MDIViewPyWrap(const Py::Object& py, Gui::Document* pcDocument,QWi catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } @@ -210,7 +210,7 @@ bool MDIViewPyWrap::onMsg(const char* pMsg,const char** ppReturn) catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); return false; } } @@ -229,7 +229,7 @@ bool MDIViewPyWrap::onHasMsg(const char* pMsg) const catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); return false; } } @@ -245,7 +245,7 @@ bool MDIViewPyWrap::canClose() catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); return false; } } @@ -261,7 +261,7 @@ void MDIViewPyWrap::print(QPrinter* printer) catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } @@ -276,7 +276,7 @@ void MDIViewPyWrap::print() catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } @@ -291,7 +291,7 @@ void MDIViewPyWrap::printPdf() catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } @@ -306,7 +306,7 @@ void MDIViewPyWrap::printPreview() catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); } } @@ -321,7 +321,7 @@ QStringList MDIViewPyWrap::undoActions() const catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); return MDIView::undoActions(); } } @@ -337,7 +337,7 @@ QStringList MDIViewPyWrap::redoActions() const catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException exc; - exc.ReportException(); + exc.reportException(); return MDIView::redoActions(); } } diff --git a/src/Gui/Macro.cpp b/src/Gui/Macro.cpp index e7f20e1ee7..be04fd18da 100644 --- a/src/Gui/Macro.cpp +++ b/src/Gui/Macro.cpp @@ -239,17 +239,17 @@ void MacroManager::open(MacroType eType, const char *sName) #endif macroFile.open(sName); - Base::Console().Log("CmdM: Open macro: %s\n", sName); + Base::Console().log("CmdM: Open macro: %s\n", sName); } void MacroManager::commit() { QString macroName = macroFile.fileName(); if (macroFile.commit()) { - Base::Console().Log("Commit macro: %s\n", (const char*)macroName.toUtf8()); + Base::Console().log("Commit macro: %s\n", (const char*)macroName.toUtf8()); } else { - Base::Console().Error("Cannot open file to write macro: %s\n", + Base::Console().error("Cannot open file to write macro: %s\n", (const char*)macroName.toUtf8()); cancel(); } @@ -258,7 +258,7 @@ void MacroManager::commit() void MacroManager::cancel() { QString macroName = macroFile.fileName(); - Base::Console().Log("Cancel macro: %s\n",(const char*)macroName.toUtf8()); + Base::Console().log("Cancel macro: %s\n",(const char*)macroName.toUtf8()); macroFile.cancel(); } @@ -389,7 +389,7 @@ void MacroManager::run(MacroType eType, const char *sName) throw; } catch (const Base::PyException& e) { - e.ReportException(); + e.reportException(); } catch (const Base::Exception& e) { qWarning("%s",e.what()); diff --git a/src/Gui/MainWindow.cpp b/src/Gui/MainWindow.cpp index dc0ae0f536..c2a664d48f 100644 --- a/src/Gui/MainWindow.cpp +++ b/src/Gui/MainWindow.cpp @@ -65,6 +65,7 @@ #endif #endif +#include #include #include @@ -179,13 +180,16 @@ public: //create the action buttons auto* menu = new QMenu(this); auto* actionGrp = new QActionGroup(menu); - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i = 0; i < num; i++) { - QAction* action = menu->addAction(QStringLiteral("UnitSchema%1").arg(i)); + + auto setAction = [&, index {0}](const std::string&) mutable { + QAction* action = menu->addAction(QStringLiteral("UnitSchema%1").arg(index)); actionGrp->addAction(action); action->setCheckable(true); - action->setData(i); - } + action->setData(index++); + }; + auto descriptions = Base::UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), setAction); + QObject::connect(actionGrp, &QActionGroup::triggered, this, [this](QAction* action) { int userSchema = action->data().toInt(); setUserSchema(userSchema); @@ -236,7 +240,7 @@ public: getWindowParameter()->SetInt("UserSchema", userSchema); unitChanged(); - Base::UnitsApi::setSchema(static_cast(userSchema)); + Base::UnitsApi::setSchema(userSchema); // Update the main window to show the unit change Gui::Application::Instance->onUpdate(); } @@ -261,12 +265,12 @@ private: void retranslateUi() { auto actions = menu()->actions(); - int maxSchema = static_cast(Base::UnitSystem::NumUnitSystemTypes); - assert(actions.size() <= maxSchema); - for(int i = 0; i < maxSchema ; i++) - { - actions[i]->setText(Base::UnitsApi::getDescription(static_cast(i))); - } + auto addAction = [&, index {0}](const std::string& action)mutable { + actions[index++]->setText(QString::fromStdString(action)); + }; + auto descriptions = Base::UnitsApi::getDescriptions(); + assert(actions.size() <= static_cast(descriptions.size())); + std::for_each(descriptions.begin(), descriptions.end(), addAction); } }; @@ -782,17 +786,18 @@ void MainWindow::closeActiveWindow () d->mdiArea->closeActiveSubWindow(); } -int MainWindow::confirmSave(const char *docName, QWidget *parent, bool addCheckbox) { +int MainWindow::confirmSave(App::Document *doc, QWidget *parent, bool addCheckbox) { QMessageBox box(parent?parent:this); box.setObjectName(QStringLiteral("confirmSave")); box.setIcon(QMessageBox::Question); box.setWindowFlags(box.windowFlags() | Qt::WindowStaysOnTopHint); box.setWindowTitle(QObject::tr("Unsaved document")); - if(docName) - box.setText(QObject::tr("Do you want to save your changes to document '%1' before closing?") - .arg(QString::fromUtf8(docName))); - else - box.setText(QObject::tr("Do you want to save your changes to document before closing?")); + const QString docName = QString::fromStdString(doc->Label.getStrValue()); + const QString text = (!docName.isEmpty() + ? QObject::tr("Do you want to save your changes to document '%1' before closing?").arg(docName) + : QObject::tr("Do you want to save your changes to document before closing?")); + box.setText(text); + box.setInformativeText(QObject::tr("If you don't save, your changes will be lost.")); box.setStandardButtons(QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save); @@ -826,6 +831,19 @@ int MainWindow::confirmSave(const char *docName, QWidget *parent, bool addCheckb int res = ConfirmSaveResult::Cancel; box.adjustSize(); // Silence warnings from Qt on Windows + + // activates the last used MDI view of the closing document + MDIView *activeView = this->activeWindow(); + App::Document *activeDoc = (activeView ? activeView->getAppDocument() : nullptr); + if (activeDoc != doc){ + const QList listOfMDIs = this->windows(); + for (QWidget *widget : listOfMDIs){ + auto mdiView = qobject_cast (widget); + if (mdiView != nullptr && mdiView->getAppDocument() == doc) + this->setActiveWindow(mdiView); + } + } + switch (box.exec()) { case QMessageBox::Save: @@ -847,13 +865,23 @@ bool MainWindow::closeAllDocuments (bool close) docs = App::Document::getDependentDocuments(docs, true); } catch(Base::Exception &e) { - e.ReportException(); + e.reportException(); } bool checkModify = true; bool saveAll = false; int failedSaves = 0; + // moves the active document to the front + MDIView *activeView = this->activeWindow(); + App::Document *activeDoc = (activeView ? activeView->getAppDocument() : nullptr); + if (activeDoc != nullptr) + for (auto it = ++docs.begin(); it != docs.end(); it++) + if (*it == activeDoc){ + docs.erase(it); + docs.insert(docs.begin(), activeDoc); + } + for (auto doc : docs) { auto gdoc = Application::Instance->getDocument(doc); if (!gdoc) @@ -866,7 +894,7 @@ bool MainWindow::closeAllDocuments (bool close) continue; bool save = saveAll; if (!save && checkModify) { - int res = confirmSave(doc->Label.getStrValue().c_str(), this, docs.size()>1); + int res = confirmSave(doc, this, docs.size() > 1); switch (res) { case ConfirmSaveResult::Cancel: @@ -954,7 +982,7 @@ void MainWindow::showDocumentation(const QString& help) } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -1532,7 +1560,7 @@ void MainWindow::delayedStartup() throw; } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } }); return; @@ -1791,10 +1819,10 @@ void MainWindowP::restoreWindowState(const QByteArray &windowState) Base::StateLocker guard(_restoring); // tmp. disable the report window to suppress some bothering warnings - if (Base::Console().IsMsgTypeEnabled("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn)) { - Base::Console().SetEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, false); + if (Base::Console().isMsgTypeEnabled("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn)) { + Base::Console().setEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, false); getMainWindow()->restoreState(windowState); - Base::Console().SetEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, true); + Base::Console().setEnabledMsgType("ReportOutput", Base::ConsoleSingleton::MsgType_Wrn, true); } else getMainWindow()->restoreState(windowState); @@ -2095,7 +2123,7 @@ void MainWindow::loadUrls(App::Document* doc, const QList& urls) files << info.absoluteFilePath(); } else { - Base::Console().Message("No support to load file '%s'\n", + Base::Console().message("No support to load file '%s'\n", (const char*)info.absoluteFilePath().toUtf8()); } } @@ -2334,7 +2362,7 @@ void MainWindow::setWindowTitle(const QString& string) msg = QStringLiteral("#statusBar{color: #000000}"); // black wrn = QStringLiteral("#statusBar{color: #ffaa00}"); // orange err = QStringLiteral("#statusBar{color: #ff0000}"); // red - Base::Console().AttachObserver(this); + Base::Console().attachObserver(this); getWindowParameter()->Attach(this); getWindowParameter()->NotifyAll(); } @@ -2342,7 +2370,7 @@ void MainWindow::setWindowTitle(const QString& string) StatusBarObserver::~StatusBarObserver() { getWindowParameter()->Detach(this); - Base::Console().DetachObserver(this); + Base::Console().detachObserver(this); } void StatusBarObserver::OnChange(Base::Subject & rCaller, const char* sReason) @@ -2368,7 +2396,7 @@ void MainWindow::setWindowTitle(const QString& string) } } - void StatusBarObserver::SendLog(const std::string& notifiername, + void StatusBarObserver::sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, diff --git a/src/Gui/MainWindow.h b/src/Gui/MainWindow.h index 9dfcf4cfdf..ac49d55a2d 100644 --- a/src/Gui/MainWindow.h +++ b/src/Gui/MainWindow.h @@ -238,7 +238,7 @@ public Q_SLOTS: bool closeAllDocuments (bool close=true); /** Pop up a message box asking for saving document */ - int confirmSave(const char *docName, QWidget *parent=nullptr, bool addCheckBox=false); + int confirmSave(App::Document *doc, QWidget *parent = nullptr, bool addCheckBox = false); /** * Activates the next window in the child window chain. */ @@ -388,11 +388,11 @@ public: /** Observes its parameter group. */ void OnChange(Base::Subject &rCaller, const char * sReason) override; - void SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) override; /// name of the observer - const char *Name() override {return "StatusBar";} + const char *name() override {return "StatusBar";} friend class MainWindow; private: diff --git a/src/Gui/MenuManager.cpp b/src/Gui/MenuManager.cpp index db6ae93325..e0520d0e57 100644 --- a/src/Gui/MenuManager.cpp +++ b/src/Gui/MenuManager.cpp @@ -62,7 +62,7 @@ std::string MenuItem::command() const bool MenuItem::hasItems() const { - return _items.count() > 0; + return !_items.isEmpty(); } MenuItem* MenuItem::findItem(const std::string& name) diff --git a/src/Gui/Navigation/GestureNavigationStyle.cpp b/src/Gui/Navigation/GestureNavigationStyle.cpp index a7ee06b82c..7c5fcf8dac 100644 --- a/src/Gui/Navigation/GestureNavigationStyle.cpp +++ b/src/Gui/Navigation/GestureNavigationStyle.cpp @@ -98,39 +98,39 @@ public: void log() const { if (isPress(1)) - Base::Console().Log("button1 press "); + Base::Console().log("button1 press "); if (isPress(2)) - Base::Console().Log("button2 press "); + Base::Console().log("button2 press "); if (isPress(3)) - Base::Console().Log("button3 press "); + Base::Console().log("button3 press "); if (isRelease(1)) - Base::Console().Log("button1 release "); + Base::Console().log("button1 release "); if (isRelease(2)) - Base::Console().Log("button2 release "); + Base::Console().log("button2 release "); if (isRelease(3)) - Base::Console().Log("button3 release "); + Base::Console().log("button3 release "); if (isMouseButtonEvent()) - Base::Console().Log("%x", modifiers); + Base::Console().log("%x", modifiers); if (isGestureEvent()){ - Base::Console().Log("Gesture "); + Base::Console().log("Gesture "); switch(asGestureEvent()->state){ case SoGestureEvent::SbGSStart: - Base::Console().Log("start "); + Base::Console().log("start "); break; case SoGestureEvent::SbGSEnd: - Base::Console().Log("end "); + Base::Console().log("end "); break; case SoGestureEvent::SbGSUpdate: - Base::Console().Log("data "); + Base::Console().log("data "); break; default: - Base::Console().Log("??? "); + Base::Console().log("??? "); } - Base::Console().Log(inventor_event->getTypeId().getName().getString()); + Base::Console().log(inventor_event->getTypeId().getName().getString()); } if (isMouseButtonEvent() || isGestureEvent()){ - Base::Console().Log("(%i,%i)\n", inventor_event->getPosition()[0],inventor_event->getPosition()[1]); + Base::Console().log("(%i,%i)\n", inventor_event->getPosition()[0],inventor_event->getPosition()[1]); } } @@ -243,7 +243,7 @@ public: auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::IDLE); if (ns.logging) - Base::Console().Log(" -> IdleState\n"); + Base::Console().log(" -> IdleState\n"); } virtual ~IdleState() = default; @@ -355,7 +355,7 @@ public: { auto &ns = this->outermost_context().ns; if (ns.logging) - Base::Console().Log(" -> AwaitingMoveState\n"); + Base::Console().log(" -> AwaitingMoveState\n"); ns.setViewingMode(NavigationStyle::IDLE); this->base_pos = static_cast(this->triggering_event())->inventor_event->getPosition(); this->since = static_cast(this->triggering_event())->inventor_event->getTime(); @@ -498,7 +498,7 @@ public: ns.setViewingMode(NavigationStyle::DRAGGING); this->base_pos = inventorEvent->getPosition(); if (ns.logging) - Base::Console().Log(" -> RotateState\n"); + Base::Console().log(" -> RotateState\n"); } virtual ~RotateState() = default; @@ -540,7 +540,7 @@ public: ns.setViewingMode(NavigationStyle::PANNING); this->base_pos = static_cast(this->triggering_event())->inventor_event->getPosition(); if (ns.logging) - Base::Console().Log(" -> PanState\n"); + Base::Console().log(" -> PanState\n"); this->ratio = ns.viewer->getSoRenderManager()->getViewportRegion().getViewportAspectRatio(); ns.setupPanningPlane(ns.viewer->getSoRenderManager()->getCamera());//set up panningplane } @@ -587,7 +587,7 @@ public: ns.setViewingMode(NavigationStyle::PANNING); this->base_pos = static_cast(this->triggering_event())->inventor_event->getPosition(); if (ns.logging) - Base::Console().Log(" -> StickyPanState\n"); + Base::Console().log(" -> StickyPanState\n"); this->ratio = ns.viewer->getSoRenderManager()->getViewportRegion().getViewportAspectRatio(); ns.setupPanningPlane(ns.viewer->getSoRenderManager()->getCamera());//set up panningplane } @@ -634,7 +634,7 @@ public: ns.setViewingMode(NavigationStyle::DRAGGING); this->base_pos = static_cast(this->triggering_event())->inventor_event->getPosition(); if (ns.logging) - Base::Console().Log(" -> TiltState\n"); + Base::Console().log(" -> TiltState\n"); ns.setupPanningPlane(ns.viewer->getSoRenderManager()->getCamera());//set up panningplane } virtual ~TiltState() = default; @@ -684,7 +684,7 @@ public: ns.setViewingMode(NavigationStyle::PANNING); this->base_pos = static_cast(this->triggering_event())->inventor_event->getPosition(); if (ns.logging) - Base::Console().Log(" -> GestureState\n"); + Base::Console().log(" -> GestureState\n"); ns.setupPanningPlane(ns.viewer->getSoRenderManager()->getCamera());//set up panningplane this->ratio = ns.viewer->getSoRenderManager()->getViewportRegion().getViewportAspectRatio(); enableTilt = !(App::GetApplication().GetParameterGroupByPath @@ -703,7 +703,7 @@ public: ev.flags->processed = true; if (ev.mbstate() == 0){ //a fail-safe: if gesture end event doesn't arrive, a mouse click should be able to stop this mode. - Base::Console().Warning("leaving gesture state by mouse-click (fail-safe)\n"); + Base::Console().warning("leaving gesture state by mouse-click (fail-safe)\n"); return transit(); } } @@ -763,7 +763,7 @@ public: { auto &ns = this->outermost_context().ns; if (ns.logging) - Base::Console().Log(" -> AwaitingReleaseState\n"); + Base::Console().log(" -> AwaitingReleaseState\n"); } virtual ~AwaitingReleaseState() = default; @@ -814,7 +814,7 @@ public: auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::INTERACT); if (ns.logging) - Base::Console().Log(" -> InteractState\n"); + Base::Console().log(" -> InteractState\n"); } virtual ~InteractState() = default; @@ -988,12 +988,12 @@ void GestureNavigationStyle::onRollGesture(int direction) std::string cmd; if (direction == +1){ if (logging) - Base::Console().Log("Roll forward gesture\n"); + Base::Console().log("Roll forward gesture\n"); cmd = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/View")->GetASCII("GestureRollFwdCommand"); } else if (direction == -1) { if (logging) - Base::Console().Log("Roll backward gesture\n"); + Base::Console().log("Roll backward gesture\n"); cmd = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/View")->GetASCII("GestureRollBackCommand"); } @@ -1004,9 +1004,9 @@ void GestureNavigationStyle::onRollGesture(int direction) try { Base::Interpreter().runString(code.str().c_str()); } catch (Base::PyException& exc) { - exc.ReportException(); + exc.reportException(); } catch (...) { - Base::Console().Error("GestureNavigationStyle::onRollGesture: unknown C++ exception when invoking command %s\n", cmd.c_str()); + Base::Console().error("GestureNavigationStyle::onRollGesture: unknown C++ exception when invoking command %s\n", cmd.c_str()); } } @@ -1016,7 +1016,7 @@ void GestureNavigationStyle::EventQueue::post(const NS::Event& ev) ev.flags->processed = true; this->push(*ev.asMouseButtonEvent()); if (ns.logging){ - Base::Console().Log("postponed: "); + Base::Console().log("postponed: "); ev.log(); } } diff --git a/src/Gui/Navigation/NavigationStyle.cpp b/src/Gui/Navigation/NavigationStyle.cpp index b24fce9ff0..38f170877c 100644 --- a/src/Gui/Navigation/NavigationStyle.cpp +++ b/src/Gui/Navigation/NavigationStyle.cpp @@ -117,20 +117,18 @@ public: // drop the sphere intersection onto the tolerance plane SbLine projectLine(sphereIntersection, sphereIntersection + planeDir); - if (!tolPlane.intersect(projectLine, planeIntersection)) -#ifdef DEBUG + if (!tolPlane.intersect(projectLine, planeIntersection)) { +#ifdef FC_DEBUG SoDebugError::post("SbSphereSheetProjector::project", "Couldn't intersect working line with plane"); -#else - /* Do nothing */; +#endif + } + } + else if (!tolPlane.intersect(workingLine, planeIntersection)) { +#ifdef FC_DEBUG + SoDebugError::post("SbSphereSheetProjector::project", "Couldn't intersect with plane"); #endif } - else if (!tolPlane.intersect(workingLine, planeIntersection)) -#ifdef DEBUG - SoDebugError::post("SbSphereSheetProjector::project", "Couldn't intersect with plane"); -#else - /* Do nothing */; -#endif // Three possibilities: // (1) Intersection is on the sphere inside where the fillet @@ -292,7 +290,7 @@ private: private: SbMatrix worldToScreen; - OrbitStyle orbit{Trackball}; + OrbitStyle orbit{RoundedArcball}; }; NavigationStyleEvent::NavigationStyleEvent(const Base::Type& s) @@ -385,7 +383,7 @@ void NavigationStyle::initialize() this->zoomStep = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/View")->GetFloat("ZoomStep",0.2f); long mode = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View")->GetInt("RotationMode", 1); + ("User parameter:BaseApp/Preferences/View")->GetInt("RotationMode", 0); if (mode == 0) { setRotationCenterMode(NavigationStyle::RotationCenterMode::WindowCenter); } @@ -813,13 +811,16 @@ void NavigationStyle::zoom(SoCamera * cam, float diffvalue) // frustum (similar to glFrustum()) if (!t.isDerivedFrom(SoPerspectiveCamera::getClassTypeId()) && tname != "FrustumCamera") { - /* static SbBool first = true; - if (first) { - SoDebugError::postWarning("SoGuiFullViewerP::zoom", - "Unknown camera type, " - "will zoom by moving position, but this might not be correct."); - first = false; - }*/ +#ifdef FC_DEBUG + static SbBool first = true; + if (first) { + SoDebugError::postWarning("NavigationStyle::zoom", + "Unknown camera type, " + "will zoom by moving position, " + "but this might not be correct."); + first = false; + } +#endif } const float oldfocaldist = cam->focalDistance.getValue(); @@ -1719,8 +1720,9 @@ void NavigationStyle::syncWithEvent(const SoEvent * const ev) auto const event = static_cast(ev); const int button = event->getButton(); const SbBool press = event->getState() == SoButtonEvent::DOWN ? true : false; - - // SoDebugError::postInfo("processSoEvent", "button = %d", button); +#ifdef FC_DEBUG + SoDebugError::postInfo("processSoEvent", "button = %d", button); +#endif switch (button) { case SoMouseButtonEvent::BUTTON1: this->button1down = press; diff --git a/src/Gui/Navigation/NavigationStyle.h b/src/Gui/Navigation/NavigationStyle.h index 74e698d482..b3000728ab 100644 --- a/src/Gui/Navigation/NavigationStyle.h +++ b/src/Gui/Navigation/NavigationStyle.h @@ -105,7 +105,7 @@ public: Trackball, FreeTurntable, TrackballClassic, - RoundedArcball, + RoundedArcball }; enum class RotationCenterMode { diff --git a/src/Gui/NetworkRetriever.cpp b/src/Gui/NetworkRetriever.cpp index 989f1856fd..d46ccecbf8 100644 --- a/src/Gui/NetworkRetriever.cpp +++ b/src/Gui/NetworkRetriever.cpp @@ -119,7 +119,7 @@ void NetworkRetriever::testFailure() { d->fail = false; QString msg = tr("Download started..."); - Base::Console().Message("%s\n", msg.toUtf8().constData()); + Base::Console().message("%s\n", msg.toUtf8().constData()); } } @@ -265,7 +265,7 @@ bool NetworkRetriever::startDownload( const QString& startUrl ) { if (!dir.mkdir(d->dir)) { - Base::Console().Error("Directory '%s' could not be created.", (const char*)d->dir.toLatin1()); + Base::Console().error("Directory '%s' could not be created.", (const char*)d->dir.toLatin1()); return true; // please, no error message } } @@ -362,7 +362,7 @@ void NetworkRetriever::wgetFinished(int exitCode, QProcess::ExitStatus status) wget->setReadChannel(QProcess::StandardError); if (wget->canReadLine()) { QByteArray data = wget->readAll(); - Base::Console().Warning(data); + Base::Console().warning(data); } Q_EMIT wgetExited(); } @@ -535,7 +535,7 @@ void StdCmdDownloadOnlineHelp::activated(int iMsg) if (canStart) { bool ok = wget->startDownload(QString::fromLatin1(url.c_str())); if (!ok) - Base::Console().Error("The tool 'wget' couldn't be found. Please check your installation."); + Base::Console().error("The tool 'wget' couldn't be found. Please check your installation."); else if ( wget->isDownloading() && _pcAction ) _pcAction->setText(tr("Stop downloading")); } diff --git a/src/Gui/NotificationArea.cpp b/src/Gui/NotificationArea.cpp index 0925013a70..5a529e3de0 100644 --- a/src/Gui/NotificationArea.cpp +++ b/src/Gui/NotificationArea.cpp @@ -234,11 +234,11 @@ public: /// Function that is called by the console interface for this observer with the message /// information - void SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) override; /// Name of the observer - const char* Name() override + const char* name() override { return "NotificationAreaObserver"; } @@ -250,7 +250,7 @@ private: NotificationAreaObserver::NotificationAreaObserver(NotificationArea* notificationarea) : notificationArea(notificationarea) { - Base::Console().AttachObserver(this); + Base::Console().attachObserver(this); bLog = false; // ignore log messages bMsg = false; // ignore messages bNotification = true;// activate user notifications @@ -258,10 +258,10 @@ NotificationAreaObserver::NotificationAreaObserver(NotificationArea* notificatio NotificationAreaObserver::~NotificationAreaObserver() { - Base::Console().DetachObserver(this); + Base::Console().detachObserver(this); } -void NotificationAreaObserver::SendLog(const std::string& notifiername, const std::string& msg, +void NotificationAreaObserver::sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) { @@ -1063,7 +1063,7 @@ void NotificationArea::pushNotification(const QString& notifiername, const QStri // // But I want my message from my thread to appear in the notification area. Fine, then configure // Console not to use the direct connection mode, but the Queued one: - // Base::Console().SetConnectionMode(ConnectionMode::Queued); + // Base::Console().setConnectionMode(ConnectionMode::Queued); auto timer_thread = pImp->inhibitTimer.thread(); auto current_thread = QThread::currentThread(); diff --git a/src/Gui/Notifications.h b/src/Gui/Notifications.h index 39bd54cb98..20e2bcf156 100644 --- a/src/Gui/Notifications.h +++ b/src/Gui/Notifications.h @@ -164,27 +164,27 @@ inline void Gui::Notify(TNotifier && notifier, TCaption && caption, TMessage && auto msg = std::string(message).append("\n"); // use untranslated message if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getFullLabel(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getObject()->getFullLabel(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getDocument()->Label.getStrValue(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->Label.getStrValue(), msg.c_str()); } else { - Base::Console().Send(notifier, msg.c_str()); } @@ -234,19 +234,19 @@ inline void Gui::Notify(TNotifier && notifier, TCaption && caption, TMessage && auto msg = QStringLiteral("%1. %2").arg(caption).arg(message); // QString if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getFullLabel(), msg.toUtf8()); + Base::Console().send(notifier->getFullLabel(), msg.toUtf8()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getObject()->getFullLabel(), msg.toUtf8()); + Base::Console().send(notifier->getObject()->getFullLabel(), msg.toUtf8()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getDocument()->Label.getStrValue(), msg.toUtf8()); + Base::Console().send(notifier->getDocument()->Label.getStrValue(), msg.toUtf8()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->Label.getStrValue(), msg.toUtf8()); + Base::Console().send(notifier->Label.getStrValue(), msg.toUtf8()); } else { - Base::Console().Send(notifier, msg.toUtf8()); + Base::Console().send(notifier, msg.toUtf8()); } } else { @@ -254,19 +254,19 @@ inline void Gui::Notify(TNotifier && notifier, TCaption && caption, TMessage && auto msg = std::string(message).append("\n"); if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getFullLabel(), msg.c_str()); + Base::Console().send(notifier->getFullLabel(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getObject()->getFullLabel(), msg.c_str()); + Base::Console().send(notifier->getObject()->getFullLabel(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->getDocument()->Label.getStrValue(), msg.c_str()); + Base::Console().send(notifier->getDocument()->Label.getStrValue(), msg.c_str()); } else if constexpr( std::is_base_of_v::type>> ) { - Base::Console().Send(notifier->Label.getStrValue(), msg.c_str()); + Base::Console().send(notifier->Label.getStrValue(), msg.c_str()); } else { - Base::Console().Send(notifier, msg.c_str()); + Base::Console().send(notifier, msg.c_str()); } } } diff --git a/src/Gui/OnlineDocumentation.cpp b/src/Gui/OnlineDocumentation.cpp index e35486ebf3..2bbbbf9e81 100644 --- a/src/Gui/OnlineDocumentation.cpp +++ b/src/Gui/OnlineDocumentation.cpp @@ -124,7 +124,7 @@ QByteArray PythonOnlineHelp::invoke(const std::functionisVisible() || dockWidget->isFloating() - || _overlayMap.count(dockWidget)) + || _overlayMap.contains(dockWidget)) continue; if (dockWidget->rect().contains(dockWidget->mapFromGlobal(pos))) { dstDock = dockWidget; diff --git a/src/Gui/Placement.cpp b/src/Gui/Placement.cpp index 0a2e1a7a01..66411e8a1a 100644 --- a/src/Gui/Placement.cpp +++ b/src/Gui/Placement.cpp @@ -264,7 +264,7 @@ void PlacementHandler::applyPlacement(const Base::Placement& p, bool incremental } } else { - Base::Console().Warning("No object selected.\n"); + Base::Console().warning("No object selected.\n"); } } @@ -315,7 +315,7 @@ void PlacementHandler::applyPlacement(const QString& data, bool incremental) tryRecompute(document); } else { - Base::Console().Warning("No object selected.\n"); + Base::Console().warning("No object selected.\n"); } } } @@ -630,13 +630,13 @@ void Placement::onSelectedVertexClicked() axis = Base::Vector3d(picked[0] - picked[1]); } double length = axis.Length(); - Base::Console().Message("Distance: %.8f\n",length); + Base::Console().message("Distance: %.8f\n",length); if (QApplication::keyboardModifiers() == Qt::ShiftModifier){ //copy to clipboard on Shift+click QLocale loc; QApplication::clipboard()->setText(loc.toString(length,'g',8)); } else { - Base::Console().Message("(Shift + click Selected points button to copy distance to clipboard)\n"); + Base::Console().message("(Shift + click Selected points button to copy distance to clipboard)\n"); } axis.Normalize(); rot.setValue(axis, angle); @@ -678,20 +678,20 @@ void Placement::onSelectedVertexClicked() double angle; rot.getRawValue(tmp, angle); double length = (a-c).Length(); - Base::Console().Message("Distance: %.8f\n",length); + Base::Console().message("Distance: %.8f\n",length); Base::Vector3d v1(a-b); Base::Vector3d v2(c-b); v1.Normalize(); v2.Normalize(); double targetAngle = Base::toDegrees(v2.GetAngle(v1)); - Base::Console().Message("Target angle: %.8f degrees, complementary: %.8f degrees\n",targetAngle, 90.0-targetAngle); + Base::Console().message("Target angle: %.8f degrees, complementary: %.8f degrees\n",targetAngle, 90.0-targetAngle); if (QApplication::keyboardModifiers() == Qt::ShiftModifier){ //copy to clipboard on Shift+click QLocale loc; QApplication::clipboard()->setText(loc.toString(targetAngle,'g',8)); - Base::Console().Message("(Angle copied to clipboard, but you might need to use a negative (-) angle sometimes.)\n"); + Base::Console().message("(Angle copied to clipboard, but you might need to use a negative (-) angle sometimes.)\n"); } else { - Base::Console().Message("(Shift + click Selected points button to copy angle to clipboard)\n"); + Base::Console().message("(Shift + click Selected points button to copy angle to clipboard)\n"); } rot.setValue(norm, angle); plm.setRotation(rot); @@ -707,7 +707,7 @@ void Placement::onSelectedVertexClicked() ui->zCnt->setValue(center.z); if (!success) { - Base::Console().Warning("Placement selection error. Select either 1 or 2 points.\n"); + Base::Console().warning("Placement selection error. Select either 1 or 2 points.\n"); QMessageBox msgBox(this); msgBox.setText(tr("Please select 1, 2, or 3 points before clicking this button. A point may be on a vertex, \ face, or edge. If on a face or edge the point used will be the point at the mouse position along \ diff --git a/src/Gui/PrefWidgets.cpp b/src/Gui/PrefWidgets.cpp index f43a7650da..66dbeaa839 100644 --- a/src/Gui/PrefWidgets.cpp +++ b/src/Gui/PrefWidgets.cpp @@ -79,7 +79,7 @@ void PrefWidget::setParamGrpPath( const QByteArray& path ) if (getWindowParameter().isValid()) { if ( paramGrpPath() != path ) - Base::Console().Warning("Widget already attached\n"); + Base::Console().warning("Widget already attached\n"); } #endif @@ -153,7 +153,7 @@ void PrefWidget::failedToSave(const QString& name) const QByteArray objname = name.toLatin1(); if (objname.isEmpty()) objname = "Undefined"; - Console().Warning("Cannot save %s (%s)\n", typeid(*this).name(), objname.constData()); + Console().warning("Cannot save %s (%s)\n", typeid(*this).name(), objname.constData()); } void PrefWidget::failedToRestore(const QString& name) const @@ -161,7 +161,7 @@ void PrefWidget::failedToRestore(const QString& name) const QByteArray objname = name.toLatin1(); if (objname.isEmpty()) objname = "Undefined"; - Console().Warning("Cannot restore %s (%s)\n", typeid(*this).name(), objname.constData()); + Console().warning("Cannot restore %s (%s)\n", typeid(*this).name(), objname.constData()); } // -------------------------------------------------------------------- diff --git a/src/Gui/PreferencePackManager.cpp b/src/Gui/PreferencePackManager.cpp index 56581e9a4d..2bac18b0e2 100644 --- a/src/Gui/PreferencePackManager.cpp +++ b/src/Gui/PreferencePackManager.cpp @@ -96,7 +96,7 @@ bool PreferencePack::apply() const Base::Interpreter().runFile(Base::FileInfo::pathToString(preMacroPath).c_str(), false); } catch (...) { - Base::Console().Message("PreferencePack application aborted by the preferencePack's pre.FCMacro"); + Base::Console().message("PreferencePack application aborted by the preferencePack's pre.FCMacro"); return false; } } @@ -120,7 +120,7 @@ bool PreferencePack::apply() const Base::Interpreter().runFile(Base::FileInfo::pathToString(postMacroPath).c_str(), false); } catch (...) { - Base::Console().Message("PreferencePack application reverted by the preferencePack's post.FCMacro"); + Base::Console().message("PreferencePack application reverted by the preferencePack's post.FCMacro"); App::GetApplication().GetUserParameter().LoadDocument(Base::FileInfo::pathToString(backupFile).c_str()); return false; } @@ -284,7 +284,7 @@ std::vector Gui::PreferencePackManager::getPacksFromDirectory(const } catch (...) { // Failed to read the metadata, or to create the preferencePack based on it... - Base::Console().Error(("Failed to read " + packageMetadataFile.string()).c_str()); + Base::Console().error(("Failed to read " + packageMetadataFile.string()).c_str()); } } return results; @@ -296,12 +296,12 @@ void Gui::PreferencePackManager::FindPreferencePacksInPackage(const fs::path &mo TryFindPreferencePacksInPackage(mod); } catch (const std::exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } catch (...) { // Failed to read the metadata, or to create the preferencePack based on it... auto packageMetadataFile = mod / "package.xml"; - Base::Console().Error("Failed to read %s\n", Base::FileInfo::pathToString(packageMetadataFile).c_str()); + Base::Console().error("Failed to read %s\n", Base::FileInfo::pathToString(packageMetadataFile).c_str()); } } diff --git a/src/Gui/PreferencePackTemplates/View.cfg b/src/Gui/PreferencePackTemplates/View.cfg index 8c2392fb2c..5abee9232f 100644 --- a/src/Gui/PreferencePackTemplates/View.cfg +++ b/src/Gui/PreferencePackTemplates/View.cfg @@ -25,12 +25,12 @@ Gui::CADNavigationStyle - + - + diff --git a/src/Gui/PreferencePages/DlgSettingsGeneral.cpp b/src/Gui/PreferencePages/DlgSettingsGeneral.cpp index 1ad45f53d6..b12c80fbe1 100644 --- a/src/Gui/PreferencePages/DlgSettingsGeneral.cpp +++ b/src/Gui/PreferencePages/DlgSettingsGeneral.cpp @@ -63,7 +63,8 @@ using namespace Gui; using namespace Gui::Dialog; namespace fs = std::filesystem; -using namespace Base; +using Base::UnitsApi; +using Base::QuantityFormat; /* TRANSLATOR Gui::Dialog::DlgSettingsGeneral */ @@ -117,23 +118,16 @@ DlgSettingsGeneral::DlgSettingsGeneral( QWidget* parent ) connect(ui->comboBox_UnitSystem, qOverload(&QComboBox::currentIndexChanged), this, &DlgSettingsGeneral::onUnitSystemIndexChanged); ui->spinBoxDecimals->setMaximum(std::numeric_limits::digits10 + 1); - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - ui->comboBox_UnitSystem->addItem(item, i); - } + auto addItem = [&, index {0}](const std::string& item) mutable { + ui->comboBox_UnitSystem->addItem(QString::fromStdString(item), index++); + }; + auto descriptions = UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), addItem); // Enable/disable the fractional inch option depending on system - if (UnitsApi::getSchema() == UnitSystem::ImperialBuilding) - { - ui->comboBox_FracInch->setVisible(true); - ui->fractionalInchLabel->setVisible(true); - } - else - { - ui->comboBox_FracInch->setVisible(false); - ui->fractionalInchLabel->setVisible(false); - } + const auto visible = UnitsApi::isMultiUnitLength(); + ui->comboBox_FracInch->setVisible(visible); + ui->fractionalInchLabel->setVisible(visible); } /** @@ -211,7 +205,7 @@ void DlgSettingsGeneral::saveUnitSystemSettings() hGrpu->SetBool("IgnoreProjectSchema", ui->checkBox_projectUnitSystemIgnore->isChecked()); // Set actual value - Base::UnitsApi::setDecimals(ui->spinBoxDecimals->value()); + UnitsApi::setDecimals(ui->spinBoxDecimals->value()); // Convert the combobox index to the its integer denominator. Currently // with 1/2, 1/4, through 1/128, this little equation directly computes the @@ -225,21 +219,21 @@ void DlgSettingsGeneral::saveUnitSystemSettings() hGrpu->SetInt("FracInch", FracInch); // Set the actual format value - Base::QuantityFormat::setDefaultDenominator(FracInch); + QuantityFormat::setDefaultDenominator(FracInch); // Set and save the Unit System if (ui->checkBox_projectUnitSystemIgnore->isChecked()) { // currently selected View System (unit system) int viewSystemIndex = ui->comboBox_UnitSystem->currentIndex(); - UnitsApi::setSchema(static_cast(viewSystemIndex)); + UnitsApi::setSchema(viewSystemIndex); } else if (App::Document* doc = App::GetApplication().getActiveDocument()) { - UnitsApi::setSchema(static_cast(doc->UnitSystem.getValue())); + UnitsApi::setSchema(doc->UnitSystem.getValue()); } else { // if there is no existing document then the unit must still be set int viewSystemIndex = ui->comboBox_UnitSystem->currentIndex(); - UnitsApi::setSchema(static_cast(viewSystemIndex)); + UnitsApi::setSchema(viewSystemIndex); } ui->SubstituteDecimal->onSave(); @@ -294,11 +288,11 @@ void DlgSettingsGeneral::loadSettings() ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Units"); ui->comboBox_UnitSystem->setCurrentIndex(hGrpu->GetInt("UserSchema", 0)); - ui->spinBoxDecimals->setValue(hGrpu->GetInt("Decimals", Base::UnitsApi::getDecimals())); + ui->spinBoxDecimals->setValue(hGrpu->GetInt("Decimals", UnitsApi::getDecimals())); ui->checkBox_projectUnitSystemIgnore->setChecked(hGrpu->GetBool("IgnoreProjectSchema", false)); // Get the current user setting for the minimum fractional inch - FracInch = hGrpu->GetInt("FracInch", Base::QuantityFormat::getDefaultDenominator()); + FracInch = hGrpu->GetInt("FracInch", QuantityFormat::getDefaultDenominator()); // Convert fractional inch to the corresponding combobox index using this // handy little equation. @@ -536,11 +530,11 @@ void DlgSettingsGeneral::translateIconSizes() void DlgSettingsGeneral::retranslateUnits() { - int num = ui->comboBox_UnitSystem->count(); - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - ui->comboBox_UnitSystem->setItemText(i, item); - } + auto setItem = [&, index {0}](const std::string& item) mutable { + ui->comboBox_UnitSystem->setItemText(index++, QString::fromStdString(item)); + }; + const auto descriptions = UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), setItem); } void DlgSettingsGeneral::changeEvent(QEvent *event) @@ -768,22 +762,16 @@ void DlgSettingsGeneral::onLoadPreferencePackClicked(const std::string& packName } } -void DlgSettingsGeneral::onUnitSystemIndexChanged(int index) +void DlgSettingsGeneral::onUnitSystemIndexChanged(const int index) { - if (index < 0) - return; // happens when clearing the combo box in retranslateUi() + if (index < 0) { + return; // happens when clearing the combo box in retranslateUi() + } // Enable/disable the fractional inch option depending on system - if (static_cast(index) == UnitSystem::ImperialBuilding) - { - ui->comboBox_FracInch->setVisible(true); - ui->fractionalInchLabel->setVisible(true); - } - else - { - ui->comboBox_FracInch->setVisible(false); - ui->fractionalInchLabel->setVisible(false); - } + const auto visible = UnitsApi::isMultiUnitLength(); + ui->comboBox_FracInch->setVisible(visible); + ui->fractionalInchLabel->setVisible(visible); } void DlgSettingsGeneral::onThemeChanged(int index) { diff --git a/src/Gui/PreferencePages/DlgSettingsNavigation.cpp b/src/Gui/PreferencePages/DlgSettingsNavigation.cpp index 6a56a33d8f..e1425348a4 100644 --- a/src/Gui/PreferencePages/DlgSettingsNavigation.cpp +++ b/src/Gui/PreferencePages/DlgSettingsNavigation.cpp @@ -162,11 +162,11 @@ void DlgSettingsNavigation::loadSettings() int index = ui->comboNavigationStyle->findData(QByteArray(model.c_str())); if (index > -1) ui->comboNavigationStyle->setCurrentIndex(index); - index = hGrp->GetInt("OrbitStyle", int(NavigationStyle::Trackball)); + index = hGrp->GetInt("OrbitStyle", int(NavigationStyle::RoundedArcball)); index = Base::clamp(index, 0, ui->comboOrbitStyle->count()-1); ui->comboOrbitStyle->setCurrentIndex(index); - index = hGrp->GetInt("RotationMode", 1); + index = hGrp->GetInt("RotationMode", 0); ui->comboRotationMode->setCurrentIndex(index); bool showNaviCube = hGrp->GetBool("ShowNaviCube", true); diff --git a/src/Gui/PreferencePages/DlgSettingsNavigation.ui b/src/Gui/PreferencePages/DlgSettingsNavigation.ui index b081328995..94f7983e97 100644 --- a/src/Gui/PreferencePages/DlgSettingsNavigation.ui +++ b/src/Gui/PreferencePages/DlgSettingsNavigation.ui @@ -473,14 +473,15 @@ Select a set and then press the button to view said configurations. Rotation orbit style. -Trackball: moving the mouse horizontally will rotate the part around the y-axis +Rounded Arcball: moving the mouse in the corners of the screen will only roll the part. +Trackball: moving the mouse horizontally will rotate the part around the y-axis. +Trackball Classic: moving the mouse will rotate the part allowing precession. Turntable: the part will be rotated around the z-axis (with constrained axes). Free Turntable: the part will be rotated around the z-axis. -Trackball Classic: moving the mouse will rotate the part allowing precession -Rounded Arcball: moving the mouse in the corners of the screen will only roll the part. + - 1 + 4 @@ -534,7 +535,7 @@ Rounded Arcball: moving the mouse in the corners of the screen will only roll th Rotations in 3D will use current cursor position as center for rotation - 1 + 0 diff --git a/src/Gui/PreferencePages/DlgSettingsPDF.cpp b/src/Gui/PreferencePages/DlgSettingsPDF.cpp index b43bdbe130..97cfbfb9d8 100644 --- a/src/Gui/PreferencePages/DlgSettingsPDF.cpp +++ b/src/Gui/PreferencePages/DlgSettingsPDF.cpp @@ -36,7 +36,7 @@ void DlgSettingsPDF::loadSettings() int currentIndex = ui->comboBox->currentIndex(); #if QT_VERSION < QT_VERSION_CHECK(6,8,0) if (currentIndex == 3) { - Base::Console().Warning("When using another copy of FreeCAD you had set the PDF version to X4, but this build of FreeCAD does not support it. Using 1.4 instead.\n"); + Base::Console().warning("When using another copy of FreeCAD you had set the PDF version to X4, but this build of FreeCAD does not support it. Using 1.4 instead.\n"); currentIndex = 0; ui->comboBox->setCurrentIndex(0); } diff --git a/src/Gui/PreferencePages/DlgSettingsWorkbenchesImp.cpp b/src/Gui/PreferencePages/DlgSettingsWorkbenchesImp.cpp index 324ac60f80..784e949e33 100644 --- a/src/Gui/PreferencePages/DlgSettingsWorkbenchesImp.cpp +++ b/src/Gui/PreferencePages/DlgSettingsWorkbenchesImp.cpp @@ -433,7 +433,7 @@ QStringList DlgSettingsWorkbenchesImp::getEnabledWorkbenches() enabled_wbs_list.append(wbName); } else { - Base::Console().Log("Ignoring unknown %s workbench found in user preferences.\n", wbName.toStdString().c_str()); + Base::Console().log("Ignoring unknown %s workbench found in user preferences.\n", wbName.toStdString().c_str()); } } @@ -465,7 +465,7 @@ QStringList DlgSettingsWorkbenchesImp::getDisabledWorkbenches() disabled_wbs_list.append(wbName); } else { - Base::Console().Log("Ignoring unknown %s workbench found in user preferences.\n", wbName.toStdString().c_str()); + Base::Console().log("Ignoring unknown %s workbench found in user preferences.\n", wbName.toStdString().c_str()); } } diff --git a/src/Gui/PropertyPage.cpp b/src/Gui/PropertyPage.cpp index 3a8711481b..08c8407720 100644 --- a/src/Gui/PropertyPage.cpp +++ b/src/Gui/PropertyPage.cpp @@ -140,7 +140,7 @@ PreferenceUiForm::PreferenceUiForm(const QString& fn, QWidget* parent) setLayout(layout); } else { - Base::Console().Error("Failed to load UI file from '%s'\n", + Base::Console().error("Failed to load UI file from '%s'\n", (const char*)fn.toUtf8()); } } diff --git a/src/Gui/PropertyView.cpp b/src/Gui/PropertyView.cpp index 9f1094243e..e8650a1165 100644 --- a/src/Gui/PropertyView.cpp +++ b/src/Gui/PropertyView.cpp @@ -214,7 +214,7 @@ void PropertyView::slotRollback() { void PropertyView::slotChangePropertyData(const App::Property& prop) { - if (propertyEditorData->propOwners.count(prop.getContainer())) { + if (propertyEditorData->propOwners.contains(prop.getContainer())) { propertyEditorData->updateProperty(prop); timer->start(ViewParams::instance()->getPropertyViewTimer()); } @@ -222,7 +222,7 @@ void PropertyView::slotChangePropertyData(const App::Property& prop) void PropertyView::slotChangePropertyView(const Gui::ViewProvider&, const App::Property& prop) { - if (propertyEditorView->propOwners.count(prop.getContainer())) { + if (propertyEditorView->propOwners.contains(prop.getContainer())) { propertyEditorView->updateProperty(prop); timer->start(ViewParams::instance()->getPropertyViewTimer()); } @@ -239,8 +239,8 @@ void PropertyView::slotAppendDynamicProperty(const App::Property& prop) return; App::PropertyContainer* parent = prop.getContainer(); - if (propertyEditorData->propOwners.count(parent) - || propertyEditorView->propOwners.count(parent)) + if (propertyEditorData->propOwners.contains(parent) + || propertyEditorView->propOwners.contains(parent)) { timer->start(ViewParams::instance()->getPropertyViewTimer()); } @@ -249,9 +249,9 @@ void PropertyView::slotAppendDynamicProperty(const App::Property& prop) void PropertyView::slotRemoveDynamicProperty(const App::Property& prop) { App::PropertyContainer* parent = prop.getContainer(); - if(propertyEditorData->propOwners.count(parent)) + if(propertyEditorData->propOwners.contains(parent)) propertyEditorData->removeProperty(prop); - else if(propertyEditorView->propOwners.count(parent)) + else if(propertyEditorView->propOwners.contains(parent)) propertyEditorView->removeProperty(prop); else return; @@ -261,13 +261,13 @@ void PropertyView::slotRemoveDynamicProperty(const App::Property& prop) void PropertyView::slotChangePropertyEditor(const App::Document &, const App::Property& prop) { App::PropertyContainer* parent = prop.getContainer(); - if (propertyEditorData->propOwners.count(parent) - || propertyEditorView->propOwners.count(parent)) + if (propertyEditorData->propOwners.contains(parent) + || propertyEditorView->propOwners.contains(parent)) timer->start(ViewParams::instance()->getPropertyViewTimer()); } void PropertyView::slotDeleteDocument(const Gui::Document &doc) { - if(propertyEditorData->propOwners.count(doc.getDocument())) { + if(propertyEditorData->propOwners.contains(doc.getDocument())) { propertyEditorView->buildUp(); propertyEditorData->buildUp(); clearPropertyItemSelection(); @@ -276,7 +276,7 @@ void PropertyView::slotDeleteDocument(const Gui::Document &doc) { } void PropertyView::slotDeletedViewObject(const Gui::ViewProvider &vp) { - if(propertyEditorView->propOwners.count(&vp)) { + if(propertyEditorView->propOwners.contains(&vp)) { propertyEditorView->buildUp(); propertyEditorData->buildUp(); clearPropertyItemSelection(); @@ -285,7 +285,7 @@ void PropertyView::slotDeletedViewObject(const Gui::ViewProvider &vp) { } void PropertyView::slotDeletedObject(const App::DocumentObject &obj) { - if(propertyEditorData->propOwners.count(&obj)) { + if(propertyEditorData->propOwners.contains(&obj)) { propertyEditorView->buildUp(); propertyEditorData->buildUp(); clearPropertyItemSelection(); @@ -341,7 +341,7 @@ void PropertyView::onTimer() { // See https://forum.freecad.org/viewtopic.php?f=8&t=72526 if (this->updating) { - Base::Console().Log("Ignore recursive call of PropertyView::onTimer()\n"); + Base::Console().log("Ignore recursive call of PropertyView::onTimer()\n"); return; } Base::StateLocker guard(this->updating); diff --git a/src/Gui/PythonConsolePy.cpp b/src/Gui/PythonConsolePy.cpp index 08b1f415a6..e2af2d1701 100644 --- a/src/Gui/PythonConsolePy.cpp +++ b/src/Gui/PythonConsolePy.cpp @@ -197,7 +197,7 @@ Py::Object OutputStdout::write(const Py::Tuple& args) PyObject* unicode = PyUnicode_AsEncodedString(output, "utf-8", nullptr); if (unicode) { const char* string = PyBytes_AsString(unicode); - Base::Console().Message("%s",string); + Base::Console().message("%s",string); Py_DECREF(unicode); } @@ -258,7 +258,7 @@ Py::Object OutputStderr::write(const Py::Tuple& args) PyObject* unicode = PyUnicode_AsEncodedString(output, "utf-8", nullptr); if (unicode) { const char* string = PyBytes_AsString(unicode); - Base::Console().Error("%s",string); + Base::Console().error("%s",string); Py_DECREF(unicode); } diff --git a/src/Gui/PythonDebugger.cpp b/src/Gui/PythonDebugger.cpp index 773678a4df..ffe8891ad4 100644 --- a/src/Gui/PythonDebugger.cpp +++ b/src/Gui/PythonDebugger.cpp @@ -225,7 +225,7 @@ Py::Object PythonDebugStderr::write(const Py::Tuple& args) if (strlen(msg) > 0) { - Base::Console().Error("%s", msg); + Base::Console().error("%s", msg); } return Py::None(); @@ -414,7 +414,7 @@ void PythonDebugger::runFile(const QString& fn) //PySys_WriteStderr("Exception: %s\n", e.what()); } catch (...) { - Base::Console().Warning("Unknown exception thrown during macro debugging\n"); + Base::Console().warning("Unknown exception thrown during macro debugging\n"); } } diff --git a/src/Gui/PythonEditor.cpp b/src/Gui/PythonEditor.cpp index 668f6b8029..a76c1eeba7 100644 --- a/src/Gui/PythonEditor.cpp +++ b/src/Gui/PythonEditor.cpp @@ -322,9 +322,9 @@ void PythonEditor::onExecuteInConsole() Gui::Command::doCommand(Gui::Command::Doc, dedentedCode.toStdString().c_str()); } catch (const Base::Exception& e) { QString errorMessage = QString::fromStdString(e.what()); - Base::Console().Error("Error executing Python code:\n%s\n", errorMessage.toUtf8().constData()); + Base::Console().error("Error executing Python code:\n%s\n", errorMessage.toUtf8().constData()); } catch (...) { - Base::Console().Error("An unknown error occurred while executing Python code.\n"); + Base::Console().error("An unknown error occurred while executing Python code.\n"); } } } diff --git a/src/Gui/PythonWrapper.cpp b/src/Gui/PythonWrapper.cpp index 58c6fc88a2..1bda2cf2d1 100644 --- a/src/Gui/PythonWrapper.cpp +++ b/src/Gui/PythonWrapper.cpp @@ -412,7 +412,7 @@ public: Shiboken::Object::setValidCpp(sbk_ptr, false); } else { - Base::Console().DeveloperError("WrapperManager", "A QObject has just been destroyed after its Pythonic wrapper.\n"); + Base::Console().developerError("WrapperManager", "A QObject has just been destroyed after its Pythonic wrapper.\n"); } Py_DECREF (pyobj); }; @@ -601,7 +601,7 @@ qsizetype PythonWrapper::toEnum(PyObject* pyPtr) } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return 0; } } diff --git a/src/Gui/QuantitySpinBox.cpp b/src/Gui/QuantitySpinBox.cpp index 326e04bc4b..2a1d79f885 100644 --- a/src/Gui/QuantitySpinBox.cpp +++ b/src/Gui/QuantitySpinBox.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include "QuantitySpinBox.h" #include "QuantitySpinBox_p.h" @@ -714,7 +715,7 @@ void QuantitySpinBox::setDecimals(int v) updateText(d->quantity); } -void QuantitySpinBox::setSchema(const Base::UnitSystem& s) +void QuantitySpinBox::setSchema(const int s) { Q_D(QuantitySpinBox); d->scheme = Base::UnitsApi::createSchema(s); @@ -732,7 +733,7 @@ QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor { Q_D(const QuantitySpinBox); std::string unitStr; - std::string str = d->scheme ? val.getUserString(d->scheme.get(), factor, unitStr) + const std::string str = d->scheme ? val.getUserString(d->scheme.get(), factor, unitStr) : val.getUserString(factor, unitStr); unitString = QString::fromStdString(unitStr); return QString::fromStdString(str); diff --git a/src/Gui/QuantitySpinBox.h b/src/Gui/QuantitySpinBox.h index 780553718c..7c17216436 100644 --- a/src/Gui/QuantitySpinBox.h +++ b/src/Gui/QuantitySpinBox.h @@ -24,7 +24,6 @@ #ifndef GUI_QUANTITYSPINBOX_H #define GUI_QUANTITYSPINBOX_H -#include #include #include @@ -99,7 +98,7 @@ public: /// Sets a specific unit schema to handle quantities. /// The system-wide schema won't be used any more. - void setSchema(const Base::UnitSystem& s); + void setSchema(int s); /// Clears the schemaand again use the system-wide schema. void clearSchema(); diff --git a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp index e98bd2d77f..2659960952 100644 --- a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp +++ b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp @@ -241,7 +241,7 @@ void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::setCameraType(SoType type) SoCamera* cam = getSoRenderManager()->getCamera(); if (cam && !cam->isOfType(SoPerspectiveCamera::getClassTypeId()) && !cam->isOfType(SoOrthographicCamera::getClassTypeId())) { - Base::Console().Warning("Quarter::setCameraType", + Base::Console().warning("Quarter::setCameraType", "Only SoPerspectiveCamera and SoOrthographicCamera is supported."); return; } @@ -293,7 +293,7 @@ void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::convertOrtho2Perspective(const So SoPerspectiveCamera* out) { if (!in || !out) { - Base::Console().Log("Quarter::convertOrtho2Perspective", + Base::Console().log("Quarter::convertOrtho2Perspective", "Cannot convert camera settings due to wrong input."); return; } diff --git a/src/Gui/ReportView.cpp b/src/Gui/ReportView.cpp index fce293d6a5..ba834e1cf6 100644 --- a/src/Gui/ReportView.cpp +++ b/src/Gui/ReportView.cpp @@ -433,7 +433,7 @@ ReportOutput::ReportOutput(QWidget* parent) clear(); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - Base::Console().AttachObserver(this); + Base::Console().attachObserver(this); getWindowParameter()->Attach(this); getWindowParameter()->NotifyAll(); // do this explicitly because the keys below might not yet be part of a group @@ -457,7 +457,7 @@ ReportOutput::~ReportOutput() { getWindowParameter()->Detach(this); _prefs->Detach(this); - Base::Console().DetachObserver(this); + Base::Console().detachObserver(this); delete reportHl; delete d; } @@ -468,7 +468,7 @@ void ReportOutput::restoreFont() setFont(serifFont); } -void ReportOutput::SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, +void ReportOutput::sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) { // Do not log translated messages, or messages intended only to the user to the Report View diff --git a/src/Gui/ReportView.h b/src/Gui/ReportView.h index 276284ca9f..1f4be9d070 100644 --- a/src/Gui/ReportView.h +++ b/src/Gui/ReportView.h @@ -141,11 +141,11 @@ public: /** Observes its parameter group. */ void OnChange(Base::Subject &rCaller, const char * sReason) override; - void SendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, Base::ContentType content) override; /// returns the name for observer handling - const char* Name() override {return "ReportOutput";} + const char* name() override {return "ReportOutput";} /** Restore the default font settings. */ void restoreFont (); diff --git a/src/Gui/Selection/Selection.cpp b/src/Gui/Selection/Selection.cpp index 112edc9e3b..baa7b87669 100644 --- a/src/Gui/Selection/Selection.cpp +++ b/src/Gui/Selection/Selection.cpp @@ -154,7 +154,7 @@ void SelectionObserver::_onSelectionChanged(const SelectionChanges& msg) { return; onSelectionChanged(msg); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); FC_ERR("Unhandled Base::Exception caught in selection observer: "); } catch (std::exception &e) { FC_ERR("Unhandled std::exception caught in selection observer: " << e.what()); @@ -545,7 +545,7 @@ void SelectionSingleton::notify(SelectionChanges &&Chng) } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("notify: Unexpected boost exception\n"); + Base::Console().warning("notify: Unexpected boost exception\n"); } } NotificationQueue.pop_front(); @@ -698,7 +698,7 @@ void SelectionSingleton::slotSelectionChanged(const SelectionChanges& msg) } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("slotSelectionChanged: Unexpected boost exception\n"); + Base::Console().warning("slotSelectionChanged: Unexpected boost exception\n"); } } else { @@ -708,7 +708,7 @@ void SelectionSingleton::slotSelectionChanged(const SelectionChanges& msg) } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("slotSelectionChanged: Unexpected boost exception\n"); + Base::Console().warning("slotSelectionChanged: Unexpected boost exception\n"); } } } @@ -841,7 +841,7 @@ QString getPreselectionInfo(const char* documentName, { auto pts = schemaTranslatePoint(x, y, z, precision); - int numberDecimals = std::min(6, Base::UnitsApi::getDecimals()); + int numberDecimals = std::min(6, static_cast(Base::UnitsApi::getDecimals())); QString message = QStringLiteral("Preselected: %1.%2.%3 (%4 %5, %6 %7, %8 %9)") .arg(QString::fromUtf8(documentName)) diff --git a/src/Gui/Selection/SelectionFilter.cpp b/src/Gui/Selection/SelectionFilter.cpp index 4508ec6167..fdc613d0c8 100644 --- a/src/Gui/Selection/SelectionFilter.cpp +++ b/src/Gui/Selection/SelectionFilter.cpp @@ -104,7 +104,7 @@ bool SelectionGatePython::allow(App::Document* doc, App::DocumentObject* obj, co } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return true; diff --git a/src/Gui/Selection/SelectionObserverPython.cpp b/src/Gui/Selection/SelectionObserverPython.cpp index a2434fa2f6..890671873f 100644 --- a/src/Gui/Selection/SelectionObserverPython.cpp +++ b/src/Gui/Selection/SelectionObserverPython.cpp @@ -92,7 +92,7 @@ void SelectionObserverPythonHandler::pickedListChanged() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -115,7 +115,7 @@ void SelectionObserverPythonHandler::addSelection(const SelectionChanges& msg) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -133,7 +133,7 @@ void SelectionObserverPythonHandler::removeSelection(const SelectionChanges& msg } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -149,7 +149,7 @@ void SelectionObserverPythonHandler::setSelection(const SelectionChanges& msg) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -165,7 +165,7 @@ void SelectionObserverPythonHandler::clearSelection(const SelectionChanges& msg) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -183,7 +183,7 @@ void SelectionObserverPythonHandler::setPreselection(const SelectionChanges& msg } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -201,7 +201,7 @@ void SelectionObserverPythonHandler::removePreselection(const SelectionChanges& } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/Selection/SelectionView.cpp b/src/Gui/Selection/SelectionView.cpp index 469f8d0f72..1c1a616e52 100644 --- a/src/Gui/Selection/SelectionView.cpp +++ b/src/Gui/Selection/SelectionView.cpp @@ -343,7 +343,7 @@ void SelectionView::select(QListWidgetItem* item) Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -366,7 +366,7 @@ void SelectionView::deselect() Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -418,7 +418,7 @@ void SelectionView::toggleSelect(QListWidgetItem* item) Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -457,7 +457,7 @@ void SelectionView::preselect(QListWidgetItem* item) Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -468,7 +468,7 @@ void SelectionView::zoom() Gui::Command::runCommand(Gui::Command::Gui, "Gui.SendMsgToActiveView(\"ViewSelection\")"); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -479,7 +479,7 @@ void SelectionView::treeSelect() Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand(\"Std_TreeSelection\")"); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -499,7 +499,7 @@ void SelectionView::touch() Gui::Command::runCommand(Gui::Command::Doc, cmd.toLatin1()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -535,7 +535,7 @@ void SelectionView::toPython() } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -560,7 +560,7 @@ void SelectionView::showPart() Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } } diff --git a/src/Gui/Selection/SoFCSelectionContext.cpp b/src/Gui/Selection/SoFCSelectionContext.cpp index 8ab9a3886f..241d2d488f 100644 --- a/src/Gui/Selection/SoFCSelectionContext.cpp +++ b/src/Gui/Selection/SoFCSelectionContext.cpp @@ -104,7 +104,7 @@ int SoFCSelectionContext::merge(int status, SoFCSelectionContextBasePtr &output, std::vector remove; for(auto idx : ret->selectionIndex) { - if(!ctx->selectionIndex.count(idx)) + if(!ctx->selectionIndex.contains(idx)) remove.push_back(idx); } @@ -216,7 +216,7 @@ int SoFCSelectionContextEx::merge(int status, SoFCSelectionContextBasePtr &outpu auto ret = std::dynamic_pointer_cast(output); assert(ret); for(auto &v : ctx->colors) { - if(ret->colors.count(v.first)) + if(ret->colors.contains(v.first)) continue; if(!status) { status = 1; diff --git a/src/Gui/SoFCColorBar.cpp b/src/Gui/SoFCColorBar.cpp index 4308baa992..a1a3645161 100644 --- a/src/Gui/SoFCColorBar.cpp +++ b/src/Gui/SoFCColorBar.cpp @@ -287,7 +287,7 @@ void SoFCColorBar::customize(SoFCColorBarBase* child) return child->customize(this); } catch (const Base::ValueError& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/SoFCColorGradient.cpp b/src/Gui/SoFCColorGradient.cpp index 50c7a15190..9f7af9e366 100644 --- a/src/Gui/SoFCColorGradient.cpp +++ b/src/Gui/SoFCColorGradient.cpp @@ -440,7 +440,7 @@ void SoFCColorGradient::customize(SoFCColorBarBase* parentNode) applyProfile(dlg.getProfile(), dlg.numberOfDecimals()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } }); diff --git a/src/Gui/SplashScreen.cpp b/src/Gui/SplashScreen.cpp index 92bac0563c..04a0e00adc 100644 --- a/src/Gui/SplashScreen.cpp +++ b/src/Gui/SplashScreen.cpp @@ -65,7 +65,7 @@ public: , alignment(Qt::AlignBottom | Qt::AlignLeft) , textColor(Qt::black) { - Base::Console().AttachObserver(this); + Base::Console().attachObserver(this); // allow to customize text position and color const std::map& cfg = App::Application::Config(); @@ -107,13 +107,13 @@ public: } ~SplashObserver() override { - Base::Console().DetachObserver(this); + Base::Console().detachObserver(this); } - const char* Name() override + const char* name() override { return "SplashObserver"; } - void SendLog(const std::string& notifiername, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, diff --git a/src/Gui/StartupProcess.cpp b/src/Gui/StartupProcess.cpp index 76b7e3022e..d154ca1d76 100644 --- a/src/Gui/StartupProcess.cpp +++ b/src/Gui/StartupProcess.cpp @@ -279,7 +279,7 @@ void StartupPostProcess::setLocale() hGrp->GetASCII("Language", Translator::instance()->activeLanguage().c_str())); } else if (localeFormat == 2) { - Translator::instance()->setLocale("C"); + Translator::instance()->setLocale("C.UTF-8"); } } @@ -308,10 +308,10 @@ void StartupPostProcess::checkOpenGL() if (context.create()) { context.makeCurrent(&window); if (!context.functions()->hasOpenGLFeature(QOpenGLFunctions::Framebuffers)) { - Base::Console().Log("This system does not support framebuffer objects\n"); + Base::Console().log("This system does not support framebuffer objects\n"); } if (!context.functions()->hasOpenGLFeature(QOpenGLFunctions::NPOTTextures)) { - Base::Console().Log("This system does not support NPOT textures\n"); + Base::Console().log("This system does not support NPOT textures\n"); } int major = context.format().majorVersion(); @@ -328,7 +328,7 @@ void StartupPostProcess::checkOpenGL() .arg(major) .arg(minor) + QStringLiteral("\n"); - Base::Console().Warning(message.toStdString().c_str()); + Base::Console().warning(message.toStdString().c_str()); Dialog::DlgCheckableMessageBox::showMessage( QCoreApplication::applicationName() + QStringLiteral(" - ") + QObject::tr("Invalid OpenGL Version"), @@ -336,7 +336,7 @@ void StartupPostProcess::checkOpenGL() } #endif const char* glVersion = reinterpret_cast(glGetString(GL_VERSION)); - Base::Console().Log("OpenGL version is: %d.%d (%s)\n", major, minor, glVersion); + Base::Console().log("OpenGL version is: %d.%d (%s)\n", major, minor, glVersion); } } @@ -411,12 +411,12 @@ void StartupPostProcess::showMainWindow() // running the GUI init script try { - Base::Console().Log("Run Gui init script\n"); + Base::Console().log("Run Gui init script\n"); Application::runInitGuiScript(); setImportImageFormats(); } catch (const Base::Exception& e) { - Base::Console().Error("Error in FreeCADGuiInit.py: %s\n", e.what()); + Base::Console().error("Error in FreeCADGuiInit.py: %s\n", e.what()); mainWindow->stopSplasher(); throw; @@ -432,7 +432,7 @@ void StartupPostProcess::activateWorkbench() { // Activate the correct workbench std::string start = App::Application::Config()["StartWorkbench"]; - Base::Console().Log("Init: Activating default workbench %s\n", start.c_str()); + Base::Console().log("Init: Activating default workbench %s\n", start.c_str()); std::string autoload = App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") @@ -469,7 +469,7 @@ void StartupPostProcess::activateWorkbench() // show the main window if (!Application::hiddenMainWindow()) { - Base::Console().Log("Init: Showing main window\n"); + Base::Console().log("Init: Showing main window\n"); mainWindow->loadWindowSettings(); } @@ -528,11 +528,11 @@ void StartupPostProcess::autoloadModules(const QStringList& wb) void StartupPostProcess::checkParameters() { if (App::GetApplication().GetSystemParameter().IgnoreSave()) { - Base::Console().Warning("System parameter file couldn't be opened.\n" + Base::Console().warning("System parameter file couldn't be opened.\n" "Continue with an empty configuration that won't be saved.\n"); } if (App::GetApplication().GetUserParameter().IgnoreSave()) { - Base::Console().Warning("User parameter file couldn't be opened.\n" + Base::Console().warning("User parameter file couldn't be opened.\n" "Continue with an empty configuration that won't be saved.\n"); } } diff --git a/src/Gui/TaskElementColors.cpp b/src/Gui/TaskElementColors.cpp index 0741bc25af..c11eb8d99b 100644 --- a/src/Gui/TaskElementColors.cpp +++ b/src/Gui/TaskElementColors.cpp @@ -108,7 +108,7 @@ public: vpParent->OnTopWhenSelected.setValue(onTopMode); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/TaskView/TaskAppearance.cpp b/src/Gui/TaskView/TaskAppearance.cpp index 67d4d5bab2..f2fba23a22 100644 --- a/src/Gui/TaskView/TaskAppearance.cpp +++ b/src/Gui/TaskView/TaskAppearance.cpp @@ -166,7 +166,7 @@ void TaskAppearance::onChangeModeActivated(const QString& s) void TaskAppearance::onChangePlotActivated(const QString& s) { - Base::Console().Log("Plot = %s\n", (const char*)s.toLatin1()); + Base::Console().log("Plot = %s\n", (const char*)s.toLatin1()); } /** diff --git a/src/Gui/TaskView/TaskDialogPython.cpp b/src/Gui/TaskView/TaskDialogPython.cpp index 7650778226..5bf0e2019d 100644 --- a/src/Gui/TaskView/TaskDialogPython.cpp +++ b/src/Gui/TaskView/TaskDialogPython.cpp @@ -303,7 +303,7 @@ bool TaskWatcherPython::shouldShow() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } if (!this->Filter.empty()) @@ -582,7 +582,7 @@ bool TaskDialogPython::tryLoadUiFile() appendForm(form, QPixmap(icon)); } else { - Base::Console().Error("Failed to load UI file from '%s'\n", + Base::Console().error("Failed to load UI file from '%s'\n", (const char*)fn.toUtf8()); } @@ -660,7 +660,7 @@ void TaskDialogPython::open() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -678,7 +678,7 @@ void TaskDialogPython::clicked(int i) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -695,7 +695,7 @@ bool TaskDialogPython::accept() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::accept(); @@ -714,7 +714,7 @@ bool TaskDialogPython::reject() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::reject(); @@ -732,7 +732,7 @@ void TaskDialogPython::helpRequested() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -750,7 +750,7 @@ bool TaskDialogPython::eventFilter(QObject *watched, QEvent *event) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -772,7 +772,7 @@ QDialogButtonBox::StandardButtons TaskDialogPython::getStandardButtons() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::getStandardButtons(); @@ -794,7 +794,7 @@ void TaskDialogPython::modifyStandardButtons(QDialogButtonBox *buttonBox) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -811,7 +811,7 @@ bool TaskDialogPython::isAllowedAlterDocument() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::isAllowedAlterDocument(); @@ -830,7 +830,7 @@ bool TaskDialogPython::isAllowedAlterView() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::isAllowedAlterView(); @@ -849,7 +849,7 @@ bool TaskDialogPython::isAllowedAlterSelection() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::isAllowedAlterSelection(); @@ -868,7 +868,7 @@ bool TaskDialogPython::needsFullSpace() const } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return TaskDialog::needsFullSpace(); @@ -886,7 +886,7 @@ void TaskDialogPython::autoClosedOnTransactionChange() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -902,6 +902,6 @@ void TaskDialogPython::autoClosedOnDeletedDocument() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/TaskView/TaskImage.cpp b/src/Gui/TaskView/TaskImage.cpp index 8266e0ee95..61c60cdbcf 100644 --- a/src/Gui/TaskView/TaskImage.cpp +++ b/src/Gui/TaskView/TaskImage.cpp @@ -573,7 +573,7 @@ void InteractiveScale::collectPoint(const SbVec3f& pos3d) Q_EMIT enableApplyBtn(); } else { - Base::Console().Warning(std::string("Image scale"), + Base::Console().warning(std::string("Image scale"), "The second point is too close. Retry!\n"); } } diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.cpp b/src/Gui/TaskView/TaskSelectLinkProperty.cpp index 51c3b630e2..e37faf706e 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.cpp +++ b/src/Gui/TaskView/TaskSelectLinkProperty.cpp @@ -75,7 +75,7 @@ TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter, LinkList = dynamic_cast(prop); } else { - Base::Console().Warning("Unknown Link property type in " + Base::Console().warning("Unknown Link property type in " "Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()"); } diff --git a/src/Gui/TaskView/TaskView.cpp b/src/Gui/TaskView/TaskView.cpp index 310e58af1b..25ee639aed 100644 --- a/src/Gui/TaskView/TaskView.cpp +++ b/src/Gui/TaskView/TaskView.cpp @@ -289,16 +289,16 @@ TaskView::TaskView(QWidget *parent) connectApplicationActiveDocument = App::GetApplication().signalActiveDocument.connect (std::bind(&Gui::TaskView::TaskView::slotActiveDocument, this, sp::_1)); - connectApplicationDeleteDocument = + connectApplicationDeleteDocument = App::GetApplication().signalDeleteDocument.connect (std::bind(&Gui::TaskView::TaskView::slotDeletedDocument, this, sp::_1)); connectApplicationClosedView = Gui::Application::Instance->signalCloseView.connect (std::bind(&Gui::TaskView::TaskView::slotViewClosed, this, sp::_1)); - connectApplicationUndoDocument = + connectApplicationUndoDocument = App::GetApplication().signalUndoDocument.connect (std::bind(&Gui::TaskView::TaskView::slotUndoDocument, this, sp::_1)); - connectApplicationRedoDocument = + connectApplicationRedoDocument = App::GetApplication().signalRedoDocument.connect (std::bind(&Gui::TaskView::TaskView::slotRedoDocument, this, sp::_1)); //NOLINTEND @@ -453,7 +453,7 @@ QSize TaskView::minimumSizeHint() const void TaskView::slotActiveDocument(const App::Document& doc) { - Q_UNUSED(doc); + Q_UNUSED(doc); if (!ActiveDialog) updateWatcher(); } @@ -464,7 +464,7 @@ void TaskView::slotDeletedDocument(const App::Document& doc) if (ActiveDialog->isAutoCloseOnDeletedDocument()) { std::string name = ActiveDialog->getDocumentName(); if (name.empty()) { - Base::Console().Warning(std::string("TaskView::slotDeletedDocument"), + Base::Console().warning(std::string("TaskView::slotDeletedDocument"), "No document name set\n"); } @@ -487,7 +487,7 @@ void TaskView::slotViewClosed(const Gui::MDIView* view) if (ActiveDialog->isAutoCloseOnClosedView()) { const Gui::MDIView* associatedView = ActiveDialog->getAssociatedView(); if (!associatedView) { - Base::Console().Warning(std::string("TaskView::slotViewClosed"), + Base::Console().warning(std::string("TaskView::slotViewClosed"), "No view associated\n"); } @@ -509,7 +509,7 @@ void TaskView::transactionChangeOnDocument(const App::Document& doc) if (ActiveDialog->isAutoCloseOnTransactionChange()) { std::string name = ActiveDialog->getDocumentName(); if (name.empty()) { - Base::Console().Warning(std::string("TaskView::transactionChangeOnDocument"), + Base::Console().warning(std::string("TaskView::transactionChangeOnDocument"), "No document name set\n"); } @@ -539,11 +539,11 @@ void TaskView::slotRedoDocument(const App::Document& doc) void TaskView::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, Gui::SelectionSingleton::MessageType Reason) { - Q_UNUSED(rCaller); + Q_UNUSED(rCaller); std::string temp; if (Reason.Type == SelectionChanges::AddSelection || - Reason.Type == SelectionChanges::ClrSelection || + Reason.Type == SelectionChanges::ClrSelection || Reason.Type == SelectionChanges::SetSelection || Reason.Type == SelectionChanges::RmvSelection) { @@ -648,7 +648,7 @@ void TaskView::removeDialog() // put the watcher back in control addTaskWatcher(); - + if (remove) { remove->closed(); remove->emitDestructionSignal(); @@ -823,7 +823,7 @@ void TaskView::removeTaskWatcher() void TaskView::accept() { if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions - Base::Console().Warning("ActiveDialog was null in call to TaskView::accept()\n"); + Base::Console().warning("ActiveDialog was null in call to TaskView::accept()\n"); return; } @@ -839,7 +839,7 @@ void TaskView::accept() void TaskView::reject() { if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions - Base::Console().Warning("ActiveDialog was null in call to TaskView::reject()\n"); + Base::Console().warning("ActiveDialog was null in call to TaskView::reject()\n"); return; } diff --git a/src/Gui/ToolBarManager.cpp b/src/Gui/ToolBarManager.cpp index ee01114b36..0b2ade5b05 100644 --- a/src/Gui/ToolBarManager.cpp +++ b/src/Gui/ToolBarManager.cpp @@ -78,7 +78,7 @@ const std::string & ToolBarItem::command() const bool ToolBarItem::hasItems() const { - return _items.count() > 0; + return !_items.isEmpty(); } ToolBarItem* ToolBarItem::findItem(const std::string& name) diff --git a/src/Gui/Tree.cpp b/src/Gui/Tree.cpp index 5e7ee7bf83..8ddc8df26a 100644 --- a/src/Gui/Tree.cpp +++ b/src/Gui/Tree.cpp @@ -75,11 +75,11 @@ FC_LOG_LEVEL_INIT("Tree", false, true, true) #define _TREE_PRINT(_level,_func,_msg) \ _FC_PRINT(FC_LOG_INSTANCE,_level,_func, '['<,_msg) -#define TREE_WARN(_msg) _TREE_PRINT(FC_LOGLEVEL_WARN,Notify,_msg) -#define TREE_ERR(_msg) _TREE_PRINT(FC_LOGLEVEL_ERR,Notify,_msg) -#define TREE_LOG(_msg) _TREE_PRINT(FC_LOGLEVEL_LOG,Notify,_msg) -#define TREE_TRACE(_msg) _TREE_PRINT(FC_LOGLEVEL_TRACE,Notify,_msg) +#define TREE_MSG(_msg) _TREE_PRINT(FC_LOGLEVEL_MSG,notify,_msg) +#define TREE_WARN(_msg) _TREE_PRINT(FC_LOGLEVEL_WARN,notify,_msg) +#define TREE_ERR(_msg) _TREE_PRINT(FC_LOGLEVEL_ERR,notify,_msg) +#define TREE_LOG(_msg) _TREE_PRINT(FC_LOGLEVEL_LOG,notify,_msg) +#define TREE_TRACE(_msg) _TREE_PRINT(FC_LOGLEVEL_TRACE,notify,_msg) using namespace Gui; namespace sp = std::placeholders; @@ -1177,12 +1177,12 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) header()->setVisible(action->isChecked()||internalNameAction->isChecked()); }); - if (contextMenu.actions().count() > 0) { + if (!contextMenu.actions().isEmpty()) { try { contextMenu.exec(QCursor::pos()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (std::exception& e) { FC_ERR("C++ exception: " << e.what()); @@ -1808,7 +1808,7 @@ void TreeWidget::mouseDoubleClickEvent(QMouseEvent* event) } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (std::exception& e) { FC_ERR("C++ exception: " << e.what()); @@ -2071,7 +2071,7 @@ void TreeWidget::dragMoveEvent(QDragMoveEvent* event) } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); event->ignore(); } catch (std::exception& e) { @@ -2320,7 +2320,7 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); errMsg = e.what(); } catch (std::exception& e) { @@ -2573,7 +2573,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, } } - if (inList.count(obj)) { + if (inList.contains(obj)) { FC_THROWM(Base::RuntimeError, "Dependency loop detected for " << obj->getFullName()); } @@ -2682,7 +2682,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); errMsg = e.what(); } catch (std::exception& e) { @@ -2874,7 +2874,7 @@ void TreeWidget::onCloseDoc() Command::doCommand(Command::Doc, "App.closeDocument(\"%s\")", doc->getName()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (std::exception& e) { FC_ERR("C++ exception: " << e.what()); @@ -3059,7 +3059,7 @@ void TreeWidget::onUpdateStatus() continue; if (obj->isError()) errors.push_back(obj); - if (docItem->ObjectMap.count(obj)) + if (docItem->ObjectMap.contains(obj)) continue; auto vpd = freecad_cast(gdoc->getViewProvider(obj)); if (vpd) @@ -3931,7 +3931,7 @@ bool DocumentItem::createNewItem(const Gui::ViewProviderDocumentObject& obj, entry.insert(pdata); } else if (pdata->rootItem && !parent) { - Base::Console().Warning("DocumentItem::slotNewObject: Cannot add view provider twice.\n"); + Base::Console().warning("DocumentItem::slotNewObject: Cannot add view provider twice.\n"); return false; } data = pdata; @@ -4447,7 +4447,7 @@ void TreeWidget::updateChildren(App::DocumentObject* obj, // and thus, its property change will not be propagated through // recomputation. So we have to manually check for each links here. for (auto link : App::GetApplication().getLinksTo(obj, App::GetLinkRecursive)) { - if (ChangedObjects.count(link)) + if (ChangedObjects.contains(link)) continue; std::vector linkedChildren; DocumentObjectDataPtr found; @@ -4475,7 +4475,7 @@ void TreeWidget::updateChildren(App::DocumentObject* obj, //if the item is in a GeoFeatureGroup we may need to update that too, as the claim children //of the geofeaturegroup depends on what the childs claim auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(obj); - if (grp && !ChangedObjects.count(grp)) { + if (grp && !ChangedObjects.contains(grp)) { auto iter = ObjectTable.find(grp); if (iter != ObjectTable.end()) updateChildren(grp, iter->second, true, false); diff --git a/src/Gui/VectorListEditor.cpp b/src/Gui/VectorListEditor.cpp index 85e69ec673..00eb6f603d 100644 --- a/src/Gui/VectorListEditor.cpp +++ b/src/Gui/VectorListEditor.cpp @@ -210,7 +210,7 @@ void Gui::VectorTableModel::pasteFromClipboard() else { QString msg(tr("Unsupported format. Must be 3 values per row separated by tabs, semicolons, or commas:") + QLatin1String("\n")); msg += clipboard->text(); - Base::Console().Error(msg.toStdString().c_str()); + Base::Console().error(msg.toStdString().c_str()); } } diff --git a/src/Gui/View3DInventor.cpp b/src/Gui/View3DInventor.cpp index 11a722fbdf..7b2f2b241f 100644 --- a/src/Gui/View3DInventor.cpp +++ b/src/Gui/View3DInventor.cpp @@ -219,7 +219,7 @@ void View3DInventor::onRename(Gui::Document *pDoc) void View3DInventor::onUpdate() { #ifdef FC_LOGUPDATECHAIN - Base::Console().Log("Acti: Gui::View3DInventor::onUpdate()"); + Base::Console().log("Acti: Gui::View3DInventor::onUpdate()"); #endif update(); _viewer->redraw(); diff --git a/src/Gui/View3DInventorRiftViewer.cpp b/src/Gui/View3DInventorRiftViewer.cpp index 3dd1a92647..c37a945176 100644 --- a/src/Gui/View3DInventorRiftViewer.cpp +++ b/src/Gui/View3DInventorRiftViewer.cpp @@ -86,7 +86,7 @@ View3DInventorRiftViewer::~View3DInventorRiftViewer() hGrp->SetInt("RenderWindowSizeW",size().width()); hGrp->SetInt("RenderWindowSizeH",size().height()); - Base::Console().Log("pos: %d %d size: %d %d \n",pos().x(),pos().y(), + Base::Console().log("pos: %d %d size: %d %d \n",pos().x(),pos().y(), size().width(),size().height()); } diff --git a/src/Gui/View3DInventorViewer.cpp b/src/Gui/View3DInventorViewer.cpp index ff7890285f..7007908768 100644 --- a/src/Gui/View3DInventorViewer.cpp +++ b/src/Gui/View3DInventorViewer.cpp @@ -262,14 +262,14 @@ public: if (event->type() == Spaceball::ButtonEvent::ButtonEventType) { auto buttonEvent = static_cast(event); // NOLINT if (!buttonEvent) { - Base::Console().Log("invalid spaceball button event\n"); + Base::Console().log("invalid spaceball button event\n"); return true; } } else if (event->type() == Spaceball::MotionEvent::MotionEventType) { auto motionEvent = static_cast(event); // NOLINT if (!motionEvent) { - Base::Console().Log("invalid spaceball motion event\n"); + Base::Console().log("invalid spaceball motion event\n"); return true; } } @@ -287,7 +287,7 @@ public: if (event->type() == Spaceball::MotionEvent::MotionEventType) { auto motionEvent = static_cast(event); // NOLINT if (!motionEvent) { - Base::Console().Log("invalid spaceball motion event\n"); + Base::Console().log("invalid spaceball motion event\n"); return nullptr; } @@ -624,9 +624,9 @@ void View3DInventorViewer::init() this->grabGesture(Qt::PanGesture); this->grabGesture(Qt::PinchGesture); } catch (Base::Exception &e) { - Base::Console().Warning("Failed to set up gestures. Error: %s\n", e.what()); + Base::Console().warning("Failed to set up gestures. Error: %s\n", e.what()); } catch (...) { - Base::Console().Warning("Failed to set up gestures. Unknown error.\n"); + Base::Console().warning("Failed to set up gestures. Unknown error.\n"); } //create the cursors @@ -1019,18 +1019,18 @@ void View3DInventorViewer::resetEditingRoot(bool updateLinks) Py::Object py = Py::type(e); if (py.isString()) { Py::String str(py); - Base::Console().Warning("%s\n", str.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", str.as_std_string("utf-8").c_str()); } else { Py::String str(py.repr()); - Base::Console().Warning("%s\n", str.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", str.as_std_string("utf-8").c_str()); } // Prints message to console window if we are in interactive mode PyErr_Print(); } catch (Py::Exception& e) { e.clear(); - Base::Console().Error("Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n"); + Base::Console().error("Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n"); } } } @@ -2029,7 +2029,7 @@ void View3DInventorViewer::interactionFinishCB(void* ud, SoQTQuarterAdaptor* vie void View3DInventorViewer::interactionLoggerCB(void* ud, SoAction* action) { Q_UNUSED(ud) - Base::Console().Log("%s\n", action->getTypeId().getName().getString()); + Base::Console().log("%s\n", action->getTypeId().getName().getString()); } void View3DInventorViewer::addGraphicsItem(GLGraphicsItem* item) @@ -2215,7 +2215,7 @@ void View3DInventorViewer::imageFromFramebuffer(int width, int height, int sampl const QOpenGLContext* context = QOpenGLContext::currentContext(); if (!context) { - Base::Console().Warning("imageFromFramebuffer failed because no context is active\n"); + Base::Console().warning("imageFromFramebuffer failed because no context is active\n"); return; } @@ -3575,7 +3575,7 @@ void View3DInventorViewer::alignToSelection() // Convert to global coordinates globalRotation.multVec(alignmentZ, alignmentZ); globalRotation.multVec(alignmentX, alignmentX); - + const auto cameraOrientation = getCameraOrientation(); auto directionZ = Base::convertTo(alignmentZ); @@ -3605,18 +3605,18 @@ void View3DInventorViewer::alignToSelection() if (axis.dot(directionZ) < 0 && angle != 0) { angle *= -1; } - + using std::numbers::pi; // Make angle positive if (angle < 0) { angle += 2 * pi; } - + // Find the angle to rotate to the nearest horizontal or vertical alignment with directionX. // f is a small value used to get more deterministic behavior when the camera is at directionX +- 45 degrees. const float f = 0.00001F; - + if (angle <= pi/4 + f) { angle = 0; } @@ -3642,7 +3642,7 @@ void View3DInventorViewer::alignToSelection() directionY[0], directionY[1], directionY[2], 0, directionZ[0], directionZ[1], directionZ[2], 0, 0, 0, 0, 1)); - + setCameraOrientation(orientation); } } @@ -4295,7 +4295,7 @@ void View3DInventorViewer::removeEventCallback(SoType eventtype, SoEventCallback ViewProvider* View3DInventorViewer::getViewProviderByPath(SoPath* path) const { if (!guiDocument) { - Base::Console().Warning("View3DInventorViewer::getViewProviderByPath: No document set\n"); + Base::Console().warning("View3DInventorViewer::getViewProviderByPath: No document set\n"); return nullptr; } return guiDocument->getViewProviderByPathFromHead(path); @@ -4304,7 +4304,7 @@ ViewProvider* View3DInventorViewer::getViewProviderByPath(SoPath* path) const ViewProvider* View3DInventorViewer::getViewProviderByPathFromTail(SoPath* path) const { if (!guiDocument) { - Base::Console().Warning("View3DInventorViewer::getViewProviderByPathFromTail: No document set\n"); + Base::Console().warning("View3DInventorViewer::getViewProviderByPathFromTail: No document set\n"); return nullptr; } return guiDocument->getViewProviderByPathFromTail(path); @@ -4313,7 +4313,7 @@ ViewProvider* View3DInventorViewer::getViewProviderByPathFromTail(SoPath* path) std::vector View3DInventorViewer::getViewProvidersOfType(const Base::Type& typeId) const { if (!guiDocument) { - Base::Console().Warning("View3DInventorViewer::getViewProvidersOfType: No document set\n"); + Base::Console().warning("View3DInventorViewer::getViewProvidersOfType: No document set\n"); return {}; } return guiDocument->getViewProvidersOfType(typeId); diff --git a/src/Gui/View3DPy.cpp b/src/Gui/View3DPy.cpp index 30eaf2a56a..178f20cc0d 100644 --- a/src/Gui/View3DPy.cpp +++ b/src/Gui/View3DPy.cpp @@ -2026,11 +2026,11 @@ void View3DInventorPy::eventCallback(void * ud, SoEventCallback * n) Py::Object o = Py::type(e); if (o.isString()) { Py::String s(o); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } else { Py::String s(o.repr()); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } // Prints message to console window if we are in interactive mode PyErr_Print(); @@ -2178,11 +2178,11 @@ void View3DInventorPy::eventCallbackPivy(void * ud, SoEventCallback * n) Py::Object o = Py::type(e); if (o.isString()) { Py::String s(o); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } else { Py::String s(o.repr()); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } // Prints message to console window if we are in interactive mode PyErr_Print(); @@ -2211,11 +2211,11 @@ void View3DInventorPy::eventCallbackPivyEx(void * ud, SoEventCallback * n) Py::Object o = Py::type(e); if (o.isString()) { Py::String s(o); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } else { Py::String s(o.repr()); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } // Prints message to console window if we are in interactive mode PyErr_Print(); @@ -2347,11 +2347,11 @@ void View3DInventorPy::draggerCallback(void * ud, SoDragger* n) Py::Object o = Py::type(e); if (o.isString()) { Py::String s(o); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } else { Py::String s(o.repr()); - Base::Console().Warning("%s\n", s.as_std_string("utf-8").c_str()); + Base::Console().warning("%s\n", s.as_std_string("utf-8").c_str()); } // Prints message to console window if we are in interactive mode PyErr_Print(); diff --git a/src/Gui/View3DSettings.cpp b/src/Gui/View3DSettings.cpp index 9bd0669627..57c67331a8 100644 --- a/src/Gui/View3DSettings.cpp +++ b/src/Gui/View3DSettings.cpp @@ -320,7 +320,7 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M } } else if (strcmp(Reason,"OrbitStyle") == 0) { - int style = rGrp.GetInt("OrbitStyle",1); + int style = rGrp.GetInt("OrbitStyle",4); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setOrbitStyle(NavigationStyle::OrbitStyle(style)); } diff --git a/src/Gui/ViewProvider.cpp b/src/Gui/ViewProvider.cpp index d3d7aee137..82823721a2 100644 --- a/src/Gui/ViewProvider.cpp +++ b/src/Gui/ViewProvider.cpp @@ -275,19 +275,19 @@ void ViewProvider::eventCallback(void * ud, SoEventCallback * node) } } catch (const Base::Exception& e) { - Base::Console().Error("Unhandled exception in ViewProvider::eventCallback: %s\n" + Base::Console().error("Unhandled exception in ViewProvider::eventCallback: %s\n" "(Event type: %s, object type: %s)\n" , e.what(), ev->getTypeId().getName().getString() , self->getTypeId().getName()); } catch (const std::exception& e) { - Base::Console().Error("Unhandled std exception in ViewProvider::eventCallback: %s\n" + Base::Console().error("Unhandled std exception in ViewProvider::eventCallback: %s\n" "(Event type: %s, object type: %s)\n" , e.what(), ev->getTypeId().getName().getString() , self->getTypeId().getName()); } catch (...) { - Base::Console().Error("Unhandled unknown C++ exception in ViewProvider::eventCallback" + Base::Console().error("Unhandled unknown C++ exception in ViewProvider::eventCallback" " (Event type: %s, object type: %s)\n" , ev->getTypeId().getName().getString() , self->getTypeId().getName()); @@ -736,11 +736,11 @@ bool ViewProvider::canDropObject(App::DocumentObject* obj) const { auto vector = getExtensionsDerivedFromType(); #if FC_DEBUG - Base::Console().Log("Check extensions for drop\n"); + Base::Console().log("Check extensions for drop\n"); #endif for (Gui::ViewProviderExtension* ext : vector){ #if FC_DEBUG - Base::Console().Log("Check extensions %s\n", ext->name().c_str()); + Base::Console().log("Check extensions %s\n", ext->name().c_str()); #endif if (ext->extensionCanDropObject(obj)) return true; diff --git a/src/Gui/ViewProviderCoordinateSystem.cpp b/src/Gui/ViewProviderCoordinateSystem.cpp index 32d1465ec1..2689e1031b 100644 --- a/src/Gui/ViewProviderCoordinateSystem.cpp +++ b/src/Gui/ViewProviderCoordinateSystem.cpp @@ -134,7 +134,7 @@ void ViewProviderCoordinateSystem::setTemporaryVisibility(DatumElements elements } } catch (const Base::Exception &ex) { - Base::Console().Error ("%s\n", ex.what() ); + Base::Console().error ("%s\n", ex.what() ); } // Remember & Set self visibility diff --git a/src/Gui/ViewProviderFeaturePython.cpp b/src/Gui/ViewProviderFeaturePython.cpp index 23c4c1383c..f92045caef 100644 --- a/src/Gui/ViewProviderFeaturePython.cpp +++ b/src/Gui/ViewProviderFeaturePython.cpp @@ -151,7 +151,7 @@ QIcon ViewProviderFeaturePythonImp::getIcon() const PyErr_Clear(); else { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -179,7 +179,7 @@ bool ViewProviderFeaturePythonImp::claimChildren(std::vectortruncate(length); return Rejected; @@ -392,7 +392,7 @@ ViewProviderFeaturePythonImp::setEdit(int ModNum) return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -433,7 +433,7 @@ ViewProviderFeaturePythonImp::unsetEdit(int ModNum) return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -459,7 +459,7 @@ ViewProviderFeaturePythonImp::setEditViewer(View3DInventorViewer *viewer, int Mo return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; } @@ -484,7 +484,7 @@ ViewProviderFeaturePythonImp::unsetEditViewer(View3DInventorViewer *viewer) return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; } @@ -516,7 +516,7 @@ ViewProviderFeaturePythonImp::doubleClicked() return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -553,7 +553,7 @@ bool ViewProviderFeaturePythonImp::setupContextMenu(QMenu* menu) return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return true; } @@ -580,7 +580,7 @@ void ViewProviderFeaturePythonImp::attach(App::DocumentObject *pcObject) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -612,7 +612,7 @@ void ViewProviderFeaturePythonImp::updateData(const App::Property* prop) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -644,7 +644,7 @@ void ViewProviderFeaturePythonImp::onChanged(const App::Property* prop) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -676,7 +676,7 @@ void ViewProviderFeaturePythonImp::onBeforeChange(const App::Property* prop) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -698,7 +698,7 @@ void ViewProviderFeaturePythonImp::finishRestoring() } }catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -735,7 +735,7 @@ ViewProviderFeaturePythonImp::onDelete(const std::vector & sub) return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -757,7 +757,7 @@ ViewProviderFeaturePythonImp::canDelete(App::DocumentObject *obj) const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); return Rejected; } } @@ -777,7 +777,7 @@ ViewProviderFeaturePythonImp::canAddToSceneGraph() const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Accepted; } @@ -799,7 +799,7 @@ bool ViewProviderFeaturePythonImp::getDefaultDisplayMode(std::string &mode) cons return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return true; @@ -835,7 +835,7 @@ std::vector ViewProviderFeaturePythonImp::getDisplayModes() const PyErr_Clear(); else { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -856,7 +856,7 @@ std::string ViewProviderFeaturePythonImp::setDisplayMode(const char* ModeName) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return ModeName; @@ -878,7 +878,7 @@ ViewProviderFeaturePythonImp::canDragObjects() const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -902,7 +902,7 @@ ViewProviderFeaturePythonImp::canDragObject(App::DocumentObject* obj) const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -936,7 +936,7 @@ ViewProviderFeaturePythonImp::dragObject(App::DocumentObject* obj) return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -958,7 +958,7 @@ ViewProviderFeaturePythonImp::canDropObjects() const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -982,7 +982,7 @@ ViewProviderFeaturePythonImp::canDropObject(App::DocumentObject* obj) const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -1014,7 +1014,7 @@ ViewProviderFeaturePythonImp::dropObject(App::DocumentObject* obj) PyErr_Clear(); return NotImplemented; } - Base::PyException::ThrowException(); + Base::PyException::throwException(); } return Rejected; @@ -1037,7 +1037,7 @@ ViewProviderFeaturePythonImp::canDragAndDropObject(App::DocumentObject *obj) con return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -1069,7 +1069,7 @@ ViewProviderFeaturePythonImp::canDropObjectEx(App::DocumentObject* obj, return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -1102,7 +1102,7 @@ bool ViewProviderFeaturePythonImp::dropObjectEx(App::DocumentObject* obj, App::D PyErr_Clear(); return false; } - Base::PyException::ThrowException(); + Base::PyException::throwException(); } return true; } @@ -1123,7 +1123,7 @@ ViewProviderFeaturePythonImp::isShow() const return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; @@ -1146,7 +1146,7 @@ ViewProviderFeaturePythonImp::canRemoveChildrenFromRoot() const { return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; } @@ -1169,7 +1169,7 @@ bool ViewProviderFeaturePythonImp::getDropPrefix(std::string &prefix) const { return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return true; } @@ -1197,7 +1197,7 @@ ViewProviderFeaturePythonImp::replaceObject( return NotImplemented; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return Rejected; } @@ -1239,7 +1239,7 @@ bool ViewProviderFeaturePythonImp::getLinkedViewProvider( return false; } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return true; } @@ -1261,7 +1261,7 @@ bool ViewProviderFeaturePythonImp::editProperty(const char *name) } Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } return false; } diff --git a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp index e441220f4b..608847e413 100644 --- a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp +++ b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp @@ -104,7 +104,7 @@ std::vector ViewProviderGeoFeatureGroupExtension::extensio for(auto obj : model) { if(!obj || !obj->isAttachedToDocument()) continue; - if(outSet.count(obj)) + if(outSet.contains(obj)) obj->setStatus(App::ObjectStatus::GeoExcluded,true); else { obj->setStatus(App::ObjectStatus::GeoExcluded,false); diff --git a/src/Gui/ViewProviderGroupExtension.cpp b/src/Gui/ViewProviderGroupExtension.cpp index 9fdc5f7c90..3577f10a45 100644 --- a/src/Gui/ViewProviderGroupExtension.cpp +++ b/src/Gui/ViewProviderGroupExtension.cpp @@ -75,7 +75,7 @@ bool ViewProviderGroupExtension::extensionCanDropObjects() const { bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj) const { #ifdef FC_DEBUG - Base::Console().Log("Check ViewProviderGroupExtension\n"); + Base::Console().log("Check ViewProviderGroupExtension\n"); #endif auto extobj = getExtendedViewProvider()->getObject(); @@ -89,7 +89,7 @@ bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj // Check for possible cyclic dependencies if we allowed to drop the object const auto& list = obj->getOutList(); if (std::ranges::find(list, extobj) != list.end()) { - Base::Console().Warning("Do not add cyclic dependency to %s\n", extobj->Label.getValue()); + Base::Console().warning("Do not add cyclic dependency to %s\n", extobj->Label.getValue()); return false; } diff --git a/src/Gui/ViewProviderLink.cpp b/src/Gui/ViewProviderLink.cpp index b9c0f126f9..265d77ef56 100644 --- a/src/Gui/ViewProviderLink.cpp +++ b/src/Gui/ViewProviderLink.cpp @@ -2521,7 +2521,7 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch } Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); } @@ -2539,7 +2539,7 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch ext->getLinkCopyOnChangeProperty()->setValue(1); Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); act = submenu->addAction(QObject::tr("Tracking")); @@ -2553,7 +2553,7 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch ext->getLinkCopyOnChangeProperty()->setValue(3); Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); } @@ -2571,7 +2571,7 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch ext->getLinkCopyOnChangeProperty()->setValue((long)0); Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); } @@ -2590,7 +2590,7 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch ext->syncCopyOnChange(); Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); } @@ -2616,7 +2616,7 @@ void ViewProviderLink::_setupContextMenu( ext->getShowElementProperty()->setValue(!ext->getShowElementValue()); Command::updateActive(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); } }); action->setToolTip(QObject::tr( @@ -2692,7 +2692,7 @@ bool ViewProviderLink::initDraggingPlacement() { } } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return false; } @@ -2897,7 +2897,7 @@ bool ViewProviderLink::callDraggerProxy(const char* fname) { } } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return true; } @@ -2936,10 +2936,10 @@ void ViewProviderLink::updateLinks(ViewProvider *vp) { ext->linkInfo->update(); } catch (const Base::TypeError &e) { - e.ReportException(); + e.reportException(); } catch (const Base::ValueError &e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/ViewProviderTextureExtension.cpp b/src/Gui/ViewProviderTextureExtension.cpp index 2c86e82150..4ec1d1b5de 100644 --- a/src/Gui/ViewProviderTextureExtension.cpp +++ b/src/Gui/ViewProviderTextureExtension.cpp @@ -95,7 +95,7 @@ void ViewProviderTextureExtension::setCoinAppearance(SoMaterial* pcShapeMaterial { #if 0 if (!source.image.empty()) { - Base::Console().Log("setCoinAppearance(Texture)\n"); + Base::Console().log("setCoinAppearance(Texture)\n"); activateTexture2D(); QByteArray by = QByteArray::fromBase64(QString::fromStdString(source.image).toUtf8()); @@ -105,7 +105,7 @@ void ViewProviderTextureExtension::setCoinAppearance(SoMaterial* pcShapeMaterial Gui::BitmapFactory().convert(image, texture); pcShapeTexture2D->image = texture; } else { - Base::Console().Log("setCoinAppearance(Material)\n"); + Base::Console().log("setCoinAppearance(Material)\n"); activateMaterial(); } #endif diff --git a/src/Gui/ViewProviderVRMLObject.cpp b/src/Gui/ViewProviderVRMLObject.cpp index 0bf4f262d6..b851f8b97e 100644 --- a/src/Gui/ViewProviderVRMLObject.cpp +++ b/src/Gui/ViewProviderVRMLObject.cpp @@ -232,7 +232,7 @@ void ViewProviderVRMLObject::updateData(const App::Property* prop) if (node) { if (!checkRecursion(node)) { - Base::Console().Error("The VRML file causes an infinite recursion!\n"); + Base::Console().error("The VRML file causes an infinite recursion!\n"); return; } pcVRML->addChild(node); diff --git a/src/Gui/WidgetFactory.cpp b/src/Gui/WidgetFactory.cpp index 01f820e09a..5322086848 100644 --- a/src/Gui/WidgetFactory.cpp +++ b/src/Gui/WidgetFactory.cpp @@ -77,9 +77,9 @@ QWidget* WidgetFactoryInst::createWidget (const char* sName, QWidget* parent) co // this widget class is not registered if (!w) { #ifdef FC_DEBUG - Base::Console().Warning("\"%s\" is not registered\n", sName); + Base::Console().warning("\"%s\" is not registered\n", sName); #else - Base::Console().Log("\"%s\" is not registered\n", sName); + Base::Console().log("\"%s\" is not registered\n", sName); #endif return nullptr; } @@ -87,14 +87,14 @@ QWidget* WidgetFactoryInst::createWidget (const char* sName, QWidget* parent) co try { #ifdef FC_DEBUG const char* cName = qobject_cast(w)->metaObject()->className(); - Base::Console().Log("Widget of type '%s' created.\n", cName); + Base::Console().log("Widget of type '%s' created.\n", cName); #endif } catch (...) { #ifdef FC_DEBUG - Base::Console().Error("%s does not inherit from \"QWidget\"\n", sName); + Base::Console().error("%s does not inherit from \"QWidget\"\n", sName); #else - Base::Console().Log("%s does not inherit from \"QWidget\"\n", sName); + Base::Console().log("%s does not inherit from \"QWidget\"\n", sName); #endif delete w; return nullptr; @@ -119,21 +119,21 @@ Gui::Dialog::PreferencePage* WidgetFactoryInst::createPreferencePage (const char // this widget class is not registered if (!w) { #ifdef FC_DEBUG - Base::Console().Warning("Cannot create an instance of \"%s\"\n", sName); + Base::Console().warning("Cannot create an instance of \"%s\"\n", sName); #else - Base::Console().Log("Cannot create an instance of \"%s\"\n", sName); + Base::Console().log("Cannot create an instance of \"%s\"\n", sName); #endif return nullptr; } if (qobject_cast(w)) { #ifdef FC_DEBUG - Base::Console().Log("Preference page of type '%s' created.\n", w->metaObject()->className()); + Base::Console().log("Preference page of type '%s' created.\n", w->metaObject()->className()); #endif } else { #ifdef FC_DEBUG - Base::Console().Error("%s does not inherit from 'Gui::Dialog::PreferencePage'\n", sName); + Base::Console().error("%s does not inherit from 'Gui::Dialog::PreferencePage'\n", sName); #endif delete w; return nullptr; @@ -172,7 +172,7 @@ QWidget* WidgetFactoryInst::createPrefWidget(const char* sName, QWidget* parent, } catch (...) { #ifdef FC_DEBUG - Base::Console().Error("%s does not inherit from \"PrefWidget\"\n", w->metaObject()->className()); + Base::Console().error("%s does not inherit from \"PrefWidget\"\n", w->metaObject()->className()); #endif delete w; return nullptr; @@ -314,7 +314,7 @@ void PreferencePagePython::loadSettings() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -330,7 +330,7 @@ void PreferencePagePython::saveSettings() } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/Gui/Widgets.cpp b/src/Gui/Widgets.cpp index bf3fb836c9..a112f5ba42 100644 --- a/src/Gui/Widgets.cpp +++ b/src/Gui/Widgets.cpp @@ -854,7 +854,7 @@ UrlLabel::UrlLabel(QWidget* parent, Qt::WindowFlags f) , _url (QStringLiteral("http://localhost")) , _launchExternal(true) { - setToolTip(this->_url); + setToolTip(this->_url); setCursor(Qt::PointingHandCursor); if (qApp->styleSheet().isEmpty()) setStyleSheet(QStringLiteral("Gui--UrlLabel {color: #0000FF;text-decoration: underline;}")); @@ -919,9 +919,9 @@ void StatefulLabel::setParameterGroup(const std::string& groupName) { if (_parameterGroup.isValid()) _parameterGroup->Detach(this); - + // Attach to the Parametergroup so we know when it changes - _parameterGroup = App::GetApplication().GetParameterGroupByPath(groupName.c_str()); + _parameterGroup = App::GetApplication().GetParameterGroupByPath(groupName.c_str()); if (_parameterGroup.isValid()) _parameterGroup->Attach(this); } diff --git a/src/Gui/Widgets.h b/src/Gui/Widgets.h index 7eae3c745b..01f4ab54f9 100644 --- a/src/Gui/Widgets.h +++ b/src/Gui/Widgets.h @@ -1,4 +1,4 @@ -/*************************************************************************** + /*************************************************************************** * Copyright (c) 2004 Werner Mayer * * * * This file is part of the FreeCAD CAx development system. * @@ -300,7 +300,7 @@ public: QString url() const; bool launchExternal() const; - + Q_SIGNALS: void linkClicked(QString url); @@ -318,18 +318,18 @@ private: /** - * A text label whose appearance can change based on a specified state. + * A text label whose appearance can change based on a specified state. * - * The state is an arbitrary string exposed as a Qt Property (and thus available for selection via - * a stylesheet). This is intended for things like messages to the user, where a message that is an + * The state is an arbitrary string exposed as a Qt Property (and thus available for selection via + * a stylesheet). This is intended for things like messages to the user, where a message that is an * "error" might be colored differently than one that is a "warning" or a "message". - * + * * In order of style precedence for a given state: User preference > Stylesheet > Default * unless the stylesheet sets the overridePreference, in which case the stylesheet will * take precedence. If a stylesheet sets styles for this widgets states, it should also * set the "handledByStyle" property to ensure the style values are used, rather than the * defaults. - * + * * For example, the .qss might contain: * Gui--StatefulLabel { * qproperty-overridePreference: true; @@ -339,7 +339,7 @@ private: * } * In this case, StatefulLabels with state "special_state" will be colored red, regardless of any * entry in preferences. Use the "overridePreference" stylesheet option with care! - * + * * @author Chris Hennes */ class GuiExport StatefulLabel : public QLabel, public Base::Observer @@ -361,15 +361,15 @@ public: void setParameterGroup(const std::string& groupName); /** Register a state and its corresponding style (optionally attached to a user preference) */ - void registerState(const QString &state, const QString &styleCSS, + void registerState(const QString &state, const QString &styleCSS, const std::string& preferenceName = std::string()); /** For convenience, allow simple color-only states via QColor (optionally attached to a user preference) */ - void registerState(const QString& state, const QColor& color, + void registerState(const QString& state, const QColor& color, const std::string& preferenceName = std::string()); /** For convenience, allow simple color-only states via QColor (optionally attached to a user preference) */ - void registerState(const QString& state, const QColor& foregroundColor, const QColor& backgroundColor, + void registerState(const QString& state, const QColor& foregroundColor, const QColor& backgroundColor, const std::string& preferenceName = std::string()); /** Observes the parameter group and clears the cache if it changes */ @@ -389,7 +389,7 @@ private: QString defaultCSS; std::string preferenceString; }; - + std::map _availableStates; std::map _styleCache; QString _defaultStyle; diff --git a/src/Gui/WorkbenchManipulatorPython.cpp b/src/Gui/WorkbenchManipulatorPython.cpp index e7c220da41..dafcdf0361 100644 --- a/src/Gui/WorkbenchManipulatorPython.cpp +++ b/src/Gui/WorkbenchManipulatorPython.cpp @@ -89,7 +89,7 @@ void WorkbenchManipulatorPython::modifyMenuBar(MenuItem* menuBar) } catch (Py::Exception&) { Base::PyException exc; // extract the Python error text - exc.ReportException(); + exc.reportException(); } } @@ -194,7 +194,7 @@ void WorkbenchManipulatorPython::modifyContextMenu(const char* recipient, MenuIt } catch (Py::Exception&) { Base::PyException exc; // extract the Python error text - exc.ReportException(); + exc.reportException(); } } @@ -232,7 +232,7 @@ void WorkbenchManipulatorPython::modifyToolBars(ToolBarItem* toolBar) } catch (Py::Exception&) { Base::PyException exc; // extract the Python error text - exc.ReportException(); + exc.reportException(); } } @@ -340,7 +340,7 @@ void WorkbenchManipulatorPython::modifyDockWindows(DockWindowItems* dockWindow) } catch (Py::Exception&) { Base::PyException exc; // extract the Python error text - exc.ReportException(); + exc.reportException(); } } diff --git a/src/Gui/propertyeditor/PropertyEditor.cpp b/src/Gui/propertyeditor/PropertyEditor.cpp index 653064ed15..05d426de68 100644 --- a/src/Gui/propertyeditor/PropertyEditor.cpp +++ b/src/Gui/propertyeditor/PropertyEditor.cpp @@ -377,16 +377,16 @@ void PropertyEditor::recomputeDocument(App::Document* doc) } // do not re-throw catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const std::exception& e) { - Base::Console().Error( + Base::Console().error( "Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n" "The error message is: %s\n", e.what()); } catch (...) { - Base::Console().Error( + Base::Console().error( "Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n"); } } @@ -612,7 +612,7 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDoc checkDocument = _checkDocument; if (committing) { - Base::Console().Warning( + Base::Console().warning( "While committing the data to the property the selection has changed.\n"); delaybuild = true; return; @@ -919,7 +919,7 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) prop->getContainer()->removeDynamicProperty(prop->getName()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } break; diff --git a/src/Gui/propertyeditor/PropertyItem.cpp b/src/Gui/propertyeditor/PropertyItem.cpp index d5bedcf79e..208e86c894 100644 --- a/src/Gui/propertyeditor/PropertyItem.cpp +++ b/src/Gui/propertyeditor/PropertyItem.cpp @@ -636,14 +636,14 @@ void PropertyItem::setPropertyValue(const std::string& value) Gui::Command::runCommand(Gui::Command::App, cmd.c_str()); } catch (Base::PyException& e) { - e.ReportException(); - Base::Console().Error("Stack Trace: %s\n", e.getStackTrace().c_str()); + e.reportException(); + Base::Console().error("Stack Trace: %s\n", e.getStackTrace().c_str()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { - Base::Console().Error("Unknown C++ exception in PropertyItem::setPropertyValue thrown\n"); + Base::Console().error("Unknown C++ exception in PropertyItem::setPropertyValue thrown\n"); } } @@ -811,7 +811,7 @@ QString PropertyItem::expressionAsString() const return QString::fromStdString(result->toString()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/LibraryVersions.h.cmake b/src/LibraryVersions.h.cmake index c2c9d39116..4d9057ac81 100644 --- a/src/LibraryVersions.h.cmake +++ b/src/LibraryVersions.h.cmake @@ -40,13 +40,13 @@ constexpr const char * fcPclVersion = "${PCL_VERSION}"; constexpr const char * fcPycxxVersion = "${PYCXX_VERSION}"; // PySide -constexpr const char * fcPysideVersion = "${PySide2_VERSION}"; +constexpr const char * fcPysideVersion = "${PySide_VERSION}"; // PyBind constexpr const char * fcPybind11Version = "${pybind11_VERSION}"; // Shiboken -constexpr const char * fcShibokenVersion = "${Shiboken2_VERSION}"; +constexpr const char * fcShibokenVersion = "${Shiboken_VERSION}"; // vtk constexpr const char * fcVtkVersion = "${VTK_VERSION}"; diff --git a/src/Main/FreeCADGuiPy.cpp b/src/Main/FreeCADGuiPy.cpp index f3a3dc70f8..39ecba36fb 100644 --- a/src/Main/FreeCADGuiPy.cpp +++ b/src/Main/FreeCADGuiPy.cpp @@ -155,7 +155,7 @@ static PyObject* FreeCADGui_showMainWindow(PyObject* /*self*/, PyObject* args) } // if successful then enable Console logger - Base::ILogger* console = Base::Console().Get("Console"); + Base::ILogger* console = Base::Console().get("Console"); if (console) { console->bMsg = true; console->bWrn = true; diff --git a/src/Main/MainCmd.cpp b/src/Main/MainCmd.cpp index 54430ff2c8..dfe29dd109 100644 --- a/src/Main/MainCmd.cpp +++ b/src/Main/MainCmd.cpp @@ -137,16 +137,16 @@ int main(int argc, char** argv) exit(e.getExitCode()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); exit(1); } catch (...) { - Console().Error("Application unexpectedly terminated\n"); + Console().error("Application unexpectedly terminated\n"); exit(1); } // Destruction phase =========================================================== - Console().Log("FreeCAD terminating...\n"); + Console().log("FreeCAD terminating...\n"); try { // close open documents @@ -158,7 +158,7 @@ int main(int argc, char** argv) // cleans up Application::destruct(); - Console().Log("FreeCAD completely terminated\n"); + Console().log("FreeCAD completely terminated\n"); return 0; } diff --git a/src/Main/MainGui.cpp b/src/Main/MainGui.cpp index 645e6df06e..02ff633e12 100644 --- a/src/Main/MainGui.cpp +++ b/src/Main/MainGui.cpp @@ -328,15 +328,15 @@ int main(int argc, char** argv) exit(e.getExitCode()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); exit(1); } catch (const std::exception& e) { - Base::Console().Error("Application unexpectedly terminated: %s\n", e.what()); + Base::Console().error("Application unexpectedly terminated: %s\n", e.what()); exit(1); } catch (...) { - Base::Console().Error("Application unexpectedly terminated\n"); + Base::Console().error("Application unexpectedly terminated\n"); exit(1); } @@ -345,12 +345,12 @@ int main(int argc, char** argv) std::cerr.rdbuf(oldcerr); // Destruction phase =========================================================== - Base::Console().Log("%s terminating...\n", App::Application::Config()["ExeName"].c_str()); + Base::Console().log("%s terminating...\n", App::Application::Config()["ExeName"].c_str()); // cleans up App::Application::destruct(); - Base::Console().Log("%s completely terminated\n", + Base::Console().log("%s completely terminated\n", App::Application::Config()["ExeName"].c_str()); return 0; @@ -383,14 +383,14 @@ public: , threadId(GetCurrentThreadId()) { std::string name = App::Application::Config()["UserAppData"] + "crash.log"; - Base::Console().AttachObserver(new Base::ConsoleObserverFile(name.c_str())); + Base::Console().attachObserver(new Base::ConsoleObserverFile(name.c_str())); } MyStackWalker(DWORD dwProcessId, HANDLE hProcess) : StackWalker(dwProcessId, hProcess) {} virtual void OnOutput(LPCSTR szText) { - Base::Console().Log("Id: %ld: %s", threadId, szText); + Base::Console().log("Id: %ld: %s", threadId, szText); // StackWalker::OnOutput(szText); } }; @@ -411,10 +411,10 @@ static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) #endif MyStackWalker sw; sw.ShowCallstack(GetCurrentThread(), pEx->ContextRecord); - Base::Console().Log("*** Unhandled Exception!\n"); - Base::Console().Log(" ExpCode: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionCode); - Base::Console().Log(" ExpFlags: %d\n", pEx->ExceptionRecord->ExceptionFlags); - Base::Console().Log(" ExpAddress: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionAddress); + Base::Console().log("*** Unhandled Exception!\n"); + Base::Console().log(" ExpCode: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionCode); + Base::Console().log(" ExpFlags: %d\n", pEx->ExceptionRecord->ExceptionFlags); + Base::Console().log(" ExpAddress: 0x%8.8X\n", pEx->ExceptionRecord->ExceptionAddress); bool bFailed = true; HANDLE hFile; diff --git a/src/Mod/Assembly/App/AppAssembly.cpp b/src/Mod/Assembly/App/AppAssembly.cpp index 578c592ca3..562221a891 100644 --- a/src/Mod/Assembly/App/AppAssembly.cpp +++ b/src/Mod/Assembly/App/AppAssembly.cpp @@ -55,7 +55,7 @@ PyMOD_INIT_FUNC(AssemblyApp) } PyObject* mod = Assembly::initModule(); - Base::Console().Log("Loading Assembly module... done\n"); + Base::Console().log("Loading Assembly module... done\n"); // NOTE: To finish the initialization of our own type objects we must diff --git a/src/Mod/Assembly/App/AssemblyObject.cpp b/src/Mod/Assembly/App/AssemblyObject.cpp index e38e46ab14..b7318f0938 100644 --- a/src/Mod/Assembly/App/AssemblyObject.cpp +++ b/src/Mod/Assembly/App/AssemblyObject.cpp @@ -197,7 +197,7 @@ int AssemblyObject::generateSimulation(App::DocumentObject* sim) mbdAssembly->runKINEMATIC(); } catch (...) { - Base::Console().Error("Generation of simulation failed\n"); + Base::Console().error("Generation of simulation failed\n"); motions.clear(); return -1; } @@ -367,7 +367,7 @@ bool AssemblyObject::validateNewPlacements() } if (!oldPlc.isSame(newPlacement)) { - Base::Console().Warning( + Base::Console().warning( "Assembly : Ignoring bad solve, a grounded object (%s) moved.\n", obj->getFullLabel()); return false; @@ -940,7 +940,7 @@ void AssemblyObject::removeUnconnectedJoints(std::vector& App::DocumentObject* obj2 = getMovingPartFromRef(this, joint, "Reference2"); if (!isObjInSetOfObjRefs(obj1, connectedParts) || !isObjInSetOfObjRefs(obj2, connectedParts)) { - Base::Console().Warning( + Base::Console().warning( "%s is unconnected to a grounded part so it is ignored.\n", joint->getFullName()); return true; // Remove joint if any connected object is not in connectedParts @@ -1550,7 +1550,7 @@ std::string AssemblyObject::handleOneSideOfJoint(App::DocumentObject* joint, App::DocumentObject* obj = getObjFromRef(joint, propRefName); if (!part || !obj) { - Base::Console().Warning("The property %s of Joint %s is bad.", + Base::Console().warning("The property %s of Joint %s is bad.", propRefName, joint->getFullName()); return ""; @@ -1614,7 +1614,7 @@ void AssemblyObject::getRackPinionMarkers(App::DocumentObject* joint, Base::Placement plc2 = getPlacementFromProp(joint, "Placement2"); if (!part1 || !obj1) { - Base::Console().Warning("Reference1 of Joint %s is bad.", joint->getFullName()); + Base::Console().warning("Reference1 of Joint %s is bad.", joint->getFullName()); return; } diff --git a/src/Mod/Assembly/App/BomObject.cpp b/src/Mod/Assembly/App/BomObject.cpp index 673a9bfbc6..3a63fd52e0 100644 --- a/src/Mod/Assembly/App/BomObject.cpp +++ b/src/Mod/Assembly/App/BomObject.cpp @@ -120,7 +120,7 @@ void BomObject::saveCustomColumnData() std::string columnName = getText(0, i); if (columnName != "Index" && columnName != "Name" && columnName != "Quantity" && columnName != "File Name") { - // Base::Console().Warning("row col %d %d\n", row, col); + // Base::Console().warning("row col %d %d\n", row, col); // save custom data if any. std::string text = getText(row, col); if (text != "") { @@ -268,7 +268,7 @@ std::string BomObject::getBomPropertyValue(App::DocumentObject* obj, const std:: App::Property* prop = obj->getPropertyByName(baseName.c_str()); if (!prop) { - Base::Console().Warning("Property not found: %s\n", baseName.c_str()); + Base::Console().warning("Property not found: %s\n", baseName.c_str()); return QObject::tr("N/A").toStdString(); } @@ -292,7 +292,7 @@ std::string BomObject::getBomPropertyValue(App::DocumentObject* obj, const std:: return propBool->getValue() ? "True" : "False"; } - Base::Console().Warning("Property type not supported for: %s\n", prop->getName()); + Base::Console().warning("Property type not supported for: %s\n", prop->getName()); return QObject::tr("Not supported").toStdString(); } diff --git a/src/Mod/Assembly/Gui/AppAssemblyGui.cpp b/src/Mod/Assembly/Gui/AppAssemblyGui.cpp index d24c4ab266..eb0e09c932 100644 --- a/src/Mod/Assembly/Gui/AppAssemblyGui.cpp +++ b/src/Mod/Assembly/Gui/AppAssemblyGui.cpp @@ -54,7 +54,7 @@ PyMOD_INIT_FUNC(AssemblyGui) } PyObject* mod = AssemblyGui::initModule(); - Base::Console().Log("Loading AssemblyGui module... done\n"); + Base::Console().log("Loading AssemblyGui module... done\n"); // NOTE: To finish the initialization of our own type objects we must diff --git a/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp b/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp index 1aa6b9f324..22ff0efa42 100644 --- a/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp +++ b/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp @@ -85,7 +85,7 @@ void printPlacement(Base::Placement plc, const char* name) double angle; Base::Rotation rot = plc.getRotation(); rot.getRawValue(axis, angle); - Base::Console().Warning( + Base::Console().warning( "placement %s : position (%.1f, %.1f, %.1f) - axis (%.1f, %.1f, %.1f) angle %.1f\n", name, pos.x, @@ -340,7 +340,7 @@ bool ViewProviderAssembly::mouseMove(const SbVec2s& cursorPos, Gui::View3DInvent return tryMouseMove(cursorPos, viewer); } catch (const Base::Exception& e) { - Base::Console().Warning("%s\n", e.what()); + Base::Console().warning("%s\n", e.what()); return false; } } @@ -822,7 +822,7 @@ void ViewProviderAssembly::initMove(const SbVec2s& cursorPos, Gui::View3DInvento tryInitMove(cursorPos, viewer); } catch (const Base::Exception& e) { - Base::Console().Warning("%s\n", e.what()); + Base::Console().warning("%s\n", e.what()); } } diff --git a/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp b/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp index 9802778efd..ad52a916db 100644 --- a/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp +++ b/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp @@ -76,7 +76,7 @@ bool ViewProviderAssemblyLink::setEdit(int mode) auto* assemblyLink = dynamic_cast(getObject()); if (!assemblyLink->isRigid() && mode == (int)ViewProvider::Transform) { - Base::Console().UserTranslatedNotification( + Base::Console().userTranslatedNotification( "Flexible sub-assemblies cannot be transformed."); return true; } @@ -106,7 +106,7 @@ bool ViewProviderAssemblyLink::onDelete(const std::vector& subNames { Q_UNUSED(subNames) - Base::Console().Warning("onDelete\n"); + Base::Console().warning("onDelete\n"); Gui::Command::doCommand(Gui::Command::Doc, "App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()", diff --git a/src/Mod/BIM/Arch.py b/src/Mod/BIM/Arch.py index bbd9263a28..c84908e43c 100644 --- a/src/Mod/BIM/Arch.py +++ b/src/Mod/BIM/Arch.py @@ -59,17 +59,30 @@ from ArchStructure import * # make functions -def makeAxis(num=1,size=1000,name=None): +def makeAxis(num=1, size=1000, name=None): + """ + Creates an axis set in the active document. - '''makeAxis([num],[size],[name]): makes an Axis set - based on the given number of axes and interval distances''' + Parameters + ---------- + num : int, optional + The number of axes to create. Defaults to 1. + size : float, optional + The interval distance between axes. Defaults to 1000. + name : str, optional + The name to assign to the created axis object. Defaults to None. + Returns + ------- + Part::FeaturePython + The created axis object. + """ import ArchAxis if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Axis") - obj.Label = name if name else translate("Arch","Axes") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Axis") + obj.Label = name if name else translate("Arch", "Axes") ArchAxis._Axis(obj) if FreeCAD.GuiUp: ArchAxis._ViewProviderAxis(obj.ViewObject) @@ -88,15 +101,27 @@ def makeAxis(num=1,size=1000,name=None): return obj -def makeAxisSystem(axes,name=None): +def makeAxisSystem(axes, name=None): + """ + Creates an axis system from the given list of axes. - '''makeAxisSystem(axes,[name]): makes a system from the given list of axes''' + Parameters + ---------- + axes : list of Part::FeaturePython + A list of axis objects to include in the axis system. + name : str, optional + The name to assign to the created axis system. Defaults to None. + Returns + ------- + App::FeaturePython + The created axis system object. + """ import ArchAxisSystem - if not isinstance(axes,list): + if not isinstance(axes, list): axes = [axes] - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","AxisSystem") - obj.Label = name if name else translate("Arch","Axis System") + obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "AxisSystem") + obj.Label = name if name else translate("Arch", "Axis System") ArchAxisSystem._AxisSystem(obj) obj.Axes = axes if FreeCAD.GuiUp: @@ -105,49 +130,90 @@ def makeAxisSystem(axes,name=None): return obj -def makeBuildingPart(objectslist=None,baseobj=None,name=None): +def makeBuildingPart(objectslist=None, baseobj=None, name=None): + """ + Creates a building part including the given objects in the list. - '''makeBuildingPart([objectslist],[name]): creates a buildingPart including the - objects from the given list.''' + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the building part. Defaults to None. + baseobj : Part::FeaturePython, optional + The base object for the building part. Defaults to None. + name : str, optional + The name to assign to the created building part. Defaults to None. + Returns + ------- + App::GeometryPython + The created building part object. + """ import ArchBuildingPart - obj = FreeCAD.ActiveDocument.addObject("App::GeometryPython","BuildingPart") + obj = FreeCAD.ActiveDocument.addObject("App::GeometryPython", "BuildingPart") #obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","BuildingPart") - obj.Label = name if name else translate("Arch","BuildingPart") + obj.Label = name if name else translate("Arch", "BuildingPart") ArchBuildingPart.BuildingPart(obj) obj.IfcType = "Building Element Part" if FreeCAD.GuiUp: ArchBuildingPart.ViewProviderBuildingPart(obj.ViewObject) if objectslist: - if isinstance(objectslist,(list,tuple)): + if isinstance(objectslist, (list, tuple)): obj.addObjects(objectslist) else: obj.addObject(objectslist) return obj -def makeFloor(objectslist=None,baseobj=None,name=None): +def makeFloor(objectslist=None, baseobj=None, name=None): + """ + Creates a floor/level in the active document. - """makes a BuildingPart and turns it into a Floor/Level""" + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the floor. Defaults to None. + baseobj : Part::FeaturePython, optional + The base object for the floor. Defaults to None. + name : str, optional + The name to assign to the created floor. Defaults to None. + Returns + ------- + App::GeometryPython + The created floor object. + """ obj = makeBuildingPart(objectslist) - obj.Label = name if name else translate("Arch","Level") + obj.Label = name if name else translate("Arch", "Level") obj.IfcType = "Building Storey" obj.CompositionType = "ELEMENT" return obj -def makeBuilding(objectslist=None,baseobj=None,name=None): +def makeBuilding(objectslist=None, baseobj=None, name=None): + """ + Creates a building in the active document. - """makes a BuildingPart and turns it into a Building""" + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the building. Defaults to None. + baseobj : Part::FeaturePython, optional + The base object for the building. Defaults to None. + name : str, optional + The name to assign to the created building. Defaults to None. + Returns + ------- + App::GeometryPython + The created building object. + """ import ArchBuildingPart obj = makeBuildingPart(objectslist) - obj.Label = name if name else translate("Arch","Building") + obj.Label = name if name else translate("Arch", "Building") obj.IfcType = "Building" obj.CompositionType = "ELEMENT" - t = QT_TRANSLATE_NOOP("App::Property","The type of this building") - obj.addProperty("App::PropertyEnumeration","BuildingType","Building",t, locked=True) + t = QT_TRANSLATE_NOOP("App::Property", "The type of this building") + obj.addProperty("App::PropertyEnumeration", "BuildingType", "Building", t, locked=True) obj.BuildingType = ArchBuildingPart.BuildingTypes if FreeCAD.GuiUp: obj.ViewObject.ShowLevel = False @@ -155,19 +221,33 @@ def makeBuilding(objectslist=None,baseobj=None,name=None): return obj -def make2DDrawing(objectslist=None,baseobj=None,name=None): +def make2DDrawing(objectslist=None, baseobj=None, name=None): + """ + Creates a 2D drawing view in the active document. - """makes a BuildingPart and turns it into a 2D drawing view""" + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the drawing. Defaults to None. + baseobj : Part::FeaturePython, optional + The base object for the drawing. Defaults to None. + name : str, optional + The name to assign to the created drawing. Defaults to None. + Returns + ------- + App::GeometryPython + The created 2D drawing object. + """ obj = makeBuildingPart(objectslist) - obj.Label = name if name else translate("Arch","Drawing") + obj.Label = name if name else translate("Arch", "Drawing") obj.IfcType = "Annotation" obj.ObjectType = "DRAWING" - obj.setEditorMode("Area",2) - obj.setEditorMode("Height",2) - obj.setEditorMode("LevelOffset",2) - obj.setEditorMode("OnlySolids",2) - obj.setEditorMode("HeightPropagate",2) + obj.setEditorMode("Area", 2) + obj.setEditorMode("Height", 2) + obj.setEditorMode("LevelOffset", 2) + obj.setEditorMode("OnlySolids", 2) + obj.setEditorMode("HeightPropagate", 2) if FreeCAD.GuiUp: obj.ViewObject.DisplayOffset = FreeCAD.Placement() obj.ViewObject.ShowLevel = False @@ -175,10 +255,19 @@ def make2DDrawing(objectslist=None,baseobj=None,name=None): def convertFloors(floor=None): + """ + Converts the given floor or building into building parts. - """convert the given Floor or Building (or all Arch Floors from the - active document if none is given) into BuildingParts""" + Parameters + ---------- + floor : Part::FeaturePython, optional + The floor or building to convert. If None, all Arch floors in the active document + are converted. Defaults to None. + Returns + ------- + None + """ import Draft import ArchBuildingPart todel = [] @@ -187,7 +276,7 @@ def convertFloors(floor=None): else: objset = FreeCAD.ActiveDocument.Objects for obj in objset: - if Draft.getType(obj) in ["Floor","Building"]: + if Draft.getType(obj) in ["Floor", "Building"]: nobj = makeBuildingPart(obj.Group) if Draft.getType(obj) == "Floor": nobj.IfcType = "Building Storey" @@ -195,12 +284,12 @@ def convertFloors(floor=None): else: nobj.IfcType = "Building" nobj.CompositionType = "ELEMENT" - t = QT_TRANSLATE_NOOP("App::Property","The type of this building") - nobj.addProperty("App::PropertyEnumeration","BuildingType","Building",t, locked=True) + t = QT_TRANSLATE_NOOP("App::Property", "The type of this building") + nobj.addProperty("App::PropertyEnumeration", "BuildingType", "Building", t, locked=True) nobj.BuildingType = ArchBuildingPart.BuildingTypes label = obj.Label for parent in obj.InList: - if hasattr(parent,"Group"): + if hasattr(parent, "Group"): if obj in parent.Group: parent.addObject(nobj) #g = parent.Group @@ -211,23 +300,35 @@ def convertFloors(floor=None): # some bug makes this trigger even efter the object has been deleted... obj.ViewObject.Proxy.Object = None # in case FreeCAD doesn't allow 2 objs with same label - obj.Label = obj.Label+" to delete" + obj.Label = obj.Label + " to delete" nobj.Label = label for n in todel: from draftutils import todo - todo.ToDo.delay(FreeCAD.ActiveDocument.removeObject,n) + todo.ToDo.delay(FreeCAD.ActiveDocument.removeObject, n) -def makeCurtainWall(baseobj=None,name=None): +def makeCurtainWall(baseobj=None, name=None): + """ + Creates a curtain wall object in the active document. - """makeCurtainWall([baseobj],[name]): Creates a curtain wall in the active document""" + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the curtain wall. Defaults to None. + name : str, optional + The name to assign to the created curtain wall. Defaults to None. + Returns + ------- + Part::FeaturePython + The created curtain wall object. + """ import ArchCurtainWall if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","CurtainWall") - obj.Label = name if name else translate("Arch","Curtain Wall") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "CurtainWall") + obj.Label = name if name else translate("Arch", "Curtain Wall") ArchCurtainWall.CurtainWall(obj) if FreeCAD.GuiUp: ArchCurtainWall.ViewProviderCurtainWall(obj.ViewObject) @@ -238,17 +339,30 @@ def makeCurtainWall(baseobj=None,name=None): return obj -def makeEquipment(baseobj=None,placement=None,name=None): +def makeEquipment(baseobj=None, placement=None, name=None): + """ + Creates an equipment object from the given base object in the active document. - """makeEquipment([baseobj],[placement],[name]): creates an equipment object - from the given base object.""" + Parameters + ---------- + baseobj : Part::FeaturePython or Mesh::Feature, optional + The base object for the equipment. Defaults to None. + placement : Placement, optional + The placement of the equipment. Defaults to None. + name : str, optional + The name to assign to the created equipment. Defaults to None. + Returns + ------- + Part::FeaturePython + The created equipment object. + """ import ArchEquipment if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Equipment") - obj.Label = name if name else translate("Arch","Equipment") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Equipment") + obj.Label = name if name else translate("Arch", "Equipment") ArchEquipment._Equipment(obj) if baseobj: if baseobj.isDerivedFrom("Mesh::Feature"): @@ -265,9 +379,23 @@ def makeEquipment(baseobj=None,placement=None,name=None): def makeFence(section, post, path): + """ + Creates a fence object in the active document. - """Makes a Fence object""" + Parameters + ---------- + section : Part::FeaturePython + The section profile of the fence. + post : Part::FeaturePython + The post profile of the fence. + path : Part::FeaturePython + The path along which the fence is created. + Returns + ------- + Part::FeaturePython + The created fence object. + """ import ArchFence obj = FreeCAD.ActiveDocument.addObject('Part::FeaturePython', 'Fence') ArchFence._Fence(obj) @@ -282,17 +410,30 @@ def makeFence(section, post, path): return obj -def makeFrame(baseobj,profile,name=None): +def makeFrame(baseobj, profile, name=None): + """Creates a frame object from a base sketch (or any other object containing wires) and a + profile object (an extrudable 2D object containing faces or closed wires). - """makeFrame(baseobj,profile,[name]): creates a frame object from a base sketch (or any other object - containing wires) and a profile object (an extrudable 2D object containing faces or closed wires)""" + Parameters + ---------- + baseobj : Part::FeaturePython + The base object containing wires to define the frame. + profile : Part::FeaturePython + The profile object, an extrudable 2D object containing faces or closed wires. + name : str, optional + The name to assign to the created frame. Defaults to None. + Returns + ------- + Part::FeaturePython + The created frame object. + """ import ArchFrame if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Frame") - obj.Label = name if name else translate("Arch","Frame") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Frame") + obj.Label = name if name else translate("Arch", "Frame") ArchFrame._Frame(obj) if FreeCAD.GuiUp: ArchFrame._ViewProviderFrame(obj.ViewObject) @@ -306,12 +447,22 @@ def makeFrame(baseobj,profile,name=None): def makeGrid(name=None): + """ + Creates a grid object in the active document. - '''makeGrid([name]): makes a grid object''' + Parameters + ---------- + name : str, optional + The name to assign to the created grid. Defaults to None. + Returns + ------- + Part::FeaturePython + The created grid object. + """ import ArchGrid - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Grid") - obj.Label = name if name else translate("Arch","Grid") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Grid") + obj.Label = name if name else translate("Arch", "Grid") ArchGrid.ArchGrid(obj) if FreeCAD.GuiUp: ArchGrid.ViewProviderArchGrid(obj.ViewObject) @@ -320,16 +471,30 @@ def makeGrid(name=None): return obj -def makeMaterial(name=None,color=None,transparency=None): +def makeMaterial(name=None, color=None, transparency=None): + """ + Creates a material object in the active document. - '''makeMaterial([name],[color],[transparency]): makes an Material object''' + Parameters + ---------- + name : str, optional + The name to assign to the created material. Defaults to None. + color : tuple of float, optional + The RGB color of the material. Defaults to None. + transparency : float, optional + The transparency level of the material. Defaults to None. + Returns + ------- + App::MaterialObjectPython + The created material object. + """ import ArchMaterial if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("App::MaterialObjectPython","Material") - obj.Label = name if name else translate("Arch","Material") + obj = FreeCAD.ActiveDocument.addObject("App::MaterialObjectPython", "Material") + obj.Label = name if name else translate("Arch", "Material") ArchMaterial._ArchMaterial(obj) if FreeCAD.GuiUp: ArchMaterial._ViewProviderArchMaterial(obj.ViewObject) @@ -337,19 +502,29 @@ def makeMaterial(name=None,color=None,transparency=None): if color: obj.Color = color[:3] if len(color) > 3: - obj.Transparency = color[3]*100 + obj.Transparency = color[3] * 100 if transparency: obj.Transparency = transparency return obj def makeMultiMaterial(name=None): + """ + Creates a multi-material object in the active document. - '''makeMultiMaterial([name]): makes an MultiMaterial object''' + Parameters + ---------- + name : str, optional + The name to assign to the created multi-material. Defaults to None. + Returns + ------- + App::FeaturePython + The created multi-material object. + """ import ArchMaterial - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","MultiMaterial") - obj.Label = name if name else translate("Arch","MultiMaterial") + obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "MultiMaterial") + obj.Label = name if name else translate("Arch", "MultiMaterial") ArchMaterial._ArchMultiMaterial(obj) if FreeCAD.GuiUp: ArchMaterial._ViewProviderArchMultiMaterial(obj.ViewObject) @@ -358,14 +533,19 @@ def makeMultiMaterial(name=None): def getMaterialContainer(): + """ + Returns a group object to store materials in the active document. - '''getMaterialContainer(): returns a group object to put materials in''' - + Returns + ------- + App::DocumentObjectGroupPython + The material container object. + """ import ArchMaterial for obj in FreeCAD.ActiveDocument.Objects: if obj.Name == "MaterialContainer": return obj - obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython","MaterialContainer") + obj = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroupPython", "MaterialContainer") obj.Label = "Materials" ArchMaterial._ArchMaterialContainer(obj) if FreeCAD.GuiUp: @@ -374,9 +554,14 @@ def getMaterialContainer(): def getDocumentMaterials(): + """ + Retrieves all material objects in the active document. - '''getDocumentMaterials(): returns all the arch materials of the document''' - + Returns + ------- + list of App::MaterialObjectPython + A list of all material objects in the document. + """ for obj in FreeCAD.ActiveDocument.Objects: if obj.Name == "MaterialContainer": mats = [] @@ -387,19 +572,38 @@ def getDocumentMaterials(): return [] -def makePanel(baseobj=None,length=0,width=0,thickness=0,placement=None,name=None): - - '''makePanel([baseobj],[length],[width],[thickness],[placement],[name]): creates a - panel element based on the given profile object and the given +def makePanel(baseobj=None, length=0, width=0, thickness=0, placement=None, name=None): + """ + Creates a panel element based on the given profile object and the given extrusion thickness. If no base object is given, you can also specify - length and width for a simple cubic object.''' + length and width for a simple cubic object. + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base profile object for the panel. Defaults to None. + length : float, optional + The length of the panel. Defaults to 0. + width : float, optional + The width of the panel. Defaults to 0. + thickness : float, optional + The thickness of the panel. Defaults to 0. + placement : Placement, optional + The placement of the panel. Defaults to None. + name : str, optional + The name to assign to the created panel. Defaults to None. + + Returns + ------- + Part::FeaturePython + The created panel object. + """ import ArchPanel if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Panel") - obj.Label = name if name else translate("Arch","Panel") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Panel") + obj.Label = name if name else translate("Arch", "Panel") ArchPanel._Panel(obj) if FreeCAD.GuiUp: ArchPanel._ViewProviderPanel(obj.ViewObject) @@ -416,14 +620,25 @@ def makePanel(baseobj=None,length=0,width=0,thickness=0,placement=None,name=None return obj -def makePanelCut(panel,name=None): +def makePanelCut(panel, name=None): + """ + Creates a 2D view of the given panel in the 3D space, positioned at the origin. - """makePanelCut(panel,[name]) : Creates a 2D view of the given panel - in the 3D space, positioned at the origin.""" + Parameters + ---------- + panel : Part::FeaturePython + The panel object to create a 2D view for. + name : str, optional + The name to assign to the created panel cut. Defaults to None. + Returns + ------- + Part::FeaturePython + The created panel cut object. + """ import ArchPanel - view = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","PanelCut") - view.Label = name if name else translate("Arch","View of")+" "+panel.Label + view = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "PanelCut") + view.Label = name if name else translate("Arch", "View of") + " " + panel.Label ArchPanel.PanelCut(view) view.Source = panel if FreeCAD.GuiUp: @@ -431,14 +646,25 @@ def makePanelCut(panel,name=None): return view -def makePanelSheet(panels=[],name=None): +def makePanelSheet(panels=[], name=None): + """ + Creates a sheet with the given panel cuts in the 3D space, positioned at the origin. - """makePanelSheet([panels],[name]) : Creates a sheet with the given panel cuts - in the 3D space, positioned at the origin.""" + Parameters + ---------- + panels : list of Part::FeaturePython, optional + A list of panel cuts to include in the sheet. Defaults to an empty list. + name : str, optional + The name to assign to the created panel sheet. Defaults to None. + Returns + ------- + Part::FeaturePython + The created panel sheet object. + """ import ArchPanel - sheet = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","PanelSheet") - sheet.Label = name if name else translate("Arch","PanelSheet") + sheet = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "PanelSheet") + sheet.Label = name if name else translate("Arch", "PanelSheet") ArchPanel.PanelSheet(sheet) if panels: sheet.Group = panels @@ -447,16 +673,34 @@ def makePanelSheet(panels=[],name=None): return sheet -def makePipe(baseobj=None,diameter=0,length=0,placement=None,name=None): +def makePipe(baseobj=None, diameter=0, length=0, placement=None, name=None): + """ + Creates a pipe object from the given base object or specified dimensions. - "makePipe([baseobj],[diameter],[length],[placement],[name]): creates an pipe object from the given base object" + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the pipe. Defaults to None. + diameter : float, optional + The diameter of the pipe. Defaults to 0. + length : float, optional + The length of the pipe. Defaults to 0. + placement : Placement, optional + The placement of the pipe. Defaults to None. + name : str, optional + The name to assign to the created pipe. Defaults to None. + Returns + ------- + Part::FeaturePython + The created pipe object. + """ import ArchPipe if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj= FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Pipe") - obj.Label = name if name else translate("Arch","Pipe") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Pipe") + obj.Label = name if name else translate("Arch", "Pipe") ArchPipe._ArchPipe(obj) if FreeCAD.GuiUp: ArchPipe._ViewProviderPipe(obj.ViewObject) @@ -480,16 +724,30 @@ def makePipe(baseobj=None,diameter=0,length=0,placement=None,name=None): return obj -def makePipeConnector(pipes,radius=0,name=None): +def makePipeConnector(pipes, radius=0, name=None): + """ + Creates a connector between the given pipes. - "makePipeConnector(pipes,[radius],[name]): creates a connector between the given pipes" + Parameters + ---------- + pipes : list of Part::FeaturePython + A list of pipe objects to connect. + radius : float, optional + The curvature radius of the connector. Defaults to 0, which uses the diameter of the first pipe. + name : str, optional + The name to assign to the created connector. Defaults to None. + Returns + ------- + Part::FeaturePython + The created pipe connector object. + """ import ArchPipe if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj= FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Connector") - obj.Label = name if name else translate("Arch","Connector") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Connector") + obj.Label = name if name else translate("Arch", "Connector") ArchPipe._ArchPipeConnector(obj) obj.Pipes = pipes if not radius: @@ -500,31 +758,41 @@ def makePipeConnector(pipes,radius=0,name=None): return obj -def makeProfile(profile=[0,'REC','REC100x100','R',100,100]): +def makeProfile(profile=[0, 'REC', 'REC100x100', 'R', 100, 100]): + """ + Creates a profile object based on the given profile data. - '''makeProfile(profile): returns a shape with the face defined by the profile data''' + Parameters + ---------- + profile : list, optional + A list defining the profile data. Defaults to [0, 'REC', 'REC100x100', 'R', 100, 100]. + Returns + ------- + Part::Part2DObjectPython + The created profile object. + """ import ArchProfile if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", "Profile") obj.Label = profile[2] + "_" - if profile[3]=="C": + if profile[3] == "C": ArchProfile._ProfileC(obj, profile) - elif profile[3]=="H": + elif profile[3] == "H": ArchProfile._ProfileH(obj, profile) - elif profile[3]=="R": + elif profile[3] == "R": ArchProfile._ProfileR(obj, profile) - elif profile[3]=="RH": + elif profile[3] == "RH": ArchProfile._ProfileRH(obj, profile) - elif profile[3]=="U": + elif profile[3] == "U": ArchProfile._ProfileU(obj, profile) - elif profile[3]=="L": + elif profile[3] == "L": ArchProfile._ProfileL(obj, profile) - elif profile[3]=="T": + elif profile[3] == "T": ArchProfile._ProfileT(obj, profile) - else : + else: print("Profile not supported") if FreeCAD.GuiUp: ArchProfile.ViewProviderProfile(obj.ViewObject) @@ -532,7 +800,6 @@ def makeProfile(profile=[0,'REC','REC100x100','R',100,100]): def makeProject(sites=None, name=None): - """Create an Arch project. If sites are provided, add them as children of the new project. @@ -550,9 +817,11 @@ def makeProject(sites=None, name=None): The created project. - WARNING: This object is obsoleted in favour of the NativeIFC project + Notes + ----- + This function is deprecated and will be removed in a future version. + The NativeIFC project is the new way to create IFC projects. """ - import ArchProject import Part if not FreeCAD.ActiveDocument: @@ -567,25 +836,43 @@ def makeProject(sites=None, name=None): return obj -def makeRebar(baseobj=None,sketch=None,diameter=None,amount=1,offset=None,name=None): +def makeRebar(baseobj=None, sketch=None, diameter=None, amount=1, offset=None, name=None): + """ + Creates a reinforcement bar object. - """makeRebar([baseobj],[sketch],[diameter],[amount],[offset],[name]): - adds a Reinforcement Bar object to the given structural object, - using the given sketch as profile.""" + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The structural object to host the rebar. Defaults to None. + sketch : Part::FeaturePython, optional + The sketch defining the rebar profile. Defaults to None. + diameter : float, optional + The diameter of the rebar. Defaults to None. + amount : int, optional + The number of rebars. Defaults to 1. + offset : float, optional + The offset distance for the rebar. Defaults to None. + name : str, optional + The name to assign to the created rebar. Defaults to None. + Returns + ------- + Part::FeaturePython + The created rebar object. + """ import ArchRebar if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Rebar") - obj.Label = name if name else translate("Arch","Rebar") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Rebar") + obj.Label = name if name else translate("Arch", "Rebar") ArchRebar._Rebar(obj) if FreeCAD.GuiUp: ArchRebar._ViewProviderRebar(obj.ViewObject) if baseobj and sketch: - if hasattr(sketch,"AttachmentSupport"): + if hasattr(sketch, "AttachmentSupport"): if sketch.AttachmentSupport: - if isinstance(sketch.AttachmentSupport,tuple): + if isinstance(sketch.AttachmentSupport, tuple): if sketch.AttachmentSupport[0] == baseobj: sketch.AttachmentSupport = None elif sketch.AttachmentSupport == baseobj: @@ -619,15 +906,29 @@ def makeRebar(baseobj=None,sketch=None,diameter=None,amount=1,offset=None,name=N def makeReference(filepath=None, partname=None, name=None): + """ + Creates an Arch reference object. - """makeReference([filepath],[partname],[name]): Creates an Arch Reference object""" + Parameters + ---------- + filepath : str, optional + The file path of the external reference. Defaults to None. + partname : str, optional + The name of the part in the external file. Defaults to None. + name : str, optional + The name to assign to the created reference. Defaults to None. + Returns + ------- + Part::FeaturePython + The created reference object. + """ import ArchReference if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","ArchReference") - obj.Label = name if name else translate("Arch","External Reference") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "ArchReference") + obj.Label = name if name else translate("Arch", "External Reference") ArchReference.ArchReference(obj) if FreeCAD.GuiUp: ArchReference.ViewProviderArchReference(obj.ViewObject) @@ -648,18 +949,39 @@ def makeRoof(baseobj=None, thickness=[50.0], overhang=[100.0], name=None): + """ + Creates a roof object based on a closed wire or an object. - '''makeRoof(baseobj, [facenr], [angle], [name]): Makes a roof based on - a closed wire or an object. + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the roof. Defaults to None. + facenr : int, optional + The face number to use as the base. Defaults to 0. + angles : list of float, optional + The angles for each edge of the roof. Defaults to [45.0]. + run : list of float, optional + The run distances for each edge. Defaults to [250.0]. + idrel : list of int, optional + The relative IDs for each edge. Defaults to [-1]. + thickness : list of float, optional + The thickness of the roof for each edge. Defaults to [50.0]. + overhang : list of float, optional + The overhang distances for each edge. Defaults to [100.0]. + name : str, optional + The name to assign to the created roof. Defaults to None. - You can provide a list of angles, run, idrel, thickness, overhang for - each edge in the wire to define the roof shape. The default for angle is - 45 and the list is automatically completed to match the number of edges - in the wire. - - If the base object is a solid the roof uses its shape. - ''' + Returns + ------- + Part::FeaturePython + The created roof object. + Notes + ----- + 1. If the base object is a solid the roof uses its shape. + 2. The angles, run, idrel, thickness, and overhang lists are automatically + completed to match the number of edges in the wire. + """ import ArchRoof import Part if not FreeCAD.ActiveDocument: @@ -679,7 +1001,7 @@ def makeRoof(baseobj=None, obj.Base.ViewObject.hide() else: if (obj.Base.Shape.Faces and obj.Face): - baseWire = obj.Base.Shape.Faces[obj.Face-1].Wires[0] + baseWire = obj.Base.Shape.Faces[obj.Face - 1].Wires[0] if FreeCAD.GuiUp: obj.Base.ViewObject.hide() elif obj.Base.Shape.Wires: @@ -702,32 +1024,50 @@ def makeRoof(baseobj=None, def makeSchedule(): - """makeSchedule(): Creates a schedule object in the active document""" + """ + Creates a schedule object in the active document. + Returns + ------- + App::FeaturePython + The created schedule object. + """ import ArchSchedule - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","Schedule") - obj.Label = translate("Arch","Schedule") + obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Schedule") + obj.Label = translate("Arch", "Schedule") ArchSchedule._ArchSchedule(obj) if FreeCAD.GuiUp: ArchSchedule._ViewProviderArchSchedule(obj.ViewObject) - if hasattr(obj,"CreateSpreadsheet") and obj.CreateSpreadsheet: + if hasattr(obj, "CreateSpreadsheet") and obj.CreateSpreadsheet: obj.Proxy.getSpreadSheet(obj, force=True) return obj -def makeSectionPlane(objectslist=None,name=None): +def makeSectionPlane(objectslist=None, name=None): + """ + Creates a section plane object including the given objects. - """makeSectionPlane([objectslist],[name]) : Creates a Section plane objects including the - given objects. If no object is given, the whole document will be considered.""" + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the section plane. If no object is given, the whole + document will be considered. Defaults to None. + name : str, optional + The name to assign to the created section plane. Defaults to None. + Returns + ------- + App::FeaturePython + The created section plane object. + """ import ArchSectionPlane import Draft import WorkingPlane if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython","Section") - obj.Label = name if name else translate("Arch","Section") + obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython", "Section") + obj.Label = name if name else translate("Arch", "Section") ArchSectionPlane._SectionPlane(obj) if FreeCAD.GuiUp: ArchSectionPlane._ViewProviderSectionPlane(obj.ViewObject) @@ -735,29 +1075,42 @@ def makeSectionPlane(objectslist=None,name=None): obj.Objects = objectslist bb = FreeCAD.BoundBox() for o in Draft.get_group_contents(objectslist): - if hasattr(o,"Shape") and hasattr(o.Shape,"BoundBox"): + if hasattr(o, "Shape") and hasattr(o.Shape, "BoundBox"): bb.add(o.Shape.BoundBox) obj.Placement = WorkingPlane.get_working_plane().get_placement() obj.Placement.Base = bb.Center if FreeCAD.GuiUp: - margin = bb.XLength*0.1 - obj.ViewObject.DisplayLength = bb.XLength+margin - obj.ViewObject.DisplayHeight = bb.YLength+margin + margin = bb.XLength * 0.1 + obj.ViewObject.DisplayLength = bb.XLength + margin + obj.ViewObject.DisplayHeight = bb.YLength + margin return obj -def makeSite(objectslist=None,baseobj=None,name=None): +def makeSite(objectslist=None, baseobj=None, name=None): + """ + Creates a site object including the given objects. - '''makeBuilding([objectslist],[baseobj],[name]): creates a site including the - objects from the given list.''' + Parameters + ---------- + objectslist : list of Part::FeaturePython, optional + A list of objects to include in the site. Defaults to None. + baseobj : Part::FeaturePython, optional + The base object for the site. Defaults to None. + name : str, optional + The name to assign to the created site. Defaults to None. + Returns + ------- + Part::FeaturePython + The created site object. + """ import ArchSite if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return import Part - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Site") - obj.Label = name if name else translate("Arch","Site") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Site") + obj.Label = name if name else translate("Arch", "Site") ArchSite._Site(obj) if FreeCAD.GuiUp: ArchSite._ViewProviderSite(obj.ViewObject) @@ -765,14 +1118,14 @@ def makeSite(objectslist=None,baseobj=None,name=None): obj.Group = objectslist if baseobj: import Part - if isinstance(baseobj,Part.Shape): + if isinstance(baseobj, Part.Shape): obj.Shape = baseobj else: obj.Terrain = baseobj return obj -def makeSpace(objects=None,baseobj=None,name=None): +def makeSpace(objects=None, baseobj=None, name=None): """Creates a space object from the given objects. Parameters @@ -788,25 +1141,27 @@ def makeSpace(objects=None,baseobj=None,name=None): The user-facing name to assign to the space object's label. By default None, in which case the label is set to "Space". + Returns + ------- + Part::FeaturePython + The created space object. + Notes ----- The objects parameter can be passed using either of these different formats: 1. Single object (e.g. a Part::Feature document object). Will be used as the space's base - shape. - :: + shape.:: objects = 2. List of selection objects, as provided by ``Gui.Selection.getSelectionEx()``. This requires the GUI to be active. The `SubObjects` property of each selection object in the list defines the space's boundaries. If the list contains a single selection object without subobjects, or with only one subobject, the object in its ``Object`` property is used as - the base shape. - :: + the base shape.:: objects = [, ...] 3. A list of tuples that can be assigned to an ``App::PropertyLinkSubList`` property. Each - tuple contains a document object and a nested tuple of subobjects that define boundaries. If + tuple contains a document object and a nested tuple of subobjects that define the boundaries. If the list contains a single tuple without a nested subobjects tuple, or a subobjects tuple - with only one subobject, the object in the tuple is used as the base shape. - :: + with only one subobject, the object in the tuple is used as the base shape.:: objects = [(obj1, ("Face1")), (obj2, ("Face1")), ...] objects = [(obj, ("Face1", "Face2", "Face3", "Face4"))] """ @@ -814,15 +1169,15 @@ def makeSpace(objects=None,baseobj=None,name=None): if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - space = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Space") - space.Label = name if name else translate("Arch","Space") + space = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Space") + space.Label = name if name else translate("Arch", "Space") ArchSpace._Space(space) if FreeCAD.GuiUp: ArchSpace._ViewProviderSpace(space.ViewObject) if baseobj: objects = baseobj if objects: - if not isinstance(objects,list): + if not isinstance(objects, list): objects = [objects] isSingleObject = lambda objs: len(objs) == 1 @@ -861,7 +1216,7 @@ def makeSpace(objects=None,baseobj=None,name=None): space.Proxy.addSubobjects(space, boundaries) return space -def addSpaceBoundaries(space,subobjects): +def addSpaceBoundaries(space, subobjects): """Adds the given subobjects as defining boundaries of the given space. Parameters @@ -876,21 +1231,19 @@ def addSpaceBoundaries(space,subobjects): The subobjects parameter can be passed using either of these different formats: 1. List of selection objects, as provided by ``Gui.Selection.getSelectionEx()``. This requires the GUI to be active. The `SubObjects` property of each selection object in the - list defines the boundaries to add to the space. - :: + list defines the boundaries to add to the space.:: subobjects = [, ...] 2. A list of tuples that can be assigned to an ``App::PropertyLinkSubList`` property. Each tuple contains a document object and a nested tuple of subobjects that define the boundaries - to add. - :: + to add.:: subobjects = [(obj1, ("Face1")), (obj2, ("Face1")), ...] subobjects = [(obj, ("Face1", "Face2", "Face3", "Face4"))] """ import Draft if Draft.getType(space) == "Space": - space.Proxy.addSubobjects(space,subobjects) + space.Proxy.addSubobjects(space, subobjects) -def removeSpaceBoundaries(space,subobjects): +def removeSpaceBoundaries(space, subobjects): """Remove the given subobjects as defining boundaries of the given space. Parameters @@ -905,25 +1258,42 @@ def removeSpaceBoundaries(space,subobjects): The subobjects parameter can be passed using either of these different formats: 1. List of selection objects, as provided by ``Gui.Selection.getSelectionEx()``. This requires the GUI to be active. The `SubObjects` property of each selection object in the - list defines the boundaries to remove from the space. - :: + list defines the boundaries to remove from the space.:: subobjects = [, ...] 2. A list of tuples that can be assigned to an ``App::PropertyLinkSubList`` property. Each tuple contains a document object and a nested tuple of subobjects that define the boundaries - to remove. - :: + to remove.:: subobjects = [(obj1, ("Face1")), (obj2, ("Face1")), ...] subobjects = [(obj, ("Face1", "Face2", "Face3", "Face4"))] """ import Draft if Draft.getType(space) == "Space": - space.Proxy.removeSubobjects(space,subobjects) + space.Proxy.removeSubobjects(space, subobjects) -def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=None): +def makeStairs(baseobj=None, length=None, width=None, height=None, steps=None, name=None): + """ + Creates a stairs object with the given attributes. - """makeStairs([baseobj],[length],[width],[height],[steps],[name]): creates a Stairs - objects with given attributes.""" + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the stairs. Defaults to None. + length : float, optional + The length of the stairs. Defaults to None. + width : float, optional + The width of the stairs. Defaults to None. + height : float, optional + The height of the stairs. Defaults to None. + steps : int, optional + The number of steps. Defaults to None. + name : str, optional + The name to assign to the created stairs. Defaults to None. + Returns + ------- + Part::FeaturePython + The created stairs object. + """ import ArchStairs if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") @@ -931,9 +1301,9 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N stairs = [] additions = [] - label = name if name else translate("Arch","Stairs") + label = name if name else translate("Arch", "Stairs") - def setProperty(obj,length,width,height,steps): + def setProperty(obj, length, width, height, steps): """setProperty(obj,length,width,height,steps): sets up the basic properties for this stair""" if length: obj.Length = length @@ -960,11 +1330,11 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N obj.RailingHeightRight = 900 if baseobj: - if not isinstance(baseobj,list): + if not isinstance(baseobj, list): baseobj = [baseobj] lenSelection = len(baseobj) if lenSelection > 1: - stair = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Stairs") + stair = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Stairs") stair.Label = label ArchStairs._Stairs(stair) stairs.append(stair) @@ -972,7 +1342,7 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N else: i = 0 for baseobjI in baseobj: - stair = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Stairs") + stair = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Stairs") stair.Label = label ArchStairs._Stairs(stair) stairs.append(stair) @@ -981,10 +1351,10 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N stepsI = steps else: stepsI = 20 - setProperty(stairs[i],None,width,height,stepsI) + setProperty(stairs[i], None, width, height, stepsI) if i > 1: additions.append(stairs[i]) - stairs[i].LastSegment = stairs[i-1] + stairs[i].LastSegment = stairs[i - 1] else: if len(stairs) > 1: # i.e. length >1, have a 'master' staircase created stairs[0].Base = stairs[1] @@ -992,10 +1362,10 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N if lenSelection > 1: stairs[0].Additions = additions else: - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Stairs") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Stairs") obj.Label = label ArchStairs._Stairs(obj) - setProperty(obj,length,width,height,steps) + setProperty(obj, length, width, height, steps) stairs.append(obj) if FreeCAD.GuiUp: if baseobj: @@ -1015,12 +1385,21 @@ def makeStairs(baseobj=None,length=None,width=None,height=None,steps=None,name=N def makeRailing(stairs): + """ + Creates railings for the given stairs. - "simple make Railing function" + Parameters + ---------- + stairs : list of Part::FeaturePython + The stairs objects to add railings to. + Returns + ------- + None + """ import ArchPipe - def makeRailingLorR(stairs,side="L"): + def makeRailingLorR(stairs, side="L"): """makeRailingLorR(stairs,side="L"): Creates a railing on the given side of the stairs, L or R""" for stair in reversed(stairs): if side == "L": @@ -1032,7 +1411,7 @@ def makeRailing(stairs): outlineLRAll = stair.OutlineRightAll stairRailingLR = "RailingRight" if outlineLR or outlineLRAll: - lrRail = makePipe(baseobj=None,diameter=0,length=0,placement=None,name=translate("Arch","Railing")) + lrRail = makePipe(baseobj=None, diameter=0, length=0, placement=None, name=translate("Arch", "Railing")) if outlineLRAll: setattr(stair, stairRailingLR, lrRail) break @@ -1058,22 +1437,32 @@ def makeRailing(stairs): print("No Stairs object selected") return - makeRailingLorR(stairs,"L") - makeRailingLorR(stairs,"R") + makeRailingLorR(stairs, "L") + makeRailingLorR(stairs, "R") -def makeTruss(baseobj=None,name=None): - - """ - makeTruss([baseobj],[name]): Creates a space object from the given object (a line) +def makeTruss(baseobj=None, name=None): """ + Creates a truss object from the given base object. + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the truss. Defaults to None. + name : str, optional + The name to assign to the created truss. Defaults to None. + + Returns + ------- + Part::FeaturePython + The created truss object. + """ import ArchTruss if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Truss") - obj.Label = name if name else translate("Arch","Truss") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Truss") + obj.Label = name if name else translate("Arch", "Truss") ArchTruss.Truss(obj) if FreeCAD.GuiUp: ArchTruss.ViewProviderTruss(obj.ViewObject) @@ -1117,34 +1506,31 @@ def makeWall(baseobj=None,height=None,length=None,width=None,align=None,offset=N Notes ----- - Creates a new object, and turns it into a parametric wall - object. This object does not yet have any shape. - - The wall then uses the baseobj.Shape as the basis to extrude out a wall shape, - giving the new object a shape. - - It then hides the original baseobj. + 1. Creates a new object, and turns it into a parametric wall + object. This object does not yet have any shape. + 2. The wall then uses the baseobj.Shape as the basis to extrude out a wall shape, + giving the new object a shape. + 3. It then hides the original baseobj. """ - import ArchWall import Draft from draftutils import params if not FreeCAD.ActiveDocument: FreeCAD.Console.PrintError("No active document. Aborting\n") return - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Wall") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Wall") if name: obj.Label = name else: - obj.Label = translate("Arch","Wall") + obj.Label = translate("Arch", "Wall") ArchWall._Wall(obj) if FreeCAD.GuiUp: ArchWall._ViewProviderWall(obj.ViewObject) if baseobj: - if hasattr(baseobj,'Shape') or baseobj.isDerivedFrom("Mesh::Feature"): + if hasattr(baseobj, 'Shape') or baseobj.isDerivedFrom("Mesh::Feature"): obj.Base = baseobj else: - FreeCAD.Console.PrintWarning(str(translate("Arch","Walls can only be based on Part or Mesh objects"))) + FreeCAD.Console.PrintWarning(str(translate("Arch", "Walls can only be based on Part or Mesh objects"))) if face: obj.Face = face if length: @@ -1164,14 +1550,14 @@ def makeWall(baseobj=None,height=None,length=None,width=None,align=None,offset=N if align: obj.Align = align else: - obj.Align = ["Center","Left","Right"][params.get_param_arch("WallAlignment")] + obj.Align = ["Center", "Left", "Right"][params.get_param_arch("WallAlignment")] if obj.Base and FreeCAD.GuiUp: if Draft.getType(obj.Base) != "Space": obj.Base.ViewObject.hide() return obj -def joinWalls(walls,delete=False): +def joinWalls(walls, delete=False): """Join the given list of walls into one sketch-based wall. Take the first wall in the list, and adds on the other walls in the list. @@ -1182,23 +1568,23 @@ def joinWalls(walls,delete=False): Parameters ---------- - walls: list of + walls : list of List containing the walls to add to the first wall in the list. Walls must be based off a base object. - delete: bool, optional - If True, deletes the other walls in the list. + delete : bool, optional + If True, deletes the other walls in the list. Defaults to False. Returns ------- - + Part::FeaturePython + The joined wall object. """ - import Part import Draft import ArchWall if not walls: return None - if not isinstance(walls,list): + if not isinstance(walls, list): walls = [walls] if not ArchWall.areSameWallTypes(walls): return None @@ -1213,14 +1599,14 @@ def joinWalls(walls,delete=False): else: try: import ArchSketchObject - newSk=ArchSketchObject.makeArchSketch() + newSk = ArchSketchObject.makeArchSketch() except: if Draft.getType(base.Base) != "Sketcher::SketchObject": - newSk=FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject","WallTrace") + newSk = FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject", "WallTrace") else: - newSk=None + newSk = None if newSk: - sk = Draft.makeSketch(base.Base,autoconstraints=True, addTo=newSk) + sk = Draft.makeSketch(base.Base, autoconstraints=True, addTo=newSk) base.Base = sk else: sk = base.Base @@ -1229,8 +1615,8 @@ def joinWalls(walls,delete=False): if not w.Base.Shape.Faces: for e in w.Base.Shape.Edges: l = e.Curve - if isinstance(l,Part.Line): - l = Part.LineSegment(e.Vertexes[0].Point,e.Vertexes[-1].Point) + if isinstance(l, Part.Line): + l = Part.LineSegment(e.Vertexes[0].Point, e.Vertexes[-1].Point) sk.addGeometry(l) deleteList.append(w.Name) if delete: @@ -1241,11 +1627,28 @@ def joinWalls(walls,delete=False): return base -def makeWindow(baseobj=None,width=None,height=None,parts=None,name=None): +def makeWindow(baseobj=None, width=None, height=None, parts=None, name=None): + """ + Creates a window object based on the given base object. - '''makeWindow(baseobj,[width,height,parts,name]): creates a window based on the - given base 2D object (sketch or draft).''' + Parameters + ---------- + baseobj : Part::FeaturePython, optional + The base object for the window. Defaults to None. + width : float, optional + The width of the window. Defaults to None. + height : float, optional + The height of the window. Defaults to None. + parts : list, optional + The parts of the window. Defaults to None. + name : str, optional + The name to assign to the created window. Defaults to None. + Returns + ------- + Part::FeaturePython + The created window object. + """ import ArchWindow import Draft from draftutils import todo @@ -1256,12 +1659,12 @@ def makeWindow(baseobj=None,width=None,height=None,parts=None,name=None): if Draft.getType(baseobj) == "Window": obj = Draft.clone(baseobj) return obj - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Window") + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Window") ArchWindow._Window(obj) if name: obj.Label = name else: - obj.Label = translate("Arch","Window") + obj.Label = translate("Arch", "Window") if FreeCAD.GuiUp: ArchWindow._ViewProviderWindow(obj.ViewObject) if width: @@ -1269,7 +1672,7 @@ def makeWindow(baseobj=None,width=None,height=None,parts=None,name=None): if height: obj.Height = height if baseobj: - obj.Normal = baseobj.Placement.Rotation.multVec(FreeCAD.Vector(0,0,-1)) + obj.Normal = baseobj.Placement.Rotation.multVec(FreeCAD.Vector(0, 0, -1)) obj.Base = baseobj if parts is not None: obj.WindowParts = parts @@ -1288,16 +1691,16 @@ def makeWindow(baseobj=None,width=None,height=None,parts=None,name=None): if ws: ws += "," ws += "Wire" + str(i) i += 1 - obj.WindowParts = ["Default",tp,ws,"1","0"] + obj.WindowParts = ["Default", tp, ws, "1", "0"] else: # bind properties from base obj if existing - for prop in ["Height","Width","Subvolume","Tag","Description","Material"]: + for prop in ["Height", "Width", "Subvolume", "Tag", "Description", "Material"]: for p in baseobj.PropertiesList: - if (p == prop) or p.endswith("_"+prop): - obj.setExpression(prop, baseobj.Name+"."+p) + if (p == prop) or p.endswith("_" + prop): + obj.setExpression(prop, baseobj.Name + "." + p) if obj.Base and FreeCAD.GuiUp: obj.Base.ViewObject.DisplayMode = "Wireframe" obj.Base.ViewObject.hide() - todo.ToDo.delay(ArchWindow.recolorize,[obj.Document.Name,obj.Name]) + todo.ToDo.delay(ArchWindow.recolorize, [obj.Document.Name, obj.Name]) return obj diff --git a/src/Mod/BIM/ArchPipe.py b/src/Mod/BIM/ArchPipe.py index 3053a67519..067203e094 100644 --- a/src/Mod/BIM/ArchPipe.py +++ b/src/Mod/BIM/ArchPipe.py @@ -122,8 +122,6 @@ class _ArchPipe(ArchComponent.Component): import DraftGeomUtils if self.clone(obj): return - if not self.ensureBase(obj): - return pl = obj.Placement w = self.getWire(obj) if not w: diff --git a/src/Mod/BIM/ArchRoof.py b/src/Mod/BIM/ArchRoof.py index 8cc968f23c..3594119932 100644 --- a/src/Mod/BIM/ArchRoof.py +++ b/src/Mod/BIM/ArchRoof.py @@ -42,6 +42,7 @@ import DraftGeomUtils import DraftVecUtils import Part +from FreeCAD import Units from FreeCAD import Vector if FreeCAD.GuiUp: @@ -885,11 +886,11 @@ class _RoofTaskPanel: self.tree.setRootIsDecorated(False) # remove 1st column's extra left margin self.tree.setColumnCount(7) self.tree.header().resizeSection(0, 37) # 37px seems to be the minimum size - self.tree.header().resizeSection(1, 70) - self.tree.header().resizeSection(2, 62) + self.tree.header().resizeSection(1, 60) + self.tree.header().resizeSection(2, 70) self.tree.header().resizeSection(3, 37) - self.tree.header().resizeSection(4, 60) - self.tree.header().resizeSection(5, 60) + self.tree.header().resizeSection(4, 70) + self.tree.header().resizeSection(5, 70) self.tree.header().resizeSection(6, 70) QtCore.QObject.connect(self.tree, QtCore.SIGNAL("itemChanged(QTreeWidgetItem *, int)"), self.edit) @@ -915,41 +916,48 @@ class _RoofTaskPanel: for i in range(len(self.obj.Angles)): item = root.child(i) item.setText(0, str(i)) - item.setText(1, str(self.obj.Angles[i])) - item.setText(2, str(self.obj.Runs[i])) + item.setText(1, Units.Quantity(self.obj.Angles[i], Units.Angle).UserString) + item.setText(2, Units.Quantity(self.obj.Runs[i], Units.Length).UserString) item.setText(3, str(self.obj.IdRel[i])) - item.setText(4, str(self.obj.Thickness[i])) - item.setText(5, str(self.obj.Overhang[i])) - item.setText(6, str(self.obj.Heights[i])) + item.setText(4, Units.Quantity(self.obj.Thickness[i], Units.Length).UserString) + item.setText(5, Units.Quantity(self.obj.Overhang[i], Units.Length).UserString) + item.setText(6, Units.Quantity(self.obj.Heights[i], Units.Length).UserString) item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable) # treeHgt = 1 + 23 + (len(self.obj.Angles) * 17) + 1 # 1px borders, 23px header, 17px rows # self.tree.setMinimumSize(QtCore.QSize(445, treeHgt)) self.retranslateUi(self.form) self.updating = False - def edit(self, item, column): - if not self.updating: - self.resetObject() + def _update_value(self, row, prop, str_val): + # Workaround for Building US unit system bug (Version 1.1, 2025): + str_val = str_val.replace("+", "--") + val_list = getattr(self.obj, prop) + val_list[row] = Units.Quantity(str_val).Value + setattr(self.obj, prop, val_list) - def resetObject(self, remove=None): - '''transfers the values from the widget to the object''' - ang = [] - run = [] - rel = [] - thick = [] - over = [] - root = self.tree.invisibleRootItem() - for it in root.takeChildren(): - ang.append(float(it.text(1))) - run.append(float(it.text(2))) - rel.append(int(it.text(3))) - thick.append(float(it.text(4))) - over.append(float(it.text(5))) - self.obj.Runs = run - self.obj.Angles = ang - self.obj.IdRel = rel - self.obj.Thickness = thick - self.obj.Overhang = over + def edit(self, item, column): + '''transfers an edited value from the widget to the object''' + if self.updating: + return + row = int(item.text(0)) + if not (0 <= row < len(self.obj.Angles)): + # Users should not change the Id (index) column, but you never know: + return + match column: + case 1: + self._update_value(row, "Angles", item.text(1)) + case 2: + self._update_value(row, "Runs", item.text(2)) + case 3: + val_list = self.obj.IdRel + val_list[row] = int(item.text(3)) + self.obj.IdRel = val_list + case 4: + self._update_value(row, "Thickness", item.text(4)) + case 5: + self._update_value(row, "Overhang", item.text(5)) + case _: + return self.obj.touch() FreeCAD.ActiveDocument.recompute() self.update() @@ -963,9 +971,9 @@ class _RoofTaskPanel: TaskPanel.setWindowTitle(QtGui.QApplication.translate("Arch", "Roof", None)) self.title.setText(QtGui.QApplication.translate("Arch", "Parameters of the roof profiles :\n* Angle : slope in degrees relative to the horizontal.\n* Run : horizontal distance between the wall and the ridge.\n* Thickness : thickness of the roof.\n* Overhang : horizontal distance between the eave and the wall.\n* Height : height of the ridge above the base (calculated automatically).\n* IdRel : Id of the relative profile used for automatic calculations.\n---\nIf Angle = 0 and Run = 0 then the profile is identical to the relative profile.\nIf Angle = 0 then the angle is calculated so that the height is the same as the relative profile.\nIf Run = 0 then the run is calculated so that the height is the same as the relative profile.", None)) self.tree.setHeaderLabels([QtGui.QApplication.translate("Arch", "Id", None), - QtGui.QApplication.translate("Arch", "Angle (deg)", None), - QtGui.QApplication.translate("Arch", "Run (mm)", None), + QtGui.QApplication.translate("Arch", "Angle", None), + QtGui.QApplication.translate("Arch", "Run", None), QtGui.QApplication.translate("Arch", "IdRel", None), - QtGui.QApplication.translate("Arch", "Thickness (mm)", None), - QtGui.QApplication.translate("Arch", "Overhang (mm)", None), - QtGui.QApplication.translate("Arch", "Height (mm)", None)]) + QtGui.QApplication.translate("Arch", "Thickness", None), + QtGui.QApplication.translate("Arch", "Overhang", None), + QtGui.QApplication.translate("Arch", "Height", None)]) diff --git a/src/Mod/BIM/ArchSite.py b/src/Mod/BIM/ArchSite.py index 3adfad24fb..2fdf971929 100644 --- a/src/Mod/BIM/ArchSite.py +++ b/src/Mod/BIM/ArchSite.py @@ -1069,7 +1069,7 @@ class _ViewProviderSite: self.windroseswitch.whichChild = -1 elif prop == 'Visibility': if vobj.Visibility: - self.updateCompassVisibility(self.Object) + self.updateCompassVisibility(vobj) else: self.compass.hide() elif prop == 'Orientation': diff --git a/src/Mod/BIM/ArchStructure.py b/src/Mod/BIM/ArchStructure.py index 51ff60dc9e..49d1c95c00 100644 --- a/src/Mod/BIM/ArchStructure.py +++ b/src/Mod/BIM/ArchStructure.py @@ -287,6 +287,7 @@ class _CommandStructure: def Activated(self): + self.doc = FreeCAD.ActiveDocument self.Width = params.get_param_arch("StructureWidth") if self.beammode: self.Height = params.get_param_arch("StructureLength") @@ -307,20 +308,21 @@ class _CommandStructure: FreeCADGui.runCommand("Arch_StructuralSystem") return elif not(ax) and not(st): - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Structure")) + self.doc.openTransaction(translate("Arch","Create Structure")) FreeCADGui.addModule("Arch") for obj in sel: FreeCADGui.doCommand("obj = Arch.makeStructure(FreeCAD.ActiveDocument." + obj.Name + ")") FreeCADGui.addModule("Draft") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() return # interactive mode import WorkingPlane - self.wp = WorkingPlane.get_working_plane() + FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off + self.wp = WorkingPlane.get_working_plane() self.points = [] self.tracker = DraftTrackers.boxTracker() self.tracker.width(self.Width) @@ -335,7 +337,6 @@ class _CommandStructure: title=translate("Arch","First point of the beam")+":" else: title=translate("Arch","Base point of column")+":" - FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off FreeCADGui.Snapper.getPoint(callback=self.getPoint,movecallback=self.update,extradlg=[self.taskbox(),self.precast.form,self.dents.form],title=title) FreeCADGui.draftToolBar.continueCmd.show() @@ -345,19 +346,19 @@ class _CommandStructure: self.bmode = self.modeb.isChecked() if point is None: - self.tracker.finalize() FreeCAD.activeDraftCommand = None FreeCADGui.Snapper.off() + self.tracker.finalize() return if self.bmode and (self.bpoint is None): self.bpoint = point FreeCADGui.Snapper.getPoint(last=point,callback=self.getPoint,movecallback=self.update,extradlg=[self.taskbox(),self.precast.form,self.dents.form],title=translate("Arch","Next point")+":",mode="line") return - self.tracker.off() FreeCAD.activeDraftCommand = None FreeCADGui.Snapper.off() + self.tracker.off() horiz = True # determines the type of rotation to apply to the final object - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Structure")) + self.doc.openTransaction(translate("Arch","Create Structure")) FreeCADGui.addModule("Arch") FreeCADGui.addModule("WorkingPlane") if self.bmode: @@ -419,8 +420,8 @@ class _CommandStructure: FreeCADGui.addModule("Draft") FreeCADGui.doCommand("Draft.autogroup(s)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() # gui_utils.end_all_events() # Causes a crash on Linux. self.tracker.finalize() if FreeCADGui.draftToolBar.continueCmd.isChecked(): diff --git a/src/Mod/BIM/BimSelect.py b/src/Mod/BIM/BimSelect.py index b5eb56ad90..2ad4efa33b 100644 --- a/src/Mod/BIM/BimSelect.py +++ b/src/Mod/BIM/BimSelect.py @@ -1,3 +1,27 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * * +# * Copyright (c) 2024 Yorik van Havre * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + import FreeCAD diff --git a/src/Mod/BIM/Dice3DS/dom3ds.py b/src/Mod/BIM/Dice3DS/dom3ds.py index 0ea31e27ee..278dcd4888 100644 --- a/src/Mod/BIM/Dice3DS/dom3ds.py +++ b/src/Mod/BIM/Dice3DS/dom3ds.py @@ -1,5 +1,3 @@ -# dom3ds.py - """Slice and dice 3DS files. Provides for reading, writing, and manipulating 3DS files. It's diff --git a/src/Mod/BIM/Dice3DS/util.py b/src/Mod/BIM/Dice3DS/util.py index b623c73c67..12ec8d2616 100644 --- a/src/Mod/BIM/Dice3DS/util.py +++ b/src/Mod/BIM/Dice3DS/util.py @@ -1,5 +1,3 @@ -# util.py - """Utitily function for Dice3DS. Defines some routines for calculating normals and transforming points. diff --git a/src/Mod/BIM/InitGui.py b/src/Mod/BIM/InitGui.py index 2c1386fe8d..084bffd9dc 100644 --- a/src/Mod/BIM/InitGui.py +++ b/src/Mod/BIM/InitGui.py @@ -103,13 +103,16 @@ class BIMWorkbench(Workbench): "Arch_AxisSystem", "Arch_Grid", "Arch_SectionPlane", - "BIM_DrawingView", - "BIM_Shape2DView", - "BIM_Shape2DCut", "BIM_TDPage", "BIM_TDView", ] + self.create_2dviews = [ + "BIM_DrawingView", + "BIM_Shape2DView", + "BIM_Shape2DCut", + ] + self.bimtools = [ "BIM_Project", "Arch_Site", @@ -255,7 +258,6 @@ class BIMWorkbench(Workbench): ] # create generic tools command - class BIM_GenericTools: def __init__(self, tools): self.tools = tools @@ -270,6 +272,22 @@ class BIMWorkbench(Workbench): FreeCADGui.addCommand("BIM_GenericTools", BIM_GenericTools(self.generictools)) self.bimtools.append("BIM_GenericTools") + # create create 2D views command + class BIM_Create2DViews: + def __init__(self, tools): + self.tools = tools + def GetCommands(self): + return self.tools + def GetResources(self): + t = QT_TRANSLATE_NOOP("BIM_Create2DViews", "Create 2D views") + return { "MenuText": t, "ToolTip": t, "Icon": "BIM_DrawingView"} + def IsActive(self): + v = hasattr(FreeCADGui.getMainWindow().getActiveWindow(), "getSceneGraph") + return v + FreeCADGui.addCommand("BIM_Create2DViews", BIM_Create2DViews(self.create_2dviews)) + insert_at_index = self.annotationtools.index("BIM_TDPage") + self.annotationtools.insert(insert_at_index, "BIM_Create2DViews") + # load rebar tools (Reinforcement addon) try: @@ -488,6 +506,7 @@ class BIMWorkbench(Workbench): import BimStatus from nativeifc import ifc_observer from draftutils import grid_observer + from draftutils import doc_observer PARAMS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM") @@ -497,6 +516,7 @@ class BIMWorkbench(Workbench): FreeCADGui.Snapper.show() WorkingPlane._view_observer_start() grid_observer._view_observer_setup() + doc_observer._doc_observer_start() if PARAMS.GetBool("FirstTime", True) and (not hasattr(FreeCAD, "TestEnvironment")): todo.ToDo.delay(FreeCADGui.runCommand, "BIM_Welcome") @@ -559,7 +579,6 @@ class BIMWorkbench(Workbench): Log("BIM workbench activated\n") - def Deactivated(self): from draftutils import todo @@ -568,6 +587,7 @@ class BIMWorkbench(Workbench): import WorkingPlane from nativeifc import ifc_observer from draftutils import grid_observer + from draftutils import doc_observer PARAMS = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/BIM") @@ -581,6 +601,7 @@ class BIMWorkbench(Workbench): FreeCADGui.Snapper.hide() WorkingPlane._view_observer_stop() grid_observer._view_observer_setup() + doc_observer._doc_observer_stop() # print("Deactivating status icon") todo.ToDo.delay(BimStatus.setStatusIcons, False) diff --git a/src/Mod/BIM/Resources/create_qrc.py b/src/Mod/BIM/Resources/create_qrc.py index 155100c670..3d5dc4d39f 100755 --- a/src/Mod/BIM/Resources/create_qrc.py +++ b/src/Mod/BIM/Resources/create_qrc.py @@ -1,3 +1,27 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * * +# * Copyright (c) 2024 Yorik van Havre * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + #!/usr/bin/python import os diff --git a/src/Mod/BIM/bimcommands/BimBox.py b/src/Mod/BIM/bimcommands/BimBox.py index e8ec126598..1d79f5f6fa 100644 --- a/src/Mod/BIM/bimcommands/BimBox.py +++ b/src/Mod/BIM/bimcommands/BimBox.py @@ -51,6 +51,7 @@ class BIM_Box: import draftguitools.gui_trackers as DraftTrackers FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off + self.doc = FreeCAD.ActiveDocument self.wp = WorkingPlane.get_working_plane() # here we will store our points self.points = [] @@ -276,15 +277,14 @@ class BIM_Box: if self.HeightValue > 0.0: pla = DraftGeomUtils.placement_from_points(p1, p3, p2) self.LengthValue, self.WidthValue = self.WidthValue, self.LengthValue - doc = FreeCAD.ActiveDocument - doc.openTransaction(translate("Arch","Create Box")) - cube = doc.addObject("Part::Box", "Cube") + self.doc.openTransaction(translate("Arch","Create Box")) + cube = self.doc.addObject("Part::Box", "Box") cube.Placement = pla cube.Length = self.LengthValue cube.Width = self.WidthValue cube.Height = abs(self.HeightValue) - doc.commitTransaction() - doc.recompute() + self.doc.commitTransaction() + self.doc.recompute() def _finish(self): self.wp._restore() diff --git a/src/Mod/BIM/bimcommands/BimCurtainwall.py b/src/Mod/BIM/bimcommands/BimCurtainwall.py index ee43ee051b..739fc1005c 100644 --- a/src/Mod/BIM/bimcommands/BimCurtainwall.py +++ b/src/Mod/BIM/bimcommands/BimCurtainwall.py @@ -52,19 +52,20 @@ class Arch_CurtainWall: def Activated(self): + self.doc = FreeCAD.ActiveDocument sel = FreeCADGui.Selection.getSelection() if len(sel) > 1: FreeCAD.Console.PrintError(translate("Arch","Please select only one base object or none")+"\n") elif len(sel) == 1: # build on selection FreeCADGui.Control.closeDialog() - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Curtain Wall")) + self.doc.openTransaction(translate("Arch","Create Curtain Wall")) FreeCADGui.addModule("Draft") FreeCADGui.addModule("Arch") FreeCADGui.doCommand("obj = Arch.makeCurtainWall(FreeCAD.ActiveDocument."+FreeCADGui.Selection.getSelection()[0].Name+")") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() else: # interactive line drawing FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off @@ -90,14 +91,14 @@ class Arch_CurtainWall: FreeCAD.activeDraftCommand = None FreeCADGui.Snapper.off() FreeCADGui.Control.closeDialog() - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Curtain Wall")) + self.doc.openTransaction(translate("Arch","Create Curtain Wall")) FreeCADGui.addModule("Draft") FreeCADGui.addModule("Arch") FreeCADGui.doCommand("base = Draft.makeLine(FreeCAD."+str(self.points[0])+",FreeCAD."+str(self.points[1])+")") FreeCADGui.doCommand("obj = Arch.makeCurtainWall(base)") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() diff --git a/src/Mod/BIM/bimcommands/BimDimensions.py b/src/Mod/BIM/bimcommands/BimDimensions.py index 1b1fed782f..569343519e 100644 --- a/src/Mod/BIM/bimcommands/BimDimensions.py +++ b/src/Mod/BIM/bimcommands/BimDimensions.py @@ -66,11 +66,10 @@ class BIM_DimensionHorizontal(gui_dimensions.Dimension): } def Activated(self): - import WorkingPlane self.dir = WorkingPlane.get_working_plane().u - super().Activated() + super().Activated(dir_vec=self.dir) class BIM_DimensionVertical(gui_dimensions.Dimension): @@ -91,11 +90,10 @@ class BIM_DimensionVertical(gui_dimensions.Dimension): } def Activated(self): - import WorkingPlane self.dir = WorkingPlane.get_working_plane().v - super().Activated() + super().Activated(dir_vec=self.dir) FreeCADGui.addCommand("BIM_DimensionVertical", BIM_DimensionVertical()) diff --git a/src/Mod/BIM/bimcommands/BimImagePlane.py b/src/Mod/BIM/bimcommands/BimImagePlane.py index 56ba73cfc1..ec6056ee9f 100644 --- a/src/Mod/BIM/bimcommands/BimImagePlane.py +++ b/src/Mod/BIM/bimcommands/BimImagePlane.py @@ -49,6 +49,7 @@ class BIM_ImagePlane: from PySide import QtGui import draftguitools.gui_trackers as DraftTrackers + self.doc = FreeCAD.ActiveDocument self.tracker = DraftTrackers.rectangleTracker() self.basepoint = None self.opposite = None @@ -115,17 +116,15 @@ class BIM_ImagePlane: diagonal = self.opposite.sub(self.basepoint) length = DraftVecUtils.project(diagonal, wp.u).Length height = DraftVecUtils.project(diagonal, wp.v).Length - FreeCAD.ActiveDocument.openTransaction("Create image plane") - image = FreeCAD.ActiveDocument.addObject( - "Image::ImagePlane", "ImagePlane" - ) + self.doc.openTransaction("Create image plane") + image = self.doc.addObject("Image::ImagePlane", "ImagePlane") image.Label = os.path.splitext(os.path.basename(self.filename))[0] image.ImageFile = self.filename image.Placement = FreeCAD.Placement(midpoint, rotation) image.XSize = length image.YSize = height - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() FreeCADGui.addCommand("BIM_ImagePlane", BIM_ImagePlane()) diff --git a/src/Mod/BIM/bimcommands/BimPanel.py b/src/Mod/BIM/bimcommands/BimPanel.py index 501259cef8..8e907ca5f7 100644 --- a/src/Mod/BIM/bimcommands/BimPanel.py +++ b/src/Mod/BIM/bimcommands/BimPanel.py @@ -66,6 +66,8 @@ class Arch_Panel: import Draft import draftguitools.gui_trackers as DraftTrackers from draftutils import params + + self.doc = FreeCAD.ActiveDocument self.Length = params.get_param_arch("PanelLength") self.Width = params.get_param_arch("PanelWidth") self.Thickness = params.get_param_arch("PanelThickness") @@ -77,14 +79,14 @@ class Arch_Panel: if len(sel) == 1: if Draft.getType(sel[0]) == "Panel": return - FreeCAD.ActiveDocument.openTransaction(str(translate("Arch","Create Panel"))) + self.doc.openTransaction(str(translate("Arch","Create Panel"))) FreeCADGui.addModule("Arch") FreeCADGui.addModule("Draft") for obj in sel: FreeCADGui.doCommand("obj = Arch.makePanel(FreeCAD.ActiveDocument." + obj.Name + ",thickness=" + str(self.Thickness) + ")") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() return # interactive mode @@ -111,7 +113,7 @@ class Arch_Panel: self.tracker.finalize() if point is None: return - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Panel")) + self.doc.openTransaction(translate("Arch","Create Panel")) FreeCADGui.addModule("Arch") if self.Profile: pr = Presets[self.Profile] @@ -123,8 +125,8 @@ class Arch_Panel: FreeCADGui.doCommand('s.Placement.Base = '+DraftVecUtils.toString(point)) if self.rotated: FreeCADGui.doCommand('s.Placement.Rotation = FreeCAD.Rotation(FreeCAD.Vector(1.00,0.00,0.00),90.00)') - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() if FreeCADGui.draftToolBar.continueCmd.isChecked(): self.Activated() diff --git a/src/Mod/BIM/bimcommands/BimProfile.py b/src/Mod/BIM/bimcommands/BimProfile.py index b839dd98b8..82434cbeeb 100644 --- a/src/Mod/BIM/bimcommands/BimProfile.py +++ b/src/Mod/BIM/bimcommands/BimProfile.py @@ -54,6 +54,7 @@ class Arch_Profile: import ArchProfile FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off + self.doc = FreeCAD.ActiveDocument self.Profile = None self.Categories = [] self.Presets = ArchProfile.readPresets() @@ -118,7 +119,7 @@ class Arch_Profile: if not self.Profile: return pt = "FreeCAD.Vector("+str(point.x)+","+str(point.y)+","+str(point.z)+")" - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Profile")) + self.doc.openTransaction(translate("Arch","Create Profile")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand('p = Arch.makeProfile('+str(self.Profile)+')') FreeCADGui.addModule('WorkingPlane') @@ -126,8 +127,8 @@ class Arch_Profile: FreeCADGui.doCommand('p.Placement.Base = ' + pt) FreeCADGui.addModule("Draft") FreeCADGui.doCommand("Draft.autogroup(p)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() def setCategory(self,i): diff --git a/src/Mod/BIM/bimcommands/BimTruss.py b/src/Mod/BIM/bimcommands/BimTruss.py index c7179fadfa..b2d27e08b2 100644 --- a/src/Mod/BIM/bimcommands/BimTruss.py +++ b/src/Mod/BIM/bimcommands/BimTruss.py @@ -51,6 +51,7 @@ class Arch_Truss: def Activated(self): + self.doc = FreeCAD.ActiveDocument sel = FreeCADGui.Selection.getSelection() if len(sel) > 1: FreeCAD.Console.PrintError(translate("Arch","Please select only one base object or none")+"\n") @@ -90,7 +91,7 @@ class Arch_Truss: """Creates the truss""" FreeCADGui.Control.closeDialog() - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Truss")) + self.doc.openTransaction(translate("Arch","Create Truss")) FreeCADGui.addModule("Draft") FreeCADGui.addModule("Arch") if not basename: @@ -101,8 +102,8 @@ class Arch_Truss: basename = "base" FreeCADGui.doCommand("obj = Arch.makeTruss("+basename+")") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() FreeCADGui.addCommand('Arch_Truss', Arch_Truss()) diff --git a/src/Mod/BIM/bimcommands/BimWall.py b/src/Mod/BIM/bimcommands/BimWall.py index b4b7e836bd..e94a1f38a8 100644 --- a/src/Mod/BIM/bimcommands/BimWall.py +++ b/src/Mod/BIM/bimcommands/BimWall.py @@ -71,6 +71,8 @@ class Arch_Wall: import WorkingPlane from draftutils import params import draftguitools.gui_trackers as DraftTrackers + + self.doc = FreeCAD.ActiveDocument self.Align = ["Center","Left","Right"][params.get_param_arch("WallAlignment")] self.MultiMat = None self.Length = None @@ -82,44 +84,38 @@ class Arch_Wall: self.JOIN_WALLS_SKETCHES = params.get_param_arch("joinWallSketches") self.AUTOJOIN = params.get_param_arch("autoJoinWalls") sel = FreeCADGui.Selection.getSelectionEx() - done = False self.existing = [] self.wp = None if sel: # automatic mode if Draft.getType(sel[0].Object) != "Wall": - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall")) + self.doc.openTransaction(translate("Arch","Create Wall")) FreeCADGui.addModule("Arch") for selobj in sel: - if Draft.getType(selobj.Object) == "Space": - spacedone = False - if selobj.HasSubObjects: - if "Face" in selobj.SubElementNames[0]: - idx = int(selobj.SubElementNames[0][4:]) - FreeCADGui.doCommand("obj = Arch.makeWall(FreeCAD.ActiveDocument."+selobj.Object.Name+",face="+str(idx)+")") - spacedone = True - if not spacedone: - FreeCADGui.doCommand('obj = Arch.makeWall(FreeCAD.ActiveDocument.'+selobj.Object.Name+')') + if Draft.getType(selobj.Object) == "Space" \ + and selobj.HasSubObjects \ + and "Face" in selobj.SubElementNames[0]: + idx = int(selobj.SubElementNames[0][4:]) + FreeCADGui.doCommand("obj = Arch.makeWall(FreeCAD.ActiveDocument."+selobj.Object.Name+",face="+str(idx)+")") else: - FreeCADGui.doCommand('obj = Arch.makeWall(FreeCAD.ActiveDocument.'+selobj.Object.Name+')') + FreeCADGui.doCommand("obj = Arch.makeWall(FreeCAD.ActiveDocument."+selobj.Object.Name+")") FreeCADGui.addModule("Draft") FreeCADGui.doCommand("Draft.autogroup(obj)") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() - done = True + self.doc.commitTransaction() + self.doc.recompute() + return - if not done: - # interactive mode + # interactive mode - self.points = [] - self.wp = WorkingPlane.get_working_plane() - self.tracker = DraftTrackers.boxTracker() - FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off - FreeCADGui.Snapper.getPoint(callback=self.getPoint, - extradlg=self.taskbox(), - title=translate("Arch","First point of wall")+":") - FreeCADGui.draftToolBar.continueCmd.show() + FreeCAD.activeDraftCommand = self # register as a Draft command for auto grid on/off + self.points = [] + self.wp = WorkingPlane.get_working_plane() + self.tracker = DraftTrackers.boxTracker() + FreeCADGui.Snapper.getPoint(callback=self.getPoint, + extradlg=self.taskbox(), + title=translate("Arch","First point of wall")+":") + FreeCADGui.draftToolBar.continueCmd.show() def getPoint(self,point=None,obj=None): """Callback for clicks during interactive mode. @@ -145,9 +141,9 @@ class Arch_Wall: if not obj in self.existing: self.existing.append(obj) if point is None: - self.tracker.finalize() FreeCAD.activeDraftCommand = None FreeCADGui.Snapper.off() + self.tracker.finalize() return self.points.append(point) if len(self.points) == 1: @@ -161,12 +157,12 @@ class Arch_Wall: title=translate("Arch","Next point")+":",mode="line") elif len(self.points) == 2: - l = Part.LineSegment(self.wp.get_local_coords(self.points[0]), - self.wp.get_local_coords(self.points[1])) - self.tracker.off() FreeCAD.activeDraftCommand = None FreeCADGui.Snapper.off() - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall")) + self.tracker.off() + l = Part.LineSegment(self.wp.get_local_coords(self.points[0]), + self.wp.get_local_coords(self.points[1])) + self.doc.openTransaction(translate("Arch","Create Wall")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand('import Part') FreeCADGui.doCommand('trace=Part.LineSegment(FreeCAD.'+str(l.StartPoint)+',FreeCAD.'+str(l.EndPoint)+')') @@ -184,16 +180,16 @@ class Arch_Wall: # if not possible, add new wall as addition to the existing one self.addDefault() if self.AUTOJOIN: - FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+FreeCAD.ActiveDocument.Objects[-1].Name+',FreeCAD.ActiveDocument.'+w.Name+')') + FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+self.doc.Objects[-1].Name+',FreeCAD.ActiveDocument.'+w.Name+')') else: self.addDefault() else: # add new wall as addition to the first existing one self.addDefault() if self.AUTOJOIN: - FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+FreeCAD.ActiveDocument.Objects[-1].Name+',FreeCAD.ActiveDocument.'+self.existing[0].Name+')') - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + FreeCADGui.doCommand('Arch.addComponents(FreeCAD.ActiveDocument.'+self.doc.Objects[-1].Name+',FreeCAD.ActiveDocument.'+self.existing[0].Name+')') + self.doc.commitTransaction() + self.doc.recompute() # gui_utils.end_all_events() # Causes a crash on Linux. self.tracker.finalize() if FreeCADGui.draftToolBar.continueCmd.isChecked(): @@ -285,7 +281,7 @@ class Arch_Wall: comboWallPresets.setToolTip(translate("Arch","This list shows all the MultiMaterials objects of this document. Create some to define wall types.")) self.multimats = [] self.MultiMat = None - for o in FreeCAD.ActiveDocument.Objects: + for o in self.doc.Objects: if Draft.getType(o) == "MultiMaterial": self.multimats.append(o) comboWallPresets.addItem(o.Label) @@ -440,13 +436,13 @@ class Arch_Wall: def createFromGUI(self): """Callback to create wall by using the _CommandWall.taskbox()""" - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Wall")) + self.doc.openTransaction(translate("Arch","Create Wall")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand('wall = Arch.makeWall(length='+str(self.lengthValue)+',width='+str(self.Width)+',height='+str(self.Height)+',align="'+str(self.Align)+'")') if self.MultiMat: FreeCADGui.doCommand("wall.Material = FreeCAD.ActiveDocument."+self.MultiMat.Name) - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() if hasattr(FreeCADGui,"draftToolBar"): FreeCADGui.draftToolBar.escape() diff --git a/src/Mod/BIM/bimcommands/BimWindow.py b/src/Mod/BIM/bimcommands/BimWindow.py index 8ff453bf3e..3652c002d4 100644 --- a/src/Mod/BIM/bimcommands/BimWindow.py +++ b/src/Mod/BIM/bimcommands/BimWindow.py @@ -62,6 +62,8 @@ class Arch_Window: import Draft import WorkingPlane import draftguitools.gui_trackers as DraftTrackers + + self.doc = FreeCAD.ActiveDocument self.sel = FreeCADGui.Selection.getSelection() self.W1 = params.get_param_arch("WindowW1") # thickness of the fixed frame if self.doormode: @@ -100,7 +102,7 @@ class Arch_Window: if obj.Objects[0].Inlist: host = obj.Objects[0].Inlist[0] - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Window")) + self.doc.openTransaction(translate("Arch","Create Window")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("win = Arch.makeWindow(FreeCAD.ActiveDocument."+obj.Name+")") if host and self.Include: @@ -111,19 +113,19 @@ class Arch_Window: if not sibling in sibs: sibs.append(sibling) FreeCADGui.doCommand("win.Hosts = win.Hosts+[FreeCAD.ActiveDocument."+sibling.Name+"]") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() return # Try to detect an object to use as a window type - TODO we must make this safer elif obj.Shape.Solids and (Draft.getType(obj) not in ["Wall","Structure","Roof"]): # we consider the selected object as a type - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Window")) + self.doc.openTransaction(translate("Arch","Create Window")) FreeCADGui.addModule("Arch") FreeCADGui.doCommand("Arch.makeWindow(FreeCAD.ActiveDocument."+obj.Name+")") - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() return # interactive mode @@ -171,7 +173,7 @@ class Arch_Window: if self.sel: obj = self.sel[0] point = point.add(FreeCAD.Vector(0,0,self.Sill)) - FreeCAD.ActiveDocument.openTransaction(translate("Arch","Create Window")) + self.doc.openTransaction(translate("Arch","Create Window")) FreeCADGui.doCommand("import FreeCAD, Arch, DraftGeomUtils, WorkingPlane") FreeCADGui.doCommand("wp = WorkingPlane.get_working_plane()") @@ -188,11 +190,11 @@ class Arch_Window: if self.Preset >= len(WindowPresets): preset = False # library object - col = FreeCAD.ActiveDocument.Objects + col = self.doc.Objects path = self.librarypresets[self.Preset - len(WindowPresets)][1] FreeCADGui.doCommand("FreeCADGui.ActiveDocument.mergeProject('" + path + "')") # find the latest added window - nol = FreeCAD.ActiveDocument.Objects + nol = self.doc.Objects for o in nol[len(col):]: if Draft.getType(o) == "Window": if Draft.getType(o.Base) != "Sketcher::SketchObject": @@ -246,8 +248,8 @@ class Arch_Window: if SketchArch: ArchSketchObject.attachToHost(w, target=host, pl=wPl) - FreeCAD.ActiveDocument.commitTransaction() - FreeCAD.ActiveDocument.recompute() + self.doc.commitTransaction() + self.doc.recompute() # gui_utils.end_all_events() # Causes a crash on Linux. self.tracker.finalize() return @@ -265,7 +267,7 @@ class Arch_Window: if info: if "Face" in info['Component']: import DraftGeomUtils - o = FreeCAD.ActiveDocument.getObject(info['Object']) + o = self.doc.getObject(info['Object']) self.baseFace = [o,int(info['Component'][4:])-1] #print("switching to ",o.Label," face ",self.baseFace[1]) f = o.Shape.Faces[self.baseFace[1]] diff --git a/src/Mod/BIM/bimcommands/__init__.py b/src/Mod/BIM/bimcommands/__init__.py index ef6aed1f43..d101870202 100644 --- a/src/Mod/BIM/bimcommands/__init__.py +++ b/src/Mod/BIM/bimcommands/__init__.py @@ -1,3 +1,5 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + import glob import os diff --git a/src/Mod/BIM/utils/getIfcElements.py b/src/Mod/BIM/utils/getIfcElements.py index 45373b99ed..2552e63dd9 100644 --- a/src/Mod/BIM/utils/getIfcElements.py +++ b/src/Mod/BIM/utils/getIfcElements.py @@ -1,3 +1,27 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * * +# * Copyright (c) 2024 Yorik van Havre * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + """This script converts the computer iterpretable listing ifcXML XSD into a list of non-abstract children of IfcProduct""" diff --git a/src/Mod/CAM/App/AppPath.cpp b/src/Mod/CAM/App/AppPath.cpp index 15001275db..2e57c22c85 100644 --- a/src/Mod/CAM/App/AppPath.cpp +++ b/src/Mod/CAM/App/AppPath.cpp @@ -63,7 +63,7 @@ PyMOD_INIT_FUNC(PathApp) } PyObject* pathModule = PathApp::initModule(); - Base::Console().Log("Loading Path module... done\n"); + Base::Console().log("Loading Path module... done\n"); Py::Object module(pathModule); diff --git a/src/Mod/CAM/App/AppPathPy.cpp b/src/Mod/CAM/App/AppPathPy.cpp index 5239ca7632..1e73697a9e 100644 --- a/src/Mod/CAM/App/AppPathPy.cpp +++ b/src/Mod/CAM/App/AppPathPy.cpp @@ -63,7 +63,7 @@ else { \ str += "No OCCT Exception Message"; \ } \ - Base::Console().Error(str.c_str()); \ + Base::Console().error(str.c_str()); \ PyErr_SetString(Part::PartExceptionOCCError, str.c_str()); \ } \ catch (Base::Exception & e) \ @@ -72,7 +72,7 @@ str += "FreeCAD exception thrown ("; \ str += e.what(); \ str += ")"; \ - e.ReportException(); \ + e.reportException(); \ PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ } \ catch (std::exception & e) \ @@ -81,7 +81,7 @@ str += "STL exception thrown ("; \ str += e.what(); \ str += ")"; \ - Base::Console().Error(str.c_str()); \ + Base::Console().error(str.c_str()); \ PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ } \ catch (const char* e) \ diff --git a/src/Mod/CAM/App/Command.cpp b/src/Mod/CAM/App/Command.cpp index ac8913b754..8b01fd3190 100644 --- a/src/Mod/CAM/App/Command.cpp +++ b/src/Mod/CAM/App/Command.cpp @@ -91,7 +91,7 @@ bool Command::has(const std::string& attr) const { std::string a(attr); boost::to_upper(a); - return Parameters.count(a) > 0; + return Parameters.contains(a); } std::string Command::toGCode(int precision, bool padzero) const diff --git a/src/Mod/CAM/App/CommandPyImp.cpp b/src/Mod/CAM/App/CommandPyImp.cpp index 0ed3af7f92..e0d0305e3e 100644 --- a/src/Mod/CAM/App/CommandPyImp.cpp +++ b/src/Mod/CAM/App/CommandPyImp.cpp @@ -281,7 +281,7 @@ PyObject* CommandPy::getCustomAttributes(const char* attr) const if (satt.length() == 1) { if (isalpha(satt[0])) { boost::to_upper(satt); - if (getCommandPtr()->Parameters.count(satt)) { + if (getCommandPtr()->Parameters.contains(satt)) { return PyFloat_FromDouble(getCommandPtr()->Parameters[satt]); } Py_INCREF(Py_None); diff --git a/src/Mod/CAM/App/Path.cpp b/src/Mod/CAM/App/Path.cpp index f3f4f8e7e4..6eda0ad030 100644 --- a/src/Mod/CAM/App/Path.cpp +++ b/src/Mod/CAM/App/Path.cpp @@ -154,7 +154,7 @@ double Toolpath::getCycleTime(double hFeed, double vFeed, double hRapid, double ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( "User parameter:BaseApp/Preferences/Mod/CAM"); if (!hGrp->GetBool("WarningsSuppressAllSpeeds", true)) { - Base::Console().Warning("Feed Rate Error: Check Tool Controllers have Feed Rates"); + Base::Console().warning("Feed Rate Error: Check Tool Controllers have Feed Rates"); } return 0; } diff --git a/src/Mod/CAM/CAMTests/TestRefactoredGrblPost.py b/src/Mod/CAM/CAMTests/TestRefactoredGrblPost.py index eed8364a92..cdad7582ff 100644 --- a/src/Mod/CAM/CAMTests/TestRefactoredGrblPost.py +++ b/src/Mod/CAM/CAMTests/TestRefactoredGrblPost.py @@ -143,7 +143,6 @@ M2 expected = """G17 G90 G21 G54 -M6 T1 M5 G17 G90 M2 diff --git a/src/Mod/CAM/CAMTests/TestRefactoredTestPost.py b/src/Mod/CAM/CAMTests/TestRefactoredTestPost.py index 1dadfddce0..58b05f44a6 100644 --- a/src/Mod/CAM/CAMTests/TestRefactoredTestPost.py +++ b/src/Mod/CAM/CAMTests/TestRefactoredTestPost.py @@ -103,8 +103,8 @@ class TestRefactoredTestPost(PathTestUtils.PathTestBase): gcode = self.post.export()[0][1] if debug: print(f"--------{nl}{gcode}--------{nl}") - # there are 4 lines of "other stuff" before the line we are interested in - self.assertEqual(gcode.splitlines()[4], expected) + # there are 3 lines of "other stuff" before the line we are interested in + self.assertEqual(gcode.splitlines()[3], expected) def multi_compare(self, path, expected, args, debug=False): """Perform a test with multiple lines of gcode comparison.""" @@ -144,12 +144,12 @@ class TestRefactoredTestPost(PathTestUtils.PathTestBase): self.job.PostProcessorArgs = "--axis-modal" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[5], "G0 Y30.000") + self.assertEqual(gcode.splitlines()[4], "G0 Y30.000") self.job.PostProcessorArgs = "--no-axis-modal" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[5], "G0 X10.000 Y30.000 Z30.000") + self.assertEqual(gcode.splitlines()[4], "G0 X10.000 Y30.000 Z30.000") ############################################################################# @@ -172,7 +172,6 @@ G54 (Block-name: TC: Default Tool) (Block-expand: 0) (Block-enable: 1) -M6 T1 (Block-name: Profile) (Block-expand: 0) (Block-enable: 1) @@ -187,7 +186,6 @@ M6 T1 """G90 G21 G54 -M6 T1 """, "--no-bcnc", ) @@ -211,7 +209,6 @@ M6 T1 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -238,7 +235,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -274,7 +270,6 @@ G90 """G90 G20 G54 -M6 T1 G0 X1.0000 Y2.0000 G0 Z8.0000 G90 @@ -439,14 +434,14 @@ G54 # print(f"--------{nl}{gcode}--------{nl}") # Note: The "internal" F speed is in mm/s, # while the output F speed is in mm/min. - self.assertEqual(gcode.splitlines()[4], "G1 X10.000 Y20.000 Z30.000 F7387.407") + self.assertEqual(gcode.splitlines()[3], "G1 X10.000 Y20.000 Z30.000 F7387.407") self.job.PostProcessorArgs = "--feed-precision=2" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") # Note: The "internal" F speed is in mm/s, # while the output F speed is in mm/min. - self.assertEqual(gcode.splitlines()[4], "G1 X10.000 Y20.000 Z30.000 F7387.41") + self.assertEqual(gcode.splitlines()[3], "G1 X10.000 Y20.000 Z30.000 F7387.41") ############################################################################# @@ -522,13 +517,11 @@ G54 self.assertEqual(split_gcode[4], "G90") self.assertEqual(split_gcode[5], "G21") self.assertEqual(split_gcode[6], "G54") - self.assertEqual(split_gcode[7], "M6 T1") # Test without comments or header. expected = """G90 G21 G54 -M6 T1 """ self.job.PostProcessorArgs = "--no-comments --no-header" gcode = self.post.export()[0][1] @@ -539,7 +532,7 @@ M6 T1 def test00160(self): """Test Line Numbers.""" - self.single_compare("G0 X10 Y20 Z30", "N140 G0 X10.000 Y20.000 Z30.000", "--line-numbers") + self.single_compare("G0 X10 Y20 Z30", "N130 G0 X10.000 Y20.000 Z30.000", "--line-numbers") ############################################################################# @@ -555,7 +548,7 @@ M6 T1 # print(f"--------{nl}{gcode}--------{nl}") self.assertEqual(gcode.splitlines()[1], "G20") self.assertEqual( - gcode.splitlines()[4], + gcode.splitlines()[3], "G0 X0.3937 Y0.7874 Z1.1811 A10.0000 B20.0000 C30.0000 U0.3937 V0.7874 W1.1811", ) @@ -575,11 +568,11 @@ M6 T1 self.job.PostProcessorArgs = "--modal" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[5], "X10.000 Y30.000 Z30.000") + self.assertEqual(gcode.splitlines()[4], "X10.000 Y30.000 Z30.000") self.job.PostProcessorArgs = "--no-modal" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[5], "G0 X10.000 Y30.000 Z30.000") + self.assertEqual(gcode.splitlines()[4], "G0 X10.000 Y30.000 Z30.000") ############################################################################# @@ -743,7 +736,7 @@ M6 T1 self.profile_op.Path = Path.Path([c, c2]) - self.job.PostProcessorArgs = "--tlo" + self.job.PostProcessorArgs = "--tlo --tool_change" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") @@ -752,7 +745,7 @@ M6 T1 self.assertEqual(split_gcode[7], "M3 S3000") # suppress TLO - self.job.PostProcessorArgs = "--no-tlo" + self.job.PostProcessorArgs = "--no-tlo --tool_change" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") @@ -769,19 +762,30 @@ M6 T1 c2 = Path.Command("M3 S3000") self.profile_op.Path = Path.Path([c, c2]) - self.job.PostProcessorArgs = "--tool_change" + self.job.PostProcessorArgs = "--no-comments --no-tool_change" + gcode = self.post.export()[0][1] + split_gcode = gcode.splitlines() + # print(f"--------{nl}{gcode}--------{nl}") + self.assertEqual(split_gcode[2], "G54") + self.assertEqual(split_gcode[3], "M3 S3000") + + self.job.PostProcessorArgs = "--no-comments --tool_change" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") self.assertEqual(split_gcode[4], "M6 T2") - self.assertEqual(split_gcode[5], "M3 S3000") self.job.PostProcessorArgs = "--comments --no-tool_change" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") self.assertEqual(split_gcode[13], "(M6 T2)") - self.assertEqual(split_gcode[14], "M3 S3000") + + self.job.PostProcessorArgs = "--comments --tool_change" + gcode = self.post.export()[0][1] + split_gcode = gcode.splitlines() + # print(f"--------{nl}{gcode}--------{nl}") + self.assertEqual(split_gcode[13], "M6 T2") ############################################################################# @@ -795,14 +799,14 @@ M6 T1 self.job.PostProcessorArgs = "" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[4], "M3 S3000") + self.assertEqual(gcode.splitlines()[3], "M3 S3000") self.job.PostProcessorArgs = "--wait-for-spindle=1.23456" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(split_gcode[4], "M3 S3000") - self.assertEqual(split_gcode[5], "G4 P1.23456") + self.assertEqual(split_gcode[3], "M3 S3000") + self.assertEqual(split_gcode[4], "G4 P1.23456") c = Path.Command("M4 S3000") self.profile_op.Path = Path.Path([c]) @@ -812,11 +816,11 @@ M6 T1 self.job.PostProcessorArgs = "" gcode = self.post.export()[0][1] # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(gcode.splitlines()[4], "M4 S3000") + self.assertEqual(gcode.splitlines()[3], "M4 S3000") self.job.PostProcessorArgs = "--wait-for-spindle=1.23456" gcode = self.post.export()[0][1] split_gcode = gcode.splitlines() # print(f"--------{nl}{gcode}--------{nl}") - self.assertEqual(split_gcode[4], "M4 S3000") - self.assertEqual(split_gcode[5], "G4 P1.23456") + self.assertEqual(split_gcode[3], "M4 S3000") + self.assertEqual(split_gcode[4], "G4 P1.23456") diff --git a/src/Mod/CAM/CAMTests/TestRefactoredTestPostGCodes.py b/src/Mod/CAM/CAMTests/TestRefactoredTestPostGCodes.py index edeb10e442..aff6c073de 100644 --- a/src/Mod/CAM/CAMTests/TestRefactoredTestPostGCodes.py +++ b/src/Mod/CAM/CAMTests/TestRefactoredTestPostGCodes.py @@ -103,8 +103,8 @@ class TestRefactoredTestPostGCodes(PathTestUtils.PathTestBase): gcode = self.post.export()[0][1] if debug: print(f"--------{nl}{gcode}--------{nl}") - # there are 4 lines of "other stuff" before the line we are interested in - self.assertEqual(gcode.splitlines()[4], expected) + # there are 3 lines of "other stuff" before the line we are interested in + self.assertEqual(gcode.splitlines()[3], expected) def multi_compare(self, path, expected, args, debug=False): """Perform a test with multiple lines of gcode comparison.""" @@ -726,7 +726,6 @@ class TestRefactoredTestPostGCodes(PathTestUtils.PathTestBase): """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -742,7 +741,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -823,7 +821,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -839,7 +836,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -922,7 +918,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -938,7 +933,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -1001,7 +995,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1017,7 +1010,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1082,7 +1074,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -1098,7 +1089,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -1163,7 +1153,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1179,7 +1168,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1246,7 +1234,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -1262,7 +1249,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G90 @@ -1343,7 +1329,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1359,7 +1344,6 @@ G90 """G90 G21 G54 -M6 T1 G0 X1.000 Y2.000 G0 Z8.000 G91 @@ -1791,7 +1775,6 @@ G90 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X20.000 Y30.000 Z10.000 A70.000 B80.000 C90.000 U40.000 V50.000 W60.000 F74.074 @@ -1799,7 +1782,6 @@ G1 X20.000 Y30.000 Z10.000 A70.000 B80.000 C90.000 U40.000 V50.000 W60.000 F74.0 """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F74.0736 G1 X0.7874 Y1.1811 Z0.3937 A70.0000 B80.0000 C90.0000 U1.5748 V1.9685 W2.3622 F2.9163 @@ -1814,14 +1796,12 @@ G1 X0.7874 Y1.1811 Z0.3937 A70.0000 B80.0000 C90.0000 U1.5748 V1.9685 W2.3622 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X20.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.7874 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 """, @@ -1835,14 +1815,12 @@ G1 X0.7874 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y30.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y1.1811 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 """, @@ -1856,14 +1834,12 @@ G1 X0.3937 Y1.1811 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z10.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z0.3937 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 """, @@ -1877,14 +1853,12 @@ G1 X0.3937 Y0.7874 Z0.3937 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A70.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A70.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F74.0736 """, @@ -1898,14 +1872,12 @@ G1 X0.3937 Y0.7874 Z1.1811 A70.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F7 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B80.000 C60.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B80.0000 C60.0000 U2.7559 V3.1496 W3.5433 F74.0736 """, @@ -1919,14 +1891,12 @@ G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B80.0000 C60.0000 U2.7559 V3.1496 W3.5433 F7 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C90.000 U70.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C90.0000 U2.7559 V3.1496 W3.5433 F74.0736 """, @@ -1940,14 +1910,12 @@ G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C90.0000 U2.7559 V3.1496 W3.5433 F7 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U40.000 V80.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U1.5748 V3.1496 W3.5433 F2.9163 """, @@ -1961,14 +1929,12 @@ G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U1.5748 V3.1496 W3.5433 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V50.000 W90.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V1.9685 W3.5433 F2.9163 """, @@ -1982,14 +1948,12 @@ G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V1.9685 W3.5433 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 U70.000 V80.000 W60.000 F74.074 """, """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W2.3622 F2.9163 """, @@ -2004,7 +1968,6 @@ G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W2.3622 F2 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 F74.074 G1 X10.000 Y20.000 Z30.000 F74.074 G1 X20.000 Y30.000 Z10.000 F74.074 @@ -2012,7 +1975,6 @@ G1 X20.000 Y30.000 Z10.000 F74.074 """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 F2.9163 G1 X0.7874 Y1.1811 Z0.3937 F2.9163 @@ -2028,7 +1990,6 @@ G1 X0.7874 Y1.1811 Z0.3937 F2.9163 """G90 G21 G54 -M6 T1 G1 U70.000 V80.000 W90.000 F74.074 G1 U70.000 V80.000 W90.000 F74.074 G1 U40.000 V50.000 W60.000 F74.074 @@ -2036,7 +1997,6 @@ G1 U40.000 V50.000 W60.000 F74.074 """G90 G20 G54 -M6 T1 G1 U2.7559 V3.1496 W3.5433 F2.9163 G1 U2.7559 V3.1496 W3.5433 F2.9163 G1 U1.5748 V1.9685 W2.3622 F2.9163 @@ -2052,7 +2012,6 @@ G1 U1.5748 V1.9685 W2.3622 F2.9163 """G90 G21 G54 -M6 T1 G1 A40.000 B50.000 C60.000 F74.074 G1 A40.000 B50.000 C60.000 F74.074 G1 A70.000 B80.000 C90.000 F74.074 @@ -2060,7 +2019,6 @@ G1 A70.000 B80.000 C90.000 F74.074 """G90 G20 G54 -M6 T1 G1 A40.0000 B50.0000 C60.0000 F74.0736 G1 A40.0000 B50.0000 C60.0000 F74.0736 G1 A70.0000 B80.0000 C90.0000 F74.0736 @@ -2076,7 +2034,6 @@ G1 A70.0000 B80.0000 C90.0000 F74.0736 """G90 G21 G54 -M6 T1 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 F74.074 G1 X10.000 Y20.000 Z30.000 A40.000 B50.000 C60.000 F74.074 G1 X20.000 Y30.000 Z10.000 A70.000 B80.000 C90.000 F74.074 @@ -2084,7 +2041,6 @@ G1 X20.000 Y30.000 Z10.000 A70.000 B80.000 C90.000 F74.074 """G90 G20 G54 -M6 T1 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 F2.9163 G1 X0.3937 Y0.7874 Z1.1811 A40.0000 B50.0000 C60.0000 F74.0736 G1 X0.7874 Y1.1811 Z0.3937 A70.0000 B80.0000 C90.0000 F2.9163 @@ -2100,7 +2056,6 @@ G1 X0.7874 Y1.1811 Z0.3937 A70.0000 B80.0000 C90.0000 F2.9163 """G90 G21 G54 -M6 T1 G1 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 A40.000 B50.000 C60.000 U70.000 V80.000 W90.000 F74.074 G1 A70.000 B80.000 C90.000 U40.000 V50.000 W60.000 F74.074 @@ -2108,7 +2063,6 @@ G1 A70.000 B80.000 C90.000 U40.000 V50.000 W60.000 F74.074 """G90 G20 G54 -M6 T1 G1 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F2.9163 G1 A40.0000 B50.0000 C60.0000 U2.7559 V3.1496 W3.5433 F74.0736 G1 A70.0000 B80.0000 C90.0000 U1.5748 V1.9685 W2.3622 F2.9163 @@ -2124,7 +2078,6 @@ G1 A70.0000 B80.0000 C90.0000 U1.5748 V1.9685 W2.3622 F2.9163 """G90 G21 G54 -M6 T1 G1 X10.000 A40.000 F74.074 G1 X10.000 A40.000 F74.074 G1 X20.000 A70.000 F74.074 @@ -2132,7 +2085,6 @@ G1 X20.000 A70.000 F74.074 """G90 G20 G54 -M6 T1 G1 X0.3937 A40.0000 F2.9163 G1 X0.3937 A40.0000 F74.0736 G1 X0.7874 A70.0000 F2.9163 @@ -2148,7 +2100,6 @@ G1 X0.7874 A70.0000 F2.9163 """G90 G21 G54 -M6 T1 G1 A40.000 U70.000 F74.074 G1 A40.000 U70.000 F74.074 G1 A70.000 U40.000 F74.074 @@ -2156,7 +2107,6 @@ G1 A70.000 U40.000 F74.074 """G90 G20 G54 -M6 T1 G1 A40.0000 U2.7559 F2.9163 G1 A40.0000 U2.7559 F74.0736 G1 A70.0000 U1.5748 F2.9163 @@ -2172,7 +2122,6 @@ G1 A70.0000 U1.5748 F2.9163 """G90 G21 G54 -M6 T1 G1 A40.000 F74.074 G1 A40.000 F74.074 G1 A70.000 F74.074 @@ -2180,7 +2129,6 @@ G1 A70.000 F74.074 """G90 G20 G54 -M6 T1 G1 A40.0000 F74.0736 G1 A40.0000 F74.0736 G1 A70.0000 F74.0736 diff --git a/src/Mod/CAM/CAMTests/TestRefactoredTestPostMCodes.py b/src/Mod/CAM/CAMTests/TestRefactoredTestPostMCodes.py index 8692fda619..916dd92e62 100644 --- a/src/Mod/CAM/CAMTests/TestRefactoredTestPostMCodes.py +++ b/src/Mod/CAM/CAMTests/TestRefactoredTestPostMCodes.py @@ -103,8 +103,8 @@ class TestRefactoredTestPostMCodes(PathTestUtils.PathTestBase): gcode = self.post.export()[0][1] if debug: print(f"--------{nl}{gcode}--------{nl}") - # there are 4 lines of "other stuff" before the line we are interested in - self.assertEqual(gcode.splitlines()[4], expected) + # there are 3 lines of "other stuff" before the line we are interested in + self.assertEqual(gcode.splitlines()[3], expected) ############################################################################# # @@ -162,8 +162,26 @@ class TestRefactoredTestPostMCodes(PathTestUtils.PathTestBase): def test20060(self): """Test M6 command Generation.""" - self.single_compare("M6", "M6", "") - self.single_compare("M06", "M06", "") + + c = Path.Command("M6 T2") + + self.profile_op.Path = Path.Path([c]) + + self.job.PostProcessorArgs = "--tool_change" + gcode = self.post.export()[0][1] + split_gcode = gcode.splitlines() + # print(f"--------{nl}{gcode}--------{nl}") + self.assertEqual(split_gcode[4], "M6 T2") + + c = Path.Command("M06 T02") + + self.profile_op.Path = Path.Path([c]) + + self.job.PostProcessorArgs = "--tool_change" + gcode = self.post.export()[0][1] + split_gcode = gcode.splitlines() + # print(f"--------{nl}{gcode}--------{nl}") + self.assertEqual(split_gcode[4], "M06 T2") ############################################################################# diff --git a/src/Mod/CAM/CAMTests/TestSnapmakerPost.py b/src/Mod/CAM/CAMTests/TestSnapmakerPost.py index bfa832a438..a141271b8f 100644 --- a/src/Mod/CAM/CAMTests/TestSnapmakerPost.py +++ b/src/Mod/CAM/CAMTests/TestSnapmakerPost.py @@ -16,7 +16,9 @@ # * implied. See the Licence for the specific language governing * # * permissions and limitations under the Licence. * # *************************************************************************** +import argparse import re +from typing import List import FreeCAD @@ -63,7 +65,7 @@ class TestSnapmakerPost(PathTestUtils.PathTestBase): """Unit test tear down""" pass - def get_gcode(self, ops: [str], arguments: str) -> str: + def get_gcode(self, ops: List[str], arguments: str) -> str: """Get postprocessed gcode from a list of operations and postprocessor arguments""" self.profile_op.Path = Path.Path(ops) self.job.PostProcessorArgs = "--no-show-editor --no-gui --no-thumbnail " + arguments @@ -75,10 +77,10 @@ class TestSnapmakerPost(PathTestUtils.PathTestBase): expected_header = """\ ;Header Start ;header_type: cnc -;machine: Snapmaker 2 A350(T) -;Post Processor: Snapmaker_post -;Cam File: boxtest.fcstd -;Output Time: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{0,6} +;machine: Snapmaker 2 A350 50W CNC module +;Post Processor: snapmaker_post +;CAM File: boxtest.fcstd +;Output Time: \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\.\\d{0,6} ;thumbnail: deactivated.""" expected_body = """\ @@ -107,7 +109,7 @@ M5 """ # test header and body with comments - gcode = self.get_gcode([], "--machine=A350 --toolhead=50W --spindle-percent") + gcode = self.get_gcode([], "--machine=A350 --toolhead=50W_CNC") g_lines = gcode.splitlines() e_lines = expected_header.splitlines() + expected_body.splitlines() @@ -117,16 +119,14 @@ M5 if exp.startswith(";Output Time:"): self.assertTrue(re.match(exp, line) is not None) else: - self.assertTrue(line, exp) + self.assertEqual(exp, line) # test body without header - gcode = self.get_gcode([], "--machine=A350 --toolhead=50W --spindle-percent --no-header") + gcode = self.get_gcode([], "--machine=A350 --toolhead=50W_CNC --no-header") self.assertEqual(gcode, expected_body) # test body without comments - gcode = self.get_gcode( - [], "--machine=A350 --toolhead=50W --spindle-percent --no-header --no-comments" - ) + gcode = self.get_gcode([], "--machine=A350 --toolhead=50W_CNC --no-header --no-comments") expected = "".join( [line for line in expected_body.splitlines(keepends=True) if not line.startswith(";")] ) @@ -137,9 +137,7 @@ M5 command = Path.Command("G0 X10 Y20 Z30") expected = "G0 X10.000 Y20.000 Z30.000" - gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=50W --spindle-percent --no-header" - ) + gcode = self.get_gcode([command], "--machine=A350 --toolhead=50W_CNC --no-header") result = gcode.splitlines()[18] self.assertEqual(result, expected) @@ -150,7 +148,7 @@ M5 expected = "G0 X10.00 Y20.00 Z30.00" gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=50W --spindle-percent --no-header --precision=2" + [command], "--machine=A350 --toolhead=50W_CNC --no-header --precision=2" ) result = gcode.splitlines()[18] self.assertEqual(result, expected) @@ -162,7 +160,7 @@ M5 gcode = self.get_gcode( [command], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --line-numbers --line-number=10 --line-increment=2", + "--machine=A350 --toolhead=50W_CNC --no-header --line-numbers --line-number=10 --line-increment=2", ) result = gcode.splitlines()[18] self.assertEqual(result, expected) @@ -171,7 +169,7 @@ M5 """Test Pre-amble""" gcode = self.get_gcode( [], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --preamble='G18 G55' --no-comments", + "--machine=A350 --toolhead=50W_CNC --no-header --preamble='G18 G55' --no-comments", ) result = gcode.splitlines()[0] self.assertEqual(result, "G18 G55") @@ -180,7 +178,7 @@ M5 """Test Post-amble""" gcode = self.get_gcode( [], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --postamble='G0 Z50\nM2' --no-comments", + "--machine=A350 --toolhead=50W_CNC --no-header --postamble='G0 Z50\nM2' --no-comments", ) result = gcode.splitlines()[-2] self.assertEqual(result, "G0 Z50") @@ -193,9 +191,7 @@ M5 # test inches conversion expected = "G0 X0.3937 Y0.7874 Z1.1811" - gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=50W --spindle-percent --no-header --inches" - ) + gcode = self.get_gcode([command], "--machine=A350 --toolhead=50W_CNC --no-header --inches") self.assertEqual(gcode.splitlines()[3], "G20") result = gcode.splitlines()[18] self.assertEqual(result, expected) @@ -204,7 +200,7 @@ M5 expected = "G0 X0.39 Y0.79 Z1.18" gcode = self.get_gcode( [command], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --inches --precision=2", + "--machine=A350 --toolhead=50W_CNC --no-header --inches --precision=2", ) result = gcode.splitlines()[18] self.assertEqual(result, expected) @@ -217,7 +213,7 @@ M5 expected = "G0 Y30.000" gcode = self.get_gcode( - [c0, c1], "--machine=A350 --toolhead=50W --spindle-percent --no-header --axis-modal" + [c0, c1], "--machine=A350 --toolhead=50W_CNC --no-header --axis-modal" ) result = gcode.splitlines()[19] self.assertEqual(result, expected) @@ -228,35 +224,361 @@ M5 c0 = Path.Command("M6 T2") c1 = Path.Command("M3 S3000") - gcode = self.get_gcode( - [c0, c1], "--machine=A350 --toolhead=50W --spindle-percent --no-header" - ) + gcode = self.get_gcode([c0, c1], "--machine=A350 --toolhead=50W_CNC --no-header") self.assertEqual(gcode.splitlines()[19:22], ["M5", "M76", "M6 T2"]) self.assertEqual( gcode.splitlines()[22], "M3 P25" ) # no TLO on Snapmaker (G43 inserted after tool change) - def test_spindle(self): + def test_models(self): + """Test the various models, and also test models that don't exist cause an error.""" + command = Path.Command("G0 X10 Y20 Z30") + expected = "G0 X10.000 Y20.000 Z30.000" + + with self.assertRaises(SystemExit): + self.get_gcode( + [command], + "--no-header", + ) + + with self.assertRaises(SystemExit): + gcode = self.get_gcode( + [command], + "--machine=robot --no-header", + ) + + gcode = self.get_gcode( + [command], + "--machine=Original --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A150 --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A250 --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A250T --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A250T --toolhead=200W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A350 --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A350T --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=A350T --toolhead=200W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + gcode = self.get_gcode( + [command], + "--machine=Artisan --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + + def test_mod_kits(self): + """Test the various mod kits against various models.""" + + # Reference for boundaries with the bracing kit and quick swap kit combinations + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + # Reference for quick swap kit + # [2] https://support.snapmaker.com/hc/en-us/articles/15320624494103-Pre-sale-FAQ-for-Quick-Swap-Kit + + command = Path.Command("G0 X10 Y20 Z30") + expected = "G0 X10.000 Y20.000 Z30.000" + + gcode = self.get_gcode( + [command], + "--machine=Original --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], []) + # https://forum.snapmaker.com/t/cnc-work-area-size/5178 + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=125, Y=125, Z=50)) + + gcode = self.get_gcode( + [command], + "--machine=Original --quick-swap --no-header", + ) + # I don't understand why export returns the arguments + # if snapmaker_process_arguments fails. + self.assertTrue(isinstance(gcode, argparse.Namespace)) + self.assertFalse(isinstance(gcode, str)) + + gcode = self.get_gcode( + [command], + "--machine=Original --bracing-kit --no-header", + ) + # I don't understand why export returns the arguments + # if snapmaker_process_arguments fails. + self.assertTrue(isinstance(gcode, argparse.Namespace)) + self.assertFalse(isinstance(gcode, str)) + + # This is incompatible according to [2] + gcode = self.get_gcode( + [command], + "--machine=A150 --quick-swap --no-header", + ) + # I don't understand why export returns the arguments + # if snapmaker_process_arguments fails. + self.assertTrue(isinstance(gcode, argparse.Namespace)) + self.assertFalse(isinstance(gcode, str)) + + gcode = self.get_gcode( + [command], + "--machine=Artisan --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], []) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=400, Y=400, Z=400)) + + gcode = self.get_gcode( + [command], + "--machine=Artisan --quick-swap --no-header", + ) + # I don't understand why export returns the arguments + # if snapmaker_process_arguments fails. + self.assertTrue(isinstance(gcode, argparse.Namespace)) + self.assertFalse(isinstance(gcode, str)) + + gcode = self.get_gcode( + [command], + "--machine=Artisan --bracing-kit --no-header", + ) + # I don't understand why export returns the arguments + # if snapmaker_process_arguments fails. + self.assertTrue(isinstance(gcode, argparse.Namespace)) + self.assertFalse(isinstance(gcode, str)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A150 --toolhead=50W_CNC --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], []) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=145, Y=160, Z=90)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A150 --toolhead=50W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=145, Y=148, Z=90)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A250 --toolhead=50W_CNC --bracing-kit --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS", "BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=230, Y=223, Z=180)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A250T --toolhead=50W_CNC --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=230, Y=235, Z=180)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A250T --toolhead=200W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=230, Y=225, Z=180)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350 --toolhead=50W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=338, Z=275)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350 --toolhead=50W_CNC --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=335, Z=275)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350 --toolhead=50W_CNC --bracing-kit --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS", "BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=323, Z=275)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350T --toolhead=50W_CNC --bracing-kit --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS", "BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=323, Z=275)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350T --toolhead=200W_CNC --bracing-kit --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=325, Z=275)) + + # This test case is covered in reference [1] + gcode = self.get_gcode( + [command], + "--machine=A350T --toolhead=200W_CNC --bracing-kit --quick-swap --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["MOD_KITS_INSTALLED"], ["QS", "BK"]) + self.assertEqual(self.post.values["BOUNDARIES"], dict(X=320, Y=310, Z=275)) + + def test_toolhead_selection(self): + """Test automatic selection of toolhead where appropriate""" + + # check succeeds + command = Path.Command("G0 X10 Y20 Z30") + expected = "G0 X10.000 Y20.000 Z30.000" + + gcode = self.get_gcode( + [command], + "--machine=Original --no-header", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["TOOLHEAD_NAME"], "Original CNC module") + + gcode = self.get_gcode( + [command], + "--machine=A350 --no-header", + ) + self.assertFalse(isinstance(gcode, str)) + + gcode = self.get_gcode( + [command], + "--machine=A350T --no-header", + ) + self.assertFalse(isinstance(gcode, str)) + + # check succeed with artisan (which base is bigger) + gcode = self.get_gcode( + [command], + "--machine=Artisan --no-header --boundaries-check", + ) + result = gcode.splitlines()[18] + self.assertEqual(result, expected) + self.assertEqual(self.post.values["TOOLHEAD_NAME"], "200W CNC module") + + def test_spindle_percent_rpm_auto_select(self): + """Test automatic selection of spindle speed rpm vs percent""" + + command = Path.Command("M3 S2100") + + # test original toolhead + gcode = self.get_gcode([command], "--machine=Original --no-header") + self.assertEqual(gcode.splitlines()[18], "M3 P30") + + command = Path.Command("M3 S3600") + + # test 50W toolhead + gcode = self.get_gcode([command], "--machine=A350 --toolhead=50W_CNC --no-header") + self.assertEqual(gcode.splitlines()[18], "M3 P30") + + # test 200W toolhead + gcode = self.get_gcode( + [command], "--machine=A350 --toolhead=200W_CNC --bracing-kit --no-header" + ) + self.assertEqual(gcode.splitlines()[18], "M3 S3600") + + # test 200W toolhead + gcode = self.get_gcode([command], "--machine=Artisan --no-header") + self.assertEqual(gcode.splitlines()[18], "M3 S3600") + + def test_spindle_percent(self): """Test spindle speed conversion from RPM to percents""" command = Path.Command("M3 S3600") # test 50W toolhead gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=50W --spindle-percent --no-header" + [command], "--machine=A350 --toolhead=50W_CNC --spindle-percent --no-header" ) self.assertEqual(gcode.splitlines()[18], "M3 P30") # test 200W toolhead gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=200W --spindle-percent --no-header" + [command], + "--machine=A350 --toolhead=200W_CNC --bracing-kit --spindle-percent --no-header", ) self.assertEqual(gcode.splitlines()[18], "M3 P20") # test custom spindle speed extrema gcode = self.get_gcode( [command], - "--machine=A350 --toolhead=200W --spindle-percent --no-header --spindle-speeds=3000,4000", + "--machine=A350 --toolhead=200W_CNC --bracing-kit --spindle-percent --no-header --spindle-speeds=3000,4000", ) self.assertEqual(gcode.splitlines()[18], "M3 P90") @@ -265,7 +587,7 @@ M5 command = Path.Command("(comment)") gcode = self.get_gcode( - [command], "--machine=A350 --toolhead=50W --spindle-percent --no-header" + [command], "--machine=A350 --toolhead=50W_CNC --spindle-percent --no-header" ) result = gcode.splitlines()[18] expected = ";comment" @@ -279,7 +601,7 @@ M5 gcode = self.get_gcode( [command], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --boundaries-check", + "--machine=A350 --toolhead=50W_CNC --no-header --boundaries-check", ) self.assertTrue(self.post.check_boundaries(gcode.splitlines())) @@ -288,20 +610,20 @@ M5 c1 = Path.Command("G02 Y260") gcode = self.get_gcode( [c0, c1], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --boundaries-check", + "--machine=A350 --toolhead=50W_CNC --no-header --boundaries-check", ) self.assertFalse(self.post.check_boundaries(gcode.splitlines())) # check succeed with artisan (which base is bigger) gcode = self.get_gcode( [c0, c1], - "--machine=artisan --toolhead=50W --spindle-percent --no-header --boundaries-check", + "--machine=Artisan --no-header --boundaries-check", ) self.assertTrue(self.post.check_boundaries(gcode.splitlines())) # check fails with custom boundaries gcode = self.get_gcode( [c0, c1], - "--machine=A350 --toolhead=50W --spindle-percent --no-header --boundaries-check --boundaries='50,400,10'", + "--machine=A350 --toolhead=50W_CNC --no-header --boundaries-check --boundaries='50,400,10'", ) self.assertFalse(self.post.check_boundaries(gcode.splitlines())) diff --git a/src/Mod/CAM/Gui/AppPathGui.cpp b/src/Mod/CAM/Gui/AppPathGui.cpp index 856d3424c9..2dd45cb5ec 100644 --- a/src/Mod/CAM/Gui/AppPathGui.cpp +++ b/src/Mod/CAM/Gui/AppPathGui.cpp @@ -68,7 +68,7 @@ PyMOD_INIT_FUNC(PathGui) PyMOD_Return(nullptr); } PyObject* mod = PathGui::initModule(); - Base::Console().Log("Loading GUI of Path module... done\n"); + Base::Console().log("Loading GUI of Path module... done\n"); // instantiating the commands CreatePathCommands(); diff --git a/src/Mod/CAM/Gui/Command.cpp b/src/Mod/CAM/Gui/Command.cpp index 008445f387..a0b1311a2e 100644 --- a/src/Mod/CAM/Gui/Command.cpp +++ b/src/Mod/CAM/Gui/Command.cpp @@ -76,7 +76,7 @@ void CmdPathArea::activated(int iMsg) } for (const std::string& name : subnames) { if (name.compare(0, 4, "Face") && name.compare(0, 4, "Edge")) { - Base::Console().Error("Selected shape is not 2D\n"); + Base::Console().error("Selected shape is not 2D\n"); return; } @@ -159,14 +159,14 @@ void CmdPathAreaWorkplane::activated(int iMsg) getSelection().getSelectionEx(nullptr, Part::Feature::getClassTypeId())) { const std::vector& subnames = selObj.getSubNames(); if (subnames.size() > 1) { - Base::Console().Error("Please select one sub shape object for plane only\n"); + Base::Console().error("Please select one sub shape object for plane only\n"); return; } const Part::Feature* pcObj = static_cast(selObj.getObject()); if (subnames.empty()) { if (pcObj->isDerivedFrom()) { if (!areaName.empty()) { - Base::Console().Error("Please select one FeatureArea only\n"); + Base::Console().error("Please select one FeatureArea only\n"); return; } areaName = pcObj->getNameInDocument(); @@ -174,12 +174,12 @@ void CmdPathAreaWorkplane::activated(int iMsg) } for (TopExp_Explorer it(pcObj->Shape.getShape().getShape(), TopAbs_SHELL); it.More(); it.Next()) { - Base::Console().Error("Selected shape is not 2D\n"); + Base::Console().error("Selected shape is not 2D\n"); return; } } if (!planeName.empty()) { - Base::Console().Error("Please select one shape object for plane only\n"); + Base::Console().error("Please select one shape object for plane only\n"); return; } else { @@ -189,7 +189,7 @@ void CmdPathAreaWorkplane::activated(int iMsg) for (const std::string& name : subnames) { if (name.compare(0, 4, "Face") && name.compare(0, 4, "Edge")) { - Base::Console().Error("Selected shape is not 2D\n"); + Base::Console().error("Selected shape is not 2D\n"); return; } std::ostringstream subname; @@ -198,11 +198,11 @@ void CmdPathAreaWorkplane::activated(int iMsg) } } if (areaName.empty()) { - Base::Console().Error("Please select one FeatureArea\n"); + Base::Console().error("Please select one FeatureArea\n"); return; } if (planeName.empty()) { - Base::Console().Error("Please select one shape object\n"); + Base::Console().error("Please select one shape object\n"); return; } @@ -258,7 +258,7 @@ void CmdPathCompound::activated(int iMsg) cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ","; } else { - Base::Console().Error( + Base::Console().error( "Only Path objects must be selected before running this command\n"); return; } @@ -277,7 +277,7 @@ void CmdPathCompound::activated(int iMsg) updateActive(); } else { - Base::Console().Error("At least one Path object must be selected\n"); + Base::Console().error("At least one Path object must be selected\n"); return; } } @@ -320,7 +320,7 @@ void CmdPathShape::activated(int iMsg) } for (const std::string& name : subnames) { if (name.compare(0, 4, "Face") && name.compare(0, 4, "Edge")) { - Base::Console().Warning("Ignored shape %s %s\n", + Base::Console().warning("Ignored shape %s %s\n", pcObj->getNameInDocument(), name.c_str()); continue; diff --git a/src/Mod/CAM/Path/Post/UtilsParse.py b/src/Mod/CAM/Path/Post/UtilsParse.py index bf31a103d2..ec2808b706 100644 --- a/src/Mod/CAM/Path/Post/UtilsParse.py +++ b/src/Mod/CAM/Path/Post/UtilsParse.py @@ -174,11 +174,12 @@ def check_for_tool_change( gcode.append(f"{linenumber(values)}M5{nl}") for line in values["TOOL_CHANGE"].splitlines(False): gcode.append(f"{linenumber(values)}{line}{nl}") - elif values["OUTPUT_COMMENTS"]: + return False + if values["OUTPUT_COMMENTS"]: # convert the tool change to a comment comment = create_comment(values, format_command_line(values, command_line)) gcode.append(f"{linenumber(values)}{comment}{nl}") - return True + return True return False diff --git a/src/Mod/CAM/Path/Post/scripts/KineticNCBeamicon2_post.py b/src/Mod/CAM/Path/Post/scripts/KineticNCBeamicon2_post.py index a9f0e083dc..3008d6e032 100644 --- a/src/Mod/CAM/Path/Post/scripts/KineticNCBeamicon2_post.py +++ b/src/Mod/CAM/Path/Post/scripts/KineticNCBeamicon2_post.py @@ -56,7 +56,10 @@ KineticNCBeamicon2_post.export(object,"/path/to/file.ncc","") now = datetime.datetime.now() -parser = argparse.ArgumentParser(prog="linuxcnc", add_help=False) +parser = argparse.ArgumentParser( + prog="linuxcnc", + add_help=False, +) parser.add_argument("--no-header", action="store_true", help="suppress header output") parser.add_argument("--no-comments", action="store_true", help="suppress comment output") parser.add_argument("--line-numbers", action="store_true", help="prefix with line numbers") @@ -68,11 +71,11 @@ parser.add_argument( parser.add_argument("--precision", default="3", help="number of digits of precision, default=3") parser.add_argument( "--preamble", - help='set commands to be issued before the first command, default="%\\nG17 G21 G40 G49 G80 G90\\nM08\\n"', + help=r'set commands to be issued before the first command, default="%%\nG17 G21 G40 G49 G80 G90\nM08\n"', ) parser.add_argument( "--postamble", - help='set commands to be issued after the last command, default="M05 M09\\nG17 G90 G80 G40\\nM30\\n"', + help=r'set commands to be issued after the last command, default="M05 M09\nG17 G90 G80 G40\nM30\n"', ) parser.add_argument( "--inches", action="store_true", help="Convert output for US imperial mode (G20)" diff --git a/src/Mod/CAM/Path/Post/scripts/snapmaker_post.py b/src/Mod/CAM/Path/Post/scripts/snapmaker_post.py index 7606c18276..925f406bba 100644 --- a/src/Mod/CAM/Path/Post/scripts/snapmaker_post.py +++ b/src/Mod/CAM/Path/Post/scripts/snapmaker_post.py @@ -9,7 +9,7 @@ # * Any redistribution must include the specific provision above. * # * * # * You may obtain a copy of the Licence at: * -# * https://joinup.ec.europa.eu/software/page/eupl5 * +# * https://interoperable-europe.ec.europa.eu/collection/eupl/eupl-text-eupl-12 * # * * # * Unless required by applicable law or agreed to in writing, software * # * distributed under the Licence is distributed on an "AS IS" basis, * @@ -21,12 +21,13 @@ import argparse import base64 +import copy import datetime import os import pathlib import re import tempfile -from typing import Any +from typing import Any, List, Tuple import FreeCAD import Path @@ -45,18 +46,156 @@ if DEBUG := False: else: Path.Log.setLevel(Path.Log.Level.INFO, Path.Log.thisModule()) + +def convert_option_to_attr(option_name): + # transforms argparse options into identifiers + if option_name.startswith("--"): + option_name = option_name[2:] + elif option_name.startswith("-"): + option_name = option_name[1:] + + return option_name.replace("-", "_") + + SNAPMAKER_MACHINES = dict( - original=dict(name="Snapmaker Original", X=90, Y=90, Z=50), - original_z_extension=dict(name="Snapmaker Original with Z extension", X=90, Y=90, Z=146), - a150=dict(name="A150", X=160, Y=160, Z=90), - **dict.fromkeys(("A250", "A250T"), dict(name="Snapmaker 2 A250(T)", X=230, Y=250, Z=180)), - **dict.fromkeys(("A350", "A350T"), dict(name="Snapmaker 2 A350(T)", X=320, Y=350, Z=275)), - artisan=dict(name="Snapmaker Artisan", X=400, Y=400, Z=400), + Original=dict( + key="Original", + name="Snapmaker Original", + boundaries_table=[ + # https://forum.snapmaker.com/t/cnc-work-area-size/5178 + dict(boundaries=dict(X=125, Y=125, Z=50), toolhead="Original_CNC", mods=set()), + ], + lead=dict(X=8, Y=8, Z=8), # Linear module screw pitch (mm/turn) + ), + Original_Z_Extension=dict( + key="Original_Z_Extension", + name="Snapmaker Original with Z extension", + boundaries_table=[ + # https://forum.snapmaker.com/t/cnc-work-area-size/5178 + dict(boundaries=dict(X=125, Y=125, Z=146), toolhead="Original_CNC", mods=set()), + ], + lead=dict(X=8, Y=8, Z=8), # Linear module screw pitch (mm/turn) + ), + A150=dict( + key="A150", + name="Snapmaker 2 A150", + boundaries_table=[ + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + dict(boundaries=dict(X=145, Y=160, Z=90), toolhead="50W_CNC", mods=set()), + dict(boundaries=dict(X=145, Y=148, Z=90), toolhead="50W_CNC", mods={"BK"}), + ], + lead=dict(X=8, Y=8, Z=8), # Linear module screw pitch (mm/turn) + ), + A250=dict( + key="A250", + name="Snapmaker 2 A250", + boundaries_table=[ + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + dict(boundaries=dict(X=230, Y=250, Z=180), toolhead="50W_CNC", mods=set()), + dict(boundaries=dict(X=230, Y=238, Z=180), toolhead="50W_CNC", mods={"BK"}), + dict(boundaries=dict(X=230, Y=235, Z=180), toolhead="50W_CNC", mods={"QS"}), + dict(boundaries=dict(X=230, Y=223, Z=180), toolhead="50W_CNC", mods={"BK", "QS"}), + dict(boundaries=dict(X=230, Y=225, Z=180), toolhead="200W_CNC", mods={"BK"}), + dict(boundaries=dict(X=230, Y=210, Z=180), toolhead="200W_CNC", mods={"BK", "QS"}), + ], + lead=dict(X=8, Y=8, Z=8), # Linear module screw pitch (mm/turn) + ), + A250T=dict( + key="A250T", + name="Snapmaker 2 A250T", + boundaries_table=[ + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + dict(boundaries=dict(X=230, Y=250, Z=180), toolhead="50W_CNC", mods=set()), + dict(boundaries=dict(X=230, Y=238, Z=180), toolhead="50W_CNC", mods={"BK"}), + dict(boundaries=dict(X=230, Y=235, Z=180), toolhead="50W_CNC", mods={"QS"}), + dict(boundaries=dict(X=230, Y=223, Z=180), toolhead="50W_CNC", mods={"BK", "QS"}), + dict(boundaries=dict(X=230, Y=225, Z=180), toolhead="200W_CNC", mods={"BK"}), + dict(boundaries=dict(X=230, Y=210, Z=180), toolhead="200W_CNC", mods={"BK", "QS"}), + ], + lead=dict(X=20, Y=20, Z=8), # Linear module screw pitch (mm/turn) + ), + A350=dict( + key="A350", + name="Snapmaker 2 A350", + boundaries_table=[ + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + dict(boundaries=dict(X=320, Y=350, Z=275), toolhead="50W_CNC", mods=set()), + dict(boundaries=dict(X=320, Y=338, Z=275), toolhead="50W_CNC", mods={"BK"}), + dict(boundaries=dict(X=320, Y=335, Z=275), toolhead="50W_CNC", mods={"QS"}), + dict(boundaries=dict(X=320, Y=323, Z=275), toolhead="50W_CNC", mods={"BK", "QS"}), + dict(boundaries=dict(X=320, Y=325, Z=275), toolhead="200W_CNC", mods={"BK"}), + dict(boundaries=dict(X=320, Y=310, Z=275), toolhead="200W_CNC", mods={"BK", "QS"}), + ], + lead=dict(X=8, Y=8, Z=8), # Linear module screw pitch (mm/turn) + ), + A350T=dict( + key="A350T", + name="Snapmaker 2 A350T", + boundaries_table=[ + # [1] https://support.snapmaker.com/hc/en-us/articles/20786910972311-FAQ-for-Bracing-Kit-for-Snapmaker-2-0-Linear-Modules#h_01HN4Z7S9WJE5BRT492WR0CKH1 + dict(boundaries=dict(X=320, Y=350, Z=275), toolhead="50W_CNC", mods=set()), + dict(boundaries=dict(X=320, Y=338, Z=275), toolhead="50W_CNC", mods={"BK"}), + dict(boundaries=dict(X=320, Y=335, Z=275), toolhead="50W_CNC", mods={"QS"}), + dict(boundaries=dict(X=320, Y=323, Z=275), toolhead="50W_CNC", mods={"BK", "QS"}), + dict(boundaries=dict(X=320, Y=325, Z=275), toolhead="200W_CNC", mods={"BK"}), + dict(boundaries=dict(X=320, Y=310, Z=275), toolhead="200W_CNC", mods={"BK", "QS"}), + ], + lead=dict(X=20, Y=20, Z=8), # Linear module screw pitch (mm/turn) + ), + Artisan=dict( + key="Artisan", + name="Snapmaker Artisan", + boundaries_table=[ + dict(boundaries=dict(X=400, Y=400, Z=400), toolhead="200W_CNC", mods=set()), + ], + lead=dict(X=40, Y=40, Z=8), # Linear module screw pitch (mm/turn) + ), ) +# These modifications were released to upgrade the Snapmaker 2.0 machines +# which started on Kickstarter. +SNAPMAKER_MOD_KITS = { + "QS": dict( + key="QS", + name="Quick Swap Kit", + option_name="--quick-swap", + option_help_text="Indicates that the quick swap kit is installed. Only compatible with Snapmaker 2 machines.", + ), + "BK": dict( + key="BK", + name="Bracing Kit", + option_name="--bracing-kit", + option_help_text="Indicates that the bracing kit is installed. Only compatible with Snapmaker 2 machines.", + ), +} + +# Could support other types of toolheads (laser, drag knife, 3DP, ...) in the future +# https://wiki.snapmaker.com/en/Snapmaker_Luban/manual/2_supported_gcode_references#m3m4-modified-cnclaser-on SNAPMAKER_TOOLHEADS = { - "50W": dict(name="50W CNC module", min=0, max=12000, percent=True), - "200W": dict(name="200W CNC module", min=8000, max=18000, percent=False), + "Original_CNC": dict( + key="Original_CNC", + name="Original CNC module", + speed_rpm=dict(min=0, max=7000), + boundaries_delta=dict(X=0, Y=0, Z=0), + has_percent=True, + has_speed_s=False, + ), + "50W_CNC": dict( + key="50W_CNC", + name="50W CNC module", + speed_rpm=dict(min=0, max=12000), + boundaries_delta=dict(X=0, Y=0, Z=0), + has_percent=True, + has_speed_s=False, + ), + "200W_CNC": dict( + key="200W_CNC", + name="200W CNC module", + speed_rpm=dict(min=0, max=18000), + boundaries_delta=dict(X=0, Y=-13, Z=0), + has_percent=True, + has_speed_s=True, + ), } @@ -65,7 +204,7 @@ class CoordinatesAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): match = re.match( - "^\s*(?P-?\d+\.?\d*),?\s*(?P-?\d+\.?\d*),?\s*(?P-?\d+\.?\d*)\s*$", values + r"^\s*(?P-?\d+\.?\d*),?\s*(?P-?\d+\.?\d*),?\s*(?P-?\d+\.?\d*)\s*$", values ) if match: # setattr(namespace, self.dest, 'G0 X{0} Y{1} Z{2}'.format(*match.groups())) @@ -79,7 +218,7 @@ class ExtremaAction(argparse.Action): """argparse Action to handle integer extrema (min,max)""" def __call__(self, parser, namespace, values, option_string=None): - if match := re.match("^ *(\d+),? *(\d+) *$", values): + if match := re.match(r"^ *(\d+),? *(\d+) *$", values): # setattr(namespace, self.dest, 'G0 X{0} Y{1} Z{2}'.format(*match.groups())) params = { key: int(value) @@ -144,7 +283,7 @@ class Snapmaker(Path.Post.Processor.PostProcessor): self.values["END_OF_LINE_CHARACTERS"] = "\n" self.values["FINISH_LABEL"] = "End" self.values["LINE_INCREMENT"] = 1 - self.values["MACHINE_NAME"] = "Generic Snapmaker" + self.values["MACHINE_NAME"] = None self.values["MODAL"] = False self.values["OUTPUT_PATH_LABELS"] = True self.values["OUTPUT_HEADER"] = ( @@ -171,7 +310,7 @@ class Snapmaker(Path.Post.Processor.PostProcessor): "P", "O", ] - self.values["PREAMBLE"] = f"""G90\nG17""" + self.values["PREAMBLE"] = """G90\nG17""" self.values["PRE_OPERATION"] = """""" self.values["POST_OPERATION"] = """""" self.values["POSTAMBLE"] = """M400\nM5""" @@ -187,17 +326,11 @@ class Snapmaker(Path.Post.Processor.PostProcessor): self.values["BOUNDARIES"] = None self.values["BOUNDARIES_CHECK"] = False self.values["MACHINES"] = SNAPMAKER_MACHINES + self.values["MOD_KITS_ALL"] = SNAPMAKER_MOD_KITS self.values["TOOLHEADS"] = SNAPMAKER_TOOLHEADS - # default toolhead is 50W (the weakest one) - self.values["DEFAULT_TOOLHEAD"] = "50W" - self.values["TOOLHEAD_NAME"] = SNAPMAKER_TOOLHEADS[self.values["DEFAULT_TOOLHEAD"]]["name"] - self.values["SPINDLE_SPEEDS"] = dict( - min=SNAPMAKER_TOOLHEADS[self.values["DEFAULT_TOOLHEAD"]]["min"], - max=SNAPMAKER_TOOLHEADS[self.values["DEFAULT_TOOLHEAD"]]["max"], - ) - self.values["SPINDLE_PERCENT"] = SNAPMAKER_TOOLHEADS[self.values["DEFAULT_TOOLHEAD"]][ - "percent" - ] + self.values["TOOLHEAD_NAME"] = None + self.values["SPINDLE_SPEEDS"] = dict() + self.values["SPINDLE_PERCENT"] = None def snapmaker_init_argument_defaults(self) -> None: """Initialize which arguments (in a pair) are shown as the default argument.""" @@ -210,7 +343,6 @@ class Snapmaker(Path.Post.Processor.PostProcessor): self.argument_defaults["thumbnail"] = True self.argument_defaults["gui"] = True self.argument_defaults["boundaries-check"] = True - self.argument_defaults["spindle-percent"] = True def snapmaker_init_arguments_visible(self) -> None: """Initialize which argument pairs are visible in TOOLTIP_ARGS.""" @@ -286,21 +418,30 @@ class Snapmaker(Path.Post.Processor.PostProcessor): "--boundaries", action=CoordinatesAction, default=None, - help='Custom boundaries (e.g. "100, 200, 300"). Overrides --machine', + help='Custom boundaries (e.g. "100, 200, 300"). Overrides boundaries from --machine', ) group.add_argument( "--machine", default=None, + required=True, choices=self.values["MACHINES"].keys(), - help=f"Snapmaker machine", + help=f"Snapmaker machine. Choose from [{self.values['MACHINES'].keys()}].", ) + for key, value in SNAPMAKER_MOD_KITS.items(): + group.add_argument( + value["option_name"], + default=False, + action="store_true", + help=value["option_help_text"], + ) + group.add_argument( "--toolhead", default=None, choices=self.values["TOOLHEADS"].keys(), - help=f"Snapmaker toolhead", + help=f"Snapmaker toolhead. Choose from [{self.values['TOOLHEADS'].keys()}].", ) group.add_argument( @@ -313,14 +454,8 @@ class Snapmaker(Path.Post.Processor.PostProcessor): group.add_argument( "--spindle-percent", action="store_true", - default=argument_defaults["spindle-percent"], - help="use percent as toolhead spindle speed unit", - ) - group.add_argument( - "--spindle-rpm", - action="store_false", - dest="spindle_percent", - help="Use RPM as toolhead spindle speed unit", + default=None, + help="use percent as toolhead spindle speed unit (default: use RPM if supported by toolhead, otherwise percent)", ) group.add_argument( @@ -339,7 +474,9 @@ class Snapmaker(Path.Post.Processor.PostProcessor): return parser - def snapmaker_process_arguments(self, filename: str = "-") -> (bool, str | argparse.Namespace): + def snapmaker_process_arguments( + self, filename: str = "-" + ) -> Tuple[bool, str | argparse.Namespace]: """Process any arguments to the postprocessor.""" (flag, args) = Path.Post.UtilsArguments.process_shared_arguments( self.values, self.parser, self._job.PostProcessorArgs, self.visible_parser, filename @@ -347,38 +484,103 @@ class Snapmaker(Path.Post.Processor.PostProcessor): if flag: # process extra arguments only if flag is True self._units = self.values["UNITS"] - if args.machine: - machine = self.values["MACHINES"][args.machine] - self.values["MACHINE_NAME"] = machine["name"] - self.values["BOUNDARIES"] = {key: machine[key] for key in ("X", "Y", "Z")} + # --machine is a required "option" + machine = self.values["MACHINES"][args.machine] + self.values["MACHINE_KEY"] = machine["key"] + self.values["MACHINE_NAME"] = machine["name"] - if args.boundaries: # may override machine boundaries, which is expected - self.values["BOUNDARIES"] = args.boundaries + compatible_toolheads = {bt["toolhead"] for bt in machine["boundaries_table"]} if args.toolhead: + if args.toolhead not in compatible_toolheads: + FreeCAD.Console.PrintError( + f"Selected --toolhead={args.toolhead} is not compatible with machine {machine['name']}." + + f" Choose from [{compatible_toolheads}]\n" + ) + flag = False + return (flag, args) toolhead = self.values["TOOLHEADS"][args.toolhead] - self.values["TOOLHEAD_NAME"] = toolhead["name"] + elif len(compatible_toolheads) == 1: + toolhead_key = next(iter(compatible_toolheads)) + toolhead = self.values["TOOLHEADS"][toolhead_key] else: - FreeCAD.Console.PrintWarning( - f'No toolhead selected, using default ({self.values["TOOLHEAD_NAME"]}). ' - f"Consider adding --toolhead\n" + FreeCAD.Console.PrintError( + f"Machine {machine['name']} has multiple compatible toolheads:\n" + f"{compatible_toolheads}\n" + "Please add --toolhead argument.\n" ) - toolhead = self.values["TOOLHEADS"][self.values["DEFAULT_TOOLHEAD"]] + flag = False + return (flag, args) + self.values["TOOLHEAD_KEY"] = toolhead["key"] + self.values["TOOLHEAD_NAME"] = toolhead["name"] - self.values["SPINDLE_SPEEDS"] = {key: toolhead[key] for key in ("min", "max")} + self.values["SPINDLE_SPEEDS"] = toolhead["speed_rpm"] if args.spindle_speeds: # may override toolhead value, which is expected self.values["SPINDLE_SPEEDS"] = args.spindle_speeds if args.spindle_percent is not None: - if toolhead["percent"] is True: + if toolhead["has_percent"]: self.values["SPINDLE_PERCENT"] = True - if args.spindle_percent is False: - FreeCAD.Console.PrintWarning( - f"Toolhead does not handle RPM spindle speed, using percents instead.\n" - ) else: - self.values["SPINDLE_PERCENT"] = args.spindle_percent + FreeCAD.Console.PrintError( + f"Requested spindle speed in percent, but toolhead {toolhead['name']}" + + " does not support speed as percent.\n" + ) + flag = False + return (flag, args) + else: + # Prefer speed S over percent P + self.values["SPINDLE_PERCENT"] = ( + toolhead["has_percent"] and not toolhead["has_speed_s"] + ) + if self.values["SPINDLE_PERCENT"]: + FreeCAD.Console.PrintWarning( + "Spindle speed will be controlled using using percentages.\n" + ) + else: + FreeCAD.Console.PrintWarning("Spindle speed will be controlled using using RPM.\n") + + self.values["MOD_KITS_INSTALLED"] = [] + if args.boundaries: # may override machine boundaries, which is expected + self.values["BOUNDARIES"] = args.boundaries + self.values["MACHINE_NAME"] += " Boundaries overide=" + str(args.boundaries) + else: + compatible_modkit_combos = [ + bt["mods"] + for bt in machine["boundaries_table"] + if toolhead["key"] == bt["toolhead"] + ] + configured_modkits = set() + + # Determine which mod kits are requested from the options + for mod_kit in self.values["MOD_KITS_ALL"].values(): + if getattr(args, convert_option_to_attr(mod_kit["option_name"])): + configured_modkits.add(mod_kit["key"]) + self.values["MACHINE_NAME"] += " " + mod_kit["name"] + self.values["MOD_KITS_INSTALLED"].append(mod_kit["key"]) + + if configured_modkits not in compatible_modkit_combos: + FreeCAD.Console.PrintError( + f"Machine {machine['name']} with toolhead {toolhead['name']}" + + f" is not compatible with modkit {configured_modkits if configured_modkits else None}.\n" + + f" Choose from {compatible_modkit_combos}." + ) + flag = False + return (flag, args) + + # Update machine dimensions based on installed toolhead and mod kits + boundaries_table_entry_l = [ + bt + for bt in machine["boundaries_table"] + if bt["toolhead"] == toolhead["key"] and bt["mods"] == configured_modkits + ] + assert len(boundaries_table_entry_l) == 1 + boundaries_table_entry = boundaries_table_entry_l[0] + + # The deepcopy is necessary to avoid modifying the boundaries in the MACHINES dict. + self.values["BOUNDARIES"] = copy.deepcopy(boundaries_table_entry["boundaries"]) + self.values["MACHINE_NAME"] += " " + toolhead["name"] self.values["THUMBNAIL"] = args.thumbnail self.values["ALLOW_GUI"] = args.gui @@ -393,9 +595,9 @@ class Snapmaker(Path.Post.Processor.PostProcessor): return flag, args - def snapmaker_process_postables(self, filename: str = "-") -> [(str, str)]: + def snapmaker_process_postables(self, filename: str = "-") -> List[Tuple[str, str]]: """process job sections to gcode""" - sections: [(str, str)] = list() + sections: List[Tuple[str, str]] = list() postables = self._buildPostList() @@ -468,11 +670,9 @@ class Snapmaker(Path.Post.Processor.PostProcessor): return f"thumbnail: data:image/png;base64,{base64.b64encode(data).decode()}" - def output_header(self, gcode: [[]]): + def output_header(self, gcode: List[str]): """custom method derived from Path.Post.UtilsExport.output_header""" cam_file: str - comment: str - nl: str = "\n" if not self.values["OUTPUT_HEADER"]: return @@ -486,28 +686,26 @@ class Snapmaker(Path.Post.Processor.PostProcessor): add_comment("Header Start") add_comment("header_type: cnc") add_comment(f'machine: {self.values["MACHINE_NAME"]}') - comment = Path.Post.UtilsParse.create_comment( - self.values, f'Post Processor: {self.values["POSTPROCESSOR_FILE_NAME"]}' - ) - gcode.append(f"{Path.Post.UtilsParse.linenumber(self.values)}{comment}{nl}") + add_comment(f'Post Processor: {self.values["POSTPROCESSOR_FILE_NAME"]}') if FreeCAD.ActiveDocument: cam_file = os.path.basename(FreeCAD.ActiveDocument.FileName) else: cam_file = "" - add_comment(f"Cam File: {cam_file}") + add_comment(f"CAM File: {cam_file}") add_comment(f"Output Time: {datetime.datetime.now()}") add_comment(self.get_thumbnail()) - def convert_spindle(self, gcode: [str]) -> [str]: + def convert_spindle(self, gcode: List[str]) -> List[str]: """convert spindle speed values from RPM to percent (%) (M3/M4 commands)""" if self.values["SPINDLE_PERCENT"] is False: - return + return gcode - # TODO: check if percentage covers range 0-max (most probable) or min-max (200W has a documented min speed) + # https://wiki.snapmaker.com/en/Snapmaker_Luban/manual/2_supported_gcode_references#m3m4-modified-cnclaser-on + # Speed as percentage in [0,100]% range for index, commandline in enumerate( gcode ): # .split(self.values["END_OF_LINE_CHARACTERS"]): - if match := re.match("(?PM0?[34])\D.*(?PS\d+.?\d*)", commandline): + if match := re.match(r"(?PM0?[34])\D.*(?PS\d+.?\d*)", commandline): percent = ( float(match.group("spindle")[1:]) * 100 / self.values["SPINDLE_SPEEDS"]["max"] ) @@ -518,7 +716,7 @@ class Snapmaker(Path.Post.Processor.PostProcessor): ) return gcode - def check_boundaries(self, gcode: [str]) -> bool: + def check_boundaries(self, gcode: List[str]) -> bool: """Check boundaries and return whether it succeeded""" status = True FreeCAD.Console.PrintLog("Boundaries check\n") @@ -528,23 +726,23 @@ class Snapmaker(Path.Post.Processor.PostProcessor): relative = False for index, commandline in enumerate(gcode): - if re.match("G90(?:\D|$)", commandline): + if re.match(r"G90(?:\D|$)", commandline): relative = False - elif re.match("G91(?:\D|$)", commandline): + elif re.match(r"G91(?:\D|$)", commandline): relative = True - elif re.match("G0?[12](?:\D|$)", commandline): + elif re.match(r"G0?[12](?:\D|$)", commandline): for axis, value in re.findall( - "(?P[XYZ])(?P-?\d+\.?\d*)(?:\D|$)", commandline + r"(?P[XYZ])(?P-?\d+\.?\d*)(?:\D|$)", commandline ): if relative: position[axis] += float(value) else: position[axis] = float(value) - extrema[axis][0] = max(extrema[axis][0], position[axis]) - extrema[axis][1] = min(extrema[axis][1], position[axis]) + extrema[axis][0] = min(extrema[axis][0], position[axis]) + extrema[axis][1] = max(extrema[axis][1], position[axis]) for axis in extrema.keys(): - if abs(extrema[axis][0] - extrema[axis][1]) > self.values["BOUNDARIES"][axis]: + if abs(extrema[axis][1] - extrema[axis][0]) > self.values["BOUNDARIES"][axis]: # gcode.insert(0, f';WARNING: Boundary check: job exceeds machine limit on {axis} axis{self.values["END_OF_LINE_CHARACTERS"]}') FreeCAD.Console.PrintWarning( f"Boundary check: job exceeds machine limit on {axis} axis\n" @@ -553,10 +751,10 @@ class Snapmaker(Path.Post.Processor.PostProcessor): return status - def export_common(self, objects: list, filename: str | pathlib.Path) -> str: + def export_common(self, objects: List, filename: str | pathlib.Path) -> str: """custom method derived from Path.Post.UtilsExport.export_common""" final: str - gcode: [[]] = [] + gcode: List = [] result: bool for obj in objects: diff --git a/src/Mod/CAM/PathSimulator/App/AppPathSimulator.cpp b/src/Mod/CAM/PathSimulator/App/AppPathSimulator.cpp index 3b8d1dcf5b..de91800d12 100644 --- a/src/Mod/CAM/PathSimulator/App/AppPathSimulator.cpp +++ b/src/Mod/CAM/PathSimulator/App/AppPathSimulator.cpp @@ -71,7 +71,7 @@ PyMOD_INIT_FUNC(PathSimulator) // PyObject* mod = PathSimulator::initModule(); - Base::Console().Log("Loading PathSimulator module.... done\n"); + Base::Console().log("Loading PathSimulator module.... done\n"); // Add Types to module Base::Interpreter().addType(&PathSimulator::PathSimPy::Type, mod, "PathSim"); diff --git a/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp b/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp index 3df111fb77..631e6dc4e6 100644 --- a/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp +++ b/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp @@ -134,7 +134,7 @@ PyObject* PathSimPy::ApplyCommand(PyObject* args, PyObject* kwds) Base::Placement* pos = static_cast(pObjPlace)->getPlacementPtr(); Path::Command* cmd = static_cast(pObjCmd)->getCommandPtr(); Base::Placement* newpos = sim->ApplyCommand(pos, cmd); - // Base::Console().Log("Done...\n"); + // Base::Console().log("Done...\n"); // Base::Console().Refresh(); Base::PlacementPy* newposPy = new Base::PlacementPy(newpos); return newposPy; diff --git a/src/Mod/CAM/PathSimulator/App/VolSim.cpp b/src/Mod/CAM/PathSimulator/App/VolSim.cpp index b915b64ee4..7d45033b35 100644 --- a/src/Mod/CAM/PathSimulator/App/VolSim.cpp +++ b/src/Mod/CAM/PathSimulator/App/VolSim.cpp @@ -777,7 +777,7 @@ cSimTool::cSimTool(const TopoDS_Shape& toolShape, float res) // Report the performance of the profile extraction // auto stop = std::chrono::high_resolution_clock::now(); // auto duration = std::chrono::duration_cast(stop - start); - // Base::Console().Log("cSimTool::cSimTool - Tool Profile Extraction Took: %i ms\n", + // Base::Console().log("cSimTool::cSimTool - Tool Profile Extraction Took: %i ms\n", // duration.count() / 1000); } diff --git a/src/Mod/CAM/PathSimulator/AppGL/AppCAMSimulator.cpp b/src/Mod/CAM/PathSimulator/AppGL/AppCAMSimulator.cpp index 8f9ce1d39e..c50b397d52 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/AppCAMSimulator.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/AppCAMSimulator.cpp @@ -71,7 +71,7 @@ PyMOD_INIT_FUNC(CAMSimulator) // PyObject* mod = CAMSimulator::initModule(); - Base::Console().Log("Loading CAMSimulator module.... done\n"); + Base::Console().log("Loading CAMSimulator module.... done\n"); // Add Types to module Base::Interpreter().addType(&CAMSimulator::CAMSimPy::Type, mod, "PathSim"); diff --git a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp index 59806559c6..ed977309cb 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp @@ -329,6 +329,7 @@ DlgCAMSimulator* DlgCAMSimulator::GetInstance() mInstance->setModality(Qt::ApplicationModal); mInstance->setMinimumWidth(700); mInstance->setMinimumHeight(400); + mInstance->setTitle(tr("FreeCAD CAM Simulator")); } return mInstance; } diff --git a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp index b7d6cb6a88..916be69f25 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp @@ -24,6 +24,10 @@ #include "OpenGlWrapper.h" #include "MillSimulation.h" #include +#include +#include +#include + using namespace MillSim; @@ -69,6 +73,9 @@ void GuiDisplay::UpdateProjection() mat4x4_ortho(projmat, 0, gWindowSizeW, gWindowSizeH, 0, -1, 1); mShader.Activate(); mShader.UpdateProjectionMat(projmat); + mThumbMaxMotion = guiItems[eGuiItemView].posx() - guiItems[eGuiItemSlider].posx() + - guiItems[eGuiItemThumb].texItem.w; + HStretchGlItem(&(guiItems[eGuiItemSlider]), mThumbMaxMotion, 10.0f); } bool GuiDisplay::GenerateGlItem(GuiItem* guiItem) @@ -108,6 +115,63 @@ bool GuiDisplay::GenerateGlItem(GuiItem* guiItem) return true; } +bool MillSim::GuiDisplay::HStretchGlItem(GuiItem* guiItem, float newWidth, float edgeWidth) +{ + if (guiItem->vbo == 0) { + return false; + } + + DestroyGlItem(guiItem); + Vertex2D verts[12]; + + int x = guiItem->texItem.tx; + int y = guiItem->texItem.ty; + int h = guiItem->texItem.h; + int w = guiItem->texItem.w; + + // left edge + verts[0] = {0, (float)h, mTexture.getTexX(x), mTexture.getTexY(y + h)}; + verts[1] = {edgeWidth, (float)h, mTexture.getTexX(x + edgeWidth), mTexture.getTexY(y + h)}; + verts[2] = {0, 0, mTexture.getTexX(x), mTexture.getTexY(y)}; + verts[3] = {edgeWidth, 0, mTexture.getTexX(x + edgeWidth), mTexture.getTexY(y)}; + + // right edge + float px = newWidth - edgeWidth; + verts[4] = {px, (float)h, mTexture.getTexX(x + w - edgeWidth), mTexture.getTexY(y + h)}; + verts[5] = {newWidth, (float)h, mTexture.getTexX(x + w), mTexture.getTexY(y + h)}; + verts[6] = {px, 0, mTexture.getTexX(x + w - edgeWidth), mTexture.getTexY(y)}; + verts[7] = {newWidth, 0, mTexture.getTexX(x + w), mTexture.getTexY(y)}; + + // center + verts[8] = {edgeWidth, (float)h, mTexture.getTexX(x + edgeWidth), mTexture.getTexY(y + h)}; + verts[9] = {px, (float)h, mTexture.getTexX(x + w - edgeWidth), mTexture.getTexY(y + h)}; + verts[10] = {edgeWidth, 0, mTexture.getTexX(x + edgeWidth), mTexture.getTexY(y)}; + verts[11] = {px, 0, mTexture.getTexX(x + w - edgeWidth), mTexture.getTexY(y)}; + + guiItem->flags |= GUIITEM_STRETCHED; + + // vertex buffer + glGenBuffers(1, &(guiItem->vbo)); + glBindBuffer(GL_ARRAY_BUFFER, guiItem->vbo); + glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(Vertex2D), verts, GL_STATIC_DRAW); + + glGenVertexArrays(1, &(guiItem->vao)); + glBindVertexArray(guiItem->vao); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, x)); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(Vertex2D), + (void*)offsetof(Vertex2D, tx)); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo); + glBindVertexArray(0); + + return true; +} + void GuiDisplay::DestroyGlItem(GuiItem* guiItem) { GLDELETE_BUFFER((guiItem->vbo)); @@ -120,10 +184,11 @@ bool GuiDisplay::InitGui() return true; } // index buffer + SetupTooltips(); glGenBuffers(1, &mIbo); - GLshort indices[6] = {0, 2, 3, 0, 3, 1}; + GLshort indices[18] = {0, 2, 3, 0, 3, 1, 4, 6, 7, 4, 7, 5, 8, 10, 11, 8, 11, 9}; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLushort), indices, GL_STATIC_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, 18 * sizeof(GLushort), indices, GL_STATIC_DRAW); TextureLoader tLoader(":/gl_simulator/", guiFileNames, TEX_SIZE); unsigned int* buffer = tLoader.GetRawData(); if (buffer == nullptr) { @@ -186,11 +251,35 @@ void GuiDisplay::RenderItem(int itemId) glBindVertexArray(item->vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo); - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr); + int nTriangles = (item->flags & GUIITEM_STRETCHED) == 0 ? 6 : 18; + glDrawElements(GL_TRIANGLES, nTriangles, GL_UNSIGNED_SHORT, nullptr); +} + +void MillSim::GuiDisplay::SetupTooltips() +{ + guiItems[eGuiItemPause].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Pause simulation", nullptr); + guiItems[eGuiItemPlay].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Play simulation", nullptr); + guiItems[eGuiItemSingleStep].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Single step simulation", nullptr); + guiItems[eGuiItemFaster].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Change simulation speed", nullptr); + guiItems[eGuiItemPath].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Show/Hide tool path", nullptr); + guiItems[eGuiItemRotate].toolTip = QCoreApplication::translate("CAM:Simulator:Tooltips", + "Toggle turn table animation", + nullptr); + guiItems[eGuiItemAmbientOclusion].toolTip = + QCoreApplication::translate("CAM:Simulator:Tooltips", "Toggle ambient oclusion", nullptr); + guiItems[eGuiItemView].toolTip = QCoreApplication::translate("CAM:Simulator:Tooltips", + "Toggle view simulation/model", + nullptr); } void GuiDisplay::MouseCursorPos(int x, int y) { + GuiItem* prevMouseOver = mMouseOverItem; mMouseOverItem = nullptr; for (unsigned int i = 0; i < NUM_GUI_ITEMS; i++) { GuiItem* g = &(guiItems[i]); @@ -206,6 +295,16 @@ void GuiDisplay::MouseCursorPos(int x, int y) mMouseOverItem = g; } } + if (mMouseOverItem != prevMouseOver) { + if (mMouseOverItem != nullptr && !mMouseOverItem->toolTip.isEmpty()) { + QPoint pos(x, y); + QPoint globPos = CAMSimulator::DlgCAMSimulator::GetInstance()->mapToGlobal(pos); + QToolTip::showText(globPos, mMouseOverItem->toolTip); + } + else { + QToolTip::hideText(); + } + } } void MillSim::GuiDisplay::HandleActionItem(GuiItem* guiItem) diff --git a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.h b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.h index b6ad0fb5bd..567cb42c38 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.h +++ b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.h @@ -27,6 +27,7 @@ #include "Shader.h" #include "TextureLoader.h" #include "GlUtils.h" +#include namespace MillSim { @@ -61,6 +62,7 @@ struct GuiItem unsigned int flags {}; bool mouseOver {}; TextureItem texItem {}; + QString toolTip; int posx() { @@ -82,6 +84,7 @@ struct GuiItem #define GUIITEM_CHECKABLE 0x01 #define GUIITEM_CHECKED 0x02 +#define GUIITEM_STRETCHED 0x04 struct Vertex2D @@ -117,8 +120,10 @@ public: private: void UpdateProjection(); bool GenerateGlItem(GuiItem* guiItem); + bool HStretchGlItem(GuiItem* guiItem, float newWidth, float edgeWidth); void DestroyGlItem(GuiItem* guiItem); void RenderItem(int itemId); + void SetupTooltips(); vec3 mStdColor = {0.8f, 0.8f, 0.4f}; vec3 mToggleColor = {0.9f, 0.6f, 0.2f}; diff --git a/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp b/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp index a59adb12aa..2a166343eb 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp @@ -79,6 +79,9 @@ void MillSimulation::SimNext() if (mCurStep < mNTotalSteps) { mCurStep += mSimSpeed; + if (mCurStep > mNTotalSteps) { + mCurStep = mNTotalSteps; + } CalcSegmentPositions(); simDisplay.updateDisplay = true; } diff --git a/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp b/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp index f9d614ab15..a18c98146f 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp @@ -196,7 +196,7 @@ bool CheckCompileResult(int shaderId, const char* shaderName, bool isVertex) len = 1020; } log[len] = 0; - Base::Console().Error(log); + Base::Console().error(log); return true; } diff --git a/src/Mod/Cloud/App/AppCloud.cpp b/src/Mod/Cloud/App/AppCloud.cpp index 3ec811dc04..e2b7956b73 100644 --- a/src/Mod/Cloud/App/AppCloud.cpp +++ b/src/Mod/Cloud/App/AppCloud.cpp @@ -62,7 +62,7 @@ XERCES_CPP_NAMESPACE_USE PyMOD_INIT_FUNC(Cloud) { PyObject* mod = Cloud::initModule(); - Base::Console().Log("Loading Cloud module... done\n"); + Base::Console().log("Loading Cloud module... done\n"); PyMOD_Return(mod); } @@ -1495,7 +1495,7 @@ bool Cloud::Module::cloudRestore(const char* BucketName) doc->Restore(reader); } catch (const Base::Exception& e) { - Base::Console().Error("Invalid Document.xml: %s\n", e.what()); + Base::Console().error("Invalid Document.xml: %s\n", e.what()); } // Special handling for Gui document, the view representations must already diff --git a/src/Mod/Cloud/Gui/AppCloudGui.cpp b/src/Mod/Cloud/Gui/AppCloudGui.cpp index 5990cfccdf..f74d1a1a8d 100644 --- a/src/Mod/Cloud/Gui/AppCloudGui.cpp +++ b/src/Mod/Cloud/Gui/AppCloudGui.cpp @@ -75,6 +75,6 @@ PyMOD_INIT_FUNC(CloudGui) // // PyObject* mod = CloudGui::initModule(); - Base::Console().Log("Loading GUI of Cloud module... done\n"); + Base::Console().log("Loading GUI of Cloud module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Cloud/Gui/Command.cpp b/src/Mod/Cloud/Gui/Command.cpp index d1f0f045b9..ae8f107ed5 100644 --- a/src/Mod/Cloud/Gui/Command.cpp +++ b/src/Mod/Cloud/Gui/Command.cpp @@ -49,7 +49,7 @@ CmdCloudTest::CmdCloudTest() void CmdCloudTest::activated(int) { - Base::Console().Message("Hello, World!\n"); + Base::Console().message("Hello, World!\n"); } void CreateCloudCommands(void) diff --git a/src/Mod/Draft/App/AppDraftUtils.cpp b/src/Mod/Draft/App/AppDraftUtils.cpp index 4de915fec9..fade5297ac 100644 --- a/src/Mod/Draft/App/AppDraftUtils.cpp +++ b/src/Mod/Draft/App/AppDraftUtils.cpp @@ -43,6 +43,6 @@ PyMOD_INIT_FUNC(DraftUtils) PyMOD_Return(nullptr); } PyObject* mod = DraftUtils::initModule(); - Base::Console().Log("Loading DraftUtils module... done\n"); + Base::Console().log("Loading DraftUtils module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Draft/App/AppDraftUtilsPy.cpp b/src/Mod/Draft/App/AppDraftUtilsPy.cpp index fcb07767f7..a0b831c097 100644 --- a/src/Mod/Draft/App/AppDraftUtilsPy.cpp +++ b/src/Mod/Draft/App/AppDraftUtilsPy.cpp @@ -45,7 +45,7 @@ public: private: Py::Object readDXF(const Py::Tuple& /*args*/) { - Base::Console().Warning("DraftUtils.readDXF is removed. " + Base::Console().warning("DraftUtils.readDXF is removed. " "Use Import.readDxf instead.\n"); return Py::None(); } diff --git a/src/Mod/Draft/Resources/ui/TaskShapeString.ui b/src/Mod/Draft/Resources/ui/TaskShapeString.ui index ab99f0264e..75ae57f9bf 100644 --- a/src/Mod/Draft/Resources/ui/TaskShapeString.ui +++ b/src/Mod/Draft/Resources/ui/TaskShapeString.ui @@ -149,7 +149,7 @@ Uncheck to use working plane coordinate system - + Text to be made into ShapeString @@ -166,12 +166,19 @@ Uncheck to use working plane coordinate system - Font files (*.ttf *.otf *.pfb *.TTF *.OTF *.PFB) + Font files (*.ttc *.ttf *.otf *.pfb *.TTC *.TTF *.OTF *.PFB) + + + + Qt::Vertical + + + diff --git a/src/Mod/Draft/draftguitools/gui_arcs.py b/src/Mod/Draft/draftguitools/gui_arcs.py index 6d5deb385c..038038bb1d 100644 --- a/src/Mod/Draft/draftguitools/gui_arcs.py +++ b/src/Mod/Draft/draftguitools/gui_arcs.py @@ -498,11 +498,10 @@ class Arc_3Points(gui_base.GuiCommandBase): Gui.Snapper.getPoint(callback=self.getPoint, movecallback=self.drawArc) - self.ui = Gui.Snapper.ui ## self must have a ui for _finish_command_on_doc_close in doc_observer.py. - self.ui.sourceCmd = self - self.ui.setTitle(title=translate("draft", "Arc by 3 points"), - icon="Draft_Arc_3Points") - self.ui.continueCmd.show() + Gui.Snapper.ui.sourceCmd = self + Gui.Snapper.ui.setTitle(title=translate("draft", "Arc by 3 points"), + icon="Draft_Arc_3Points") + Gui.Snapper.ui.continueCmd.show() def getPoint(self, point, info): """Get the point by clicking on the 3D view. @@ -543,11 +542,10 @@ class Arc_3Points(gui_base.GuiCommandBase): Gui.Snapper.getPoint(last=self.points[-1], callback=self.getPoint, movecallback=self.drawArc) - self.ui = Gui.Snapper.ui - self.ui.sourceCmd = self - self.ui.setTitle(title=translate("draft", "Arc by 3 points"), - icon="Draft_Arc_3Points") - self.ui.continueCmd.show() + Gui.Snapper.ui.sourceCmd = self + Gui.Snapper.ui.setTitle(title=translate("draft", "Arc by 3 points"), + icon="Draft_Arc_3Points") + Gui.Snapper.ui.continueCmd.show() else: # If three points were already picked in the 3D view diff --git a/src/Mod/Draft/draftguitools/gui_dimensions.py b/src/Mod/Draft/draftguitools/gui_dimensions.py index 778d46df04..e32d55ae5b 100644 --- a/src/Mod/Draft/draftguitools/gui_dimensions.py +++ b/src/Mod/Draft/draftguitools/gui_dimensions.py @@ -87,7 +87,7 @@ class Dimension(gui_base_original.Creator): 'MenuText': QT_TRANSLATE_NOOP("Draft_Dimension", "Dimension"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Dimension", "Creates a dimension.\n\n- Pick three points to create a simple linear dimension.\n- Select a straight line to create a linear dimension linked to that line.\n- Select an arc or circle to create a radius or diameter dimension linked to that arc.\n- Select two straight lines to create an angular dimension between them.\nCTRL to snap, SHIFT to constrain, ALT to select an edge or arc.\n\nYou may select a single line or single circular arc before launching this command\nto create the corresponding linked dimension.\nYou may also select an 'App::MeasureDistance' object before launching this command\nto turn it into a 'Draft Dimension' object.")} - def Activated(self): + def Activated(self, dir_vec=None): """Execute when the command is called.""" if self.chain and not self.contMode: self.finish() @@ -103,6 +103,7 @@ class Dimension(gui_base_original.Creator): self.dimtrack = trackers.dimTracker() self.arctrack = trackers.arcTracker() self.link = None + self.dir = dir_vec self.edges = [] self.angles = [] self.angledata = None diff --git a/src/Mod/Draft/draftguitools/gui_polygons.py b/src/Mod/Draft/draftguitools/gui_polygons.py index 8825002b41..175255d0d0 100644 --- a/src/Mod/Draft/draftguitools/gui_polygons.py +++ b/src/Mod/Draft/draftguitools/gui_polygons.py @@ -57,7 +57,7 @@ class Polygon(gui_base_original.Creator): 'MenuText': QT_TRANSLATE_NOOP("Draft_Polygon", "Polygon"), 'ToolTip': QT_TRANSLATE_NOOP("Draft_Polygon", "Creates a regular polygon (triangle, square, pentagon, ...), by defining the number of sides and the circumscribed radius.\nCTRL to snap, SHIFT to constrain")} - def Activated(self): + def Activated(self, numVertices=None): """Execute when the command is called.""" super().Activated(name="Polygon") if self.ui: @@ -72,8 +72,10 @@ class Polygon(gui_base_original.Creator): self.ui.numFaces.show() self.ui.numFacesLabel.show() self.altdown = False + self.numVertices = numVertices if numVertices is not None else 3 + self.ui.numFaces.setValue(self.numVertices) self.ui.sourceCmd = self - self.arctrack = trackers.arcTracker() + self.polygonTrack = trackers.polygonTracker(sides=self.numVertices) self.call = self.view.addEventCallback("SoEvent", self.action) _toolmsg(translate("draft", "Pick center point")) @@ -88,10 +90,10 @@ class Polygon(gui_base_original.Creator): """ self.end_callbacks(self.call) if self.ui: - self.arctrack.finalize() + self.polygonTrack.finalize() super().finish() if cont or (cont is None and self.ui and self.ui.continueMode): - self.Activated() + self.Activated(self.numVertices) def action(self, arg): """Handle the 3D scene events. @@ -105,12 +107,15 @@ class Polygon(gui_base_original.Creator): from the 3D view. """ import DraftGeomUtils - + if self.ui.numFaces.value() != self.numVertices: + self.polygonTrack.setNumVertices(self.ui.numFaces.value()) + self.numVertices = self.ui.numFaces.value() if arg["Type"] == "SoKeyboardEvent": if arg["Key"] == "ESCAPE": self.finish() elif arg["Type"] == "SoLocation2Event": # mouse movement detection self.point, ctrlPoint, info = gui_tool_utils.getPoint(self, arg) + self.polygonTrack.update(ctrlPoint) # this is to make sure radius is what you see on screen if self.center and DraftVecUtils.dist(self.point, self.center) > 0: @@ -134,14 +139,12 @@ class Polygon(gui_base_original.Creator): self.point) _c = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = _c.Center - self.arctrack.setCenter(self.center) elif self.tangents and self.tanpoints: cir = DraftGeomUtils.circleFrom1tan2pt(self.tangents[0], self.tanpoints[0], self.point) _c = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = _c.Center - self.arctrack.setCenter(self.center) if gui_tool_utils.hasMod(arg, gui_tool_utils.get_mod_alt_key()): if not self.altdown: self.altdown = True @@ -158,7 +161,6 @@ class Polygon(gui_base_original.Creator): cl = DraftGeomUtils.findClosestCircle(self.point, cir) self.center = cl.Center self.rad = cl.Radius - self.arctrack.setCenter(self.center) else: self.rad = self.center.add(DraftGeomUtils.findDistance(self.center,ed).sub(self.center)).Length else: @@ -168,7 +170,6 @@ class Polygon(gui_base_original.Creator): self.altdown = False self.rad = DraftVecUtils.dist(self.point, self.center) self.ui.setRadiusValue(self.rad, 'Length') - self.arctrack.setRadius(self.rad) gui_tool_utils.redraw3DView() @@ -190,7 +191,7 @@ class Polygon(gui_base_original.Creator): ed = ob.Shape.Edges[num] self.tangents.append(ed) if len(self.tangents) == 2: - self.arctrack.on() + self.polygonTrack.on() self.ui.radiusUi() self.step = 1 _toolmsg(translate("draft", "Pick radius")) @@ -200,8 +201,8 @@ class Polygon(gui_base_original.Creator): else: self.center = self.point self.node = [self.point] - self.arctrack.setCenter(self.center) - self.arctrack.on() + self.polygonTrack.setOrigin(self.center) + self.polygonTrack.on() self.ui.radiusUi() self.step = 1 _toolmsg(translate("draft", "Pick radius")) @@ -260,8 +261,7 @@ class Polygon(gui_base_original.Creator): """ self.center = App.Vector(numx, numy, numz) self.node = [self.center] - self.arctrack.setCenter(self.center) - self.arctrack.on() + self.polygonTrack.on() self.ui.radiusUi() self.step = 1 self.ui.radiusValue.setFocus() diff --git a/src/Mod/Draft/draftguitools/gui_trackers.py b/src/Mod/Draft/draftguitools/gui_trackers.py index 1c067781f6..5664832956 100644 --- a/src/Mod/Draft/draftguitools/gui_trackers.py +++ b/src/Mod/Draft/draftguitools/gui_trackers.py @@ -249,7 +249,78 @@ class lineTracker(Tracker): p1 = Vector(self.coords.point.getValues()[0].getValue()) p2 = Vector(self.coords.point.getValues()[-1].getValue()) return (p2.sub(p1)).Length + +class polygonTracker(Tracker): + """A Polygon tracker, used by the polygon tool.""" + + def __init__(self, dotted=False, scolor=None, swidth=None, face=False, sides=None): + self.origin = Vector(0, 0, 0) + self.line = coin.SoLineSet() + self.sides = sides if sides is not None else 3 + self.base_angle = None + self.line.numVertices.setValue(self.sides + 1) + self.coords = coin.SoCoordinate3() # this is the coordinate + self.coords.point.setValues(0, 50, [[0, 0, 0], + [2, 0, 0], + [1, 2, 0], + [0, 0, 0]]) + if face: + m1 = coin.SoMaterial() + m1.transparency.setValue(0.5) + m1.diffuseColor.setValue([0.5, 0.5, 1.0]) + f = coin.SoIndexedFaceSet() + f.coordIndex.setValues([0, 1, 2, 3]) + super().__init__(dotted, scolor, swidth, + [self.coords, self.line, m1, f], + name="polygonTracker") + else: + super().__init__(dotted, scolor, swidth, + [self.coords, self.line], + name="polygonTracker") + + def setNumVertices(self, num): + self.line.numVertices.setValue(num + 1) + self.sides = num + + def _drawPolygon(self, local_origin, radius): + wp = self._get_wp() + for i in range(self.sides): + angle = 2 * math.pi * i / self.sides + px = local_origin.x + radius * math.cos(angle) + py = local_origin.y + radius * math.sin(angle) + + # Back to global space + global_point = wp.get_global_coords(Vector(px, py, 0)) + self.coords.point.set1Value(i, *global_point) + + # Close the polygon by repeating the first point + first = self.coords.point[0].getValue() + self.coords.point.set1Value(self.sides, *first) + + def setOrigin(self, point, radius=1.0): + """Set the origin of the polygon and initialize the shape.""" + self.origin = point + wp = self._get_wp() + + # Convert the origin to working plane local space + local_origin = wp.get_local_coords(point) + + self._drawPolygon(local_origin, radius) + + def update(self, point): + """Update polygon size based on current mouse point.""" + wp = self._get_wp() + + # Convert current point and origin to local working plane coordinates + local = wp.get_local_coords(point) + local_origin = wp.get_local_coords(self.origin) + + dx = local.x - local_origin.x + dy = local.y - local_origin.y + radius = math.hypot(dx, dy) + + self._drawPolygon(local_origin, radius) class rectangleTracker(Tracker): """A Rectangle tracker, used by the rectangle tool.""" diff --git a/src/Mod/Draft/draftobjects/shapestring.py b/src/Mod/Draft/draftobjects/shapestring.py index c855e3c86e..991e3bdc89 100644 --- a/src/Mod/Draft/draftobjects/shapestring.py +++ b/src/Mod/Draft/draftobjects/shapestring.py @@ -146,7 +146,7 @@ class ShapeString(DraftObject): if not os.path.isfile(font_file): _err(obj.Label + ": " + translate("draft", "Specified font file is not a file")) return - if not os.path.splitext(font_file)[1].upper() in (".TTF", ".OTF", ".PFB"): + if not os.path.splitext(font_file)[1].lower() in (".ttc", ".ttf", ".otf", ".pfb"): _err(obj.Label + ": " + translate("draft", "Specified font type is not supported")) return diff --git a/src/Mod/Draft/draftutils/doc_observer.py b/src/Mod/Draft/draftutils/doc_observer.py index 2ff93d27c5..900f880225 100644 --- a/src/Mod/Draft/draftutils/doc_observer.py +++ b/src/Mod/Draft/draftutils/doc_observer.py @@ -1,3 +1,27 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later + +# *************************************************************************** +# * * +# * Copyright (c) 2025 FreeCAD Project Association * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** + import FreeCAD as App if App.GuiUp: @@ -34,9 +58,13 @@ if App.GuiUp: and use a task panel. """ if getattr(App, "activeDraftCommand", None) \ - and getattr(App.activeDraftCommand, "doc", None) == gui_doc.Document \ - and getattr(App.activeDraftCommand, "ui", None): - if hasattr(App.activeDraftCommand.ui, "reject"): - ToDo.delay(App.activeDraftCommand.ui.reject, None) - elif hasattr(App.activeDraftCommand.ui, "escape"): - ToDo.delay(App.activeDraftCommand.ui.escape, None) + and getattr(App.activeDraftCommand, "doc", None) == gui_doc.Document: + if hasattr(App.activeDraftCommand, "ui"): + if hasattr(App.activeDraftCommand.ui, "reject"): + ToDo.delay(App.activeDraftCommand.ui.reject, None) + elif hasattr(App.activeDraftCommand.ui, "escape"): + ToDo.delay(App.activeDraftCommand.ui.escape, None) + elif hasattr(Gui, "Snapper") \ + and hasattr(Gui.Snapper, "ui") \ + and hasattr(Gui.Snapper.ui, "escape"): + ToDo.delay(Gui.Snapper.ui.escape, None) diff --git a/src/Mod/Draft/draftutils/params.py b/src/Mod/Draft/draftutils/params.py index 19d1d948a2..0171b20a2e 100644 --- a/src/Mod/Draft/draftutils/params.py +++ b/src/Mod/Draft/draftutils/params.py @@ -391,15 +391,44 @@ def _param_from_PrefFontBox(widget): return path, entry, value +def _get_shape_string_font_file(): + """Try to get the file name of a sans serif font (TTC or TTF) from the OS.""" + # https://forum.freecad.org/viewtopic.php?t=96770 + # Windows font: "arial" + # Mac fonts: "geneva" and "helvetica" + # Linux fonts: "dejavusans" and "freesans" + favorite_names = ("arial", "geneva", "helvetica", "dejavusans", "freesans") + font_file_sans = None # Font with name containing "sans". 1st fallback. + font_file_alpha = None # Font with name starting with a letter. 2nd fallback. + # Reverse the order of the paths so that user related paths come last: + for path in QtCore.QStandardPaths.standardLocations(QtCore.QStandardPaths.FontsLocation)[::-1]: + # We don't use os.path.join as dir_path has forward slashes even on Windows. + for (dir_path, dir_names, file_names) in os.walk(path): + for file_name in file_names: + base_name, ext = [s.lower() for s in os.path.splitext(file_name)] + if not ext in (".ttc", ".ttf"): + continue + if base_name in favorite_names: + return dir_path + "/" + file_name + if font_file_sans is None and "sans" in base_name: + font_file_sans = dir_path + "/" + file_name + if font_file_alpha is None and base_name[0].isalpha(): + font_file_alpha = dir_path + "/" + file_name + if font_file_sans is not None: + return font_file_sans + if font_file_alpha is not None: + return font_file_alpha + return "" + + def _get_param_dictionary(): # print("Creating preferences dictionary...") param_dict = {} - hatch_pattern_file = os.path.join( - App.getResourceDir().replace("\\", "/"), "Mod/TechDraw/PAT/FCPAT.pat" - ) + hatch_pattern_file = App.getResourceDir().replace("\\", "/").rstrip("/") \ + + "/Mod/TechDraw/PAT/FCPAT.pat" # Draft parameters that are not in the preferences: param_dict["Mod/Draft"] = { @@ -437,7 +466,7 @@ def _get_param_dictionary(): "ScaleCopy": ("bool", False), "ScaleRelative": ("bool", False), "ScaleUniform": ("bool", False), - "ShapeStringFontFile": ("string", ""), + "ShapeStringFontFile": ("string", _get_shape_string_font_file()), "ShapeStringHeight": ("float", 10.0), "ShapeStringText": ("string", translate("draft", "Default")), "snapModes": ("string", "100000000000000"), diff --git a/src/Mod/Draft/draftviewproviders/view_dimension.py b/src/Mod/Draft/draftviewproviders/view_dimension.py index c96a2793f2..d426b285d8 100644 --- a/src/Mod/Draft/draftviewproviders/view_dimension.py +++ b/src/Mod/Draft/draftviewproviders/view_dimension.py @@ -596,7 +596,7 @@ class ViewProviderLinearDimension(ViewProviderDimensionBase): unit = vobj.UnitOverride # Special representation if we use 'Building US' scheme - if (params.get_param("UserSchema", path="Units") == 5) or (unit == "arch"): + if (not unit and params.get_param("UserSchema", path="Units") == 5) or (unit == "arch"): self.string = App.Units.Quantity(length, App.Units.Length).UserString if self.string.count('"') > 1: # multiple inch tokens diff --git a/src/Mod/Drawing/App/AppDrawing.cpp b/src/Mod/Drawing/App/AppDrawing.cpp index 21556f4fef..e25ce90bfd 100644 --- a/src/Mod/Drawing/App/AppDrawing.cpp +++ b/src/Mod/Drawing/App/AppDrawing.cpp @@ -44,7 +44,7 @@ PyMOD_INIT_FUNC(Drawing) PyMOD_Return(nullptr); } PyObject* mod = Drawing::initModule(); - Base::Console().Log("Loading Drawing module... done\n"); + Base::Console().log("Loading Drawing module... done\n"); // NOTE: To finish the initialization of our own type objects we must diff --git a/src/Mod/Drawing/App/AppDrawingPy.cpp b/src/Mod/Drawing/App/AppDrawingPy.cpp index 274ffbd249..88bd819c40 100644 --- a/src/Mod/Drawing/App/AppDrawingPy.cpp +++ b/src/Mod/Drawing/App/AppDrawingPy.cpp @@ -123,7 +123,7 @@ private: else { str += "No OCCT Exception Message"; } - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception& e) { @@ -131,7 +131,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception& e) { @@ -139,7 +139,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } diff --git a/src/Mod/Drawing/App/FeaturePage.cpp b/src/Mod/Drawing/App/FeaturePage.cpp index d4cc5473cd..2e4aa60008 100644 --- a/src/Mod/Drawing/App/FeaturePage.cpp +++ b/src/Mod/Drawing/App/FeaturePage.cpp @@ -149,7 +149,7 @@ App::DocumentObjectExecReturn* FeaturePage::execute(void) fi.setFile(App::Application::getResourceDir() + "Mod/Drawing/Templates/" + fi.fileName()); // try the redirect if (!fi.isReadable()) { - Base::Console().Log("FeaturePage::execute() not able to open %s!\n", + Base::Console().log("FeaturePage::execute() not able to open %s!\n", Template.getValue()); std::string error = std::string("Cannot open file ") + Template.getValue(); return new App::DocumentObjectExecReturn(error); diff --git a/src/Mod/Drawing/Gui/AppDrawingGui.cpp b/src/Mod/Drawing/Gui/AppDrawingGui.cpp index ce4f17fe8f..2b7123c10a 100644 --- a/src/Mod/Drawing/Gui/AppDrawingGui.cpp +++ b/src/Mod/Drawing/Gui/AppDrawingGui.cpp @@ -58,7 +58,7 @@ PyMOD_INIT_FUNC(DrawingGui) } PyObject* mod = DrawingGui::initModule(); - Base::Console().Log("Loading GUI of Drawing module... done\n"); + Base::Console().log("Loading GUI of Drawing module... done\n"); // instantiating the commands CreateDrawingCommands(); diff --git a/src/Mod/Fem/App/AppFem.cpp b/src/Mod/Fem/App/AppFem.cpp index df13a6cf96..e59e7930fe 100644 --- a/src/Mod/Fem/App/AppFem.cpp +++ b/src/Mod/Fem/App/AppFem.cpp @@ -87,7 +87,7 @@ PyMOD_INIT_FUNC(Fem) PyMOD_Return(nullptr); } PyObject* femModule = Fem::initModule(); - Base::Console().Log("Loading Fem module... done\n"); + Base::Console().log("Loading Fem module... done\n"); // clang-format off Fem::StdMeshers_Arithmetic1DPy ::init_type(femModule); @@ -206,6 +206,8 @@ PyMOD_INIT_FUNC(Fem) Fem::FemPostSphereFunction ::init(); Fem::PropertyPostDataObject ::init(); + + Fem::PostFilterPython ::init(); #endif // clang-format on diff --git a/src/Mod/Fem/App/AppFemPy.cpp b/src/Mod/Fem/App/AppFemPy.cpp index c87474fd08..69ab7fc502 100644 --- a/src/Mod/Fem/App/AppFemPy.cpp +++ b/src/Mod/Fem/App/AppFemPy.cpp @@ -40,6 +40,11 @@ #ifdef FC_USE_VTK #include "FemPostPipeline.h" #include "FemVTKTools.h" +#include +#endif + +#ifdef FC_USE_VTK_PYTHON +#include #endif @@ -75,6 +80,15 @@ public: &Module::writeResult, "write a CFD or FEM result (auto detect) to a file (file format " "detected from file suffix)"); + add_varargs_method("getVtkVersion", + &Module::getVtkVersion, + "Returns the VTK version FreeCAD is linked against"); +#ifdef FC_USE_VTK_PYTHON + add_varargs_method( + "isVtkCompatible", + &Module::isVtkCompatible, + "Checks if the passed vtkObject is compatible with the c++ VTK version FreeCAD uses"); +#endif #endif add_varargs_method("show", &Module::show, @@ -318,6 +332,34 @@ private: return Py::None(); } + + Py::Object getVtkVersion(const Py::Tuple& args) + { + if (!PyArg_ParseTuple(args.ptr(), "")) { + throw Py::Exception(); + } + + return Py::String(fcVtkVersion); + } + +#ifdef FC_USE_VTK_PYTHON + Py::Object isVtkCompatible(const Py::Tuple& args) + { + PyObject* pcObj = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj)) { + throw Py::Exception(); + } + + // if non is returned the VTK object was created by annother VTK library, and the + // python api used to create it cannot be used with FreeCAD + vtkObjectBase* obj = vtkPythonUtil::GetPointerFromObject(pcObj, "vtkObject"); + if (!obj) { + PyErr_Clear(); + return Py::False(); + } + return Py::True(); + } +#endif #endif Py::Object show(const Py::Tuple& args) diff --git a/src/Mod/Fem/App/CMakeLists.txt b/src/Mod/Fem/App/CMakeLists.txt index 61d3f20be1..b58a53f5b2 100644 --- a/src/Mod/Fem/App/CMakeLists.txt +++ b/src/Mod/Fem/App/CMakeLists.txt @@ -67,11 +67,14 @@ if(BUILD_FEM_VTK) FemPostObjectPyImp.cpp FemPostPipelinePy.xml FemPostPipelinePyImp.cpp + FemPostFilterPy.xml + FemPostFilterPyImp.cpp FemPostBranchFilterPy.xml FemPostBranchFilterPyImp.cpp ) generate_from_xml(FemPostObjectPy) generate_from_xml(FemPostPipelinePy) + generate_from_xml(FemPostFilterPy) generate_from_xml(FemPostBranchFilterPy) endif(BUILD_FEM_VTK) SOURCE_GROUP("Python" FILES ${Python_SRCS}) diff --git a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp index 7675962655..22e3ce377d 100644 --- a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp @@ -131,8 +131,8 @@ void ConstraintFluidBoundary::onChanged(const App::Property* prop) Subtype.setEnums(OutletSubtypes); } else { - Base::Console().Message(boundaryType.c_str()); - Base::Console().Message(" Error: this boundaryType is not defined\n"); + Base::Console().message(boundaryType.c_str()); + Base::Console().message(" Error: this boundaryType is not defined\n"); } // must set a default (0 or 1) as freestream has only 2 subtypes diff --git a/src/Mod/Fem/App/FemMesh.cpp b/src/Mod/Fem/App/FemMesh.cpp index c026483702..70b2182027 100644 --- a/src/Mod/Fem/App/FemMesh.cpp +++ b/src/Mod/Fem/App/FemMesh.cpp @@ -572,7 +572,7 @@ std::set FemMesh::getNodesBySolid(const TopoDS_Solid& solid) const TopAbs_ShapeEnum shapetype = TopAbs_SHAPE; ShapeAnalysis_ShapeTolerance analysis; double limit = analysis.Tolerance(solid, 1, shapetype); - Base::Console().Log("The limit if a node is in or out: %.12lf in scientific: %.4e \n", + Base::Console().log("The limit if a node is in or out: %.12lf in scientific: %.4e \n", limit, limit); @@ -971,7 +971,7 @@ public: meshds->AddFaceWithID(n0, n1, n2, element_id); } else { - Base::Console().Warning("NASTRAN: Failed to add face %d from nodes: (%d, %d, %d,)\n", + Base::Console().warning("NASTRAN: Failed to add face %d from nodes: (%d, %d, %d,)\n", element_id, elements[0], elements[1], @@ -1038,7 +1038,7 @@ public: meshds->AddVolumeWithID(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, element_id); } else { - Base::Console().Warning("NASTRAN: Failed to add volume %d from nodes: (%d, %d, %d, %d, " + Base::Console().warning("NASTRAN: Failed to add volume %d from nodes: (%d, %d, %d, %d, " "%d, %d, %d, %d, %d, %d)\n", element_id, elements[1], @@ -1299,7 +1299,7 @@ class CHEXA2Element: public NastranElement void FemMesh::readNastran(const std::string& Filename) { Base::TimeElapsed Start; - Base::Console().Log("Start: FemMesh::readNastran() =================================\n"); + Base::Console().log("Start: FemMesh::readNastran() =================================\n"); _Mtrx = Base::Matrix4D(); @@ -1375,7 +1375,7 @@ void FemMesh::readNastran(const std::string& Filename) } while (inputfile.good()); inputfile.close(); - Base::Console().Log(" %f: File read, start building mesh\n", + Base::Console().log(" %f: File read, start building mesh\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // Now fill the SMESH datastructure @@ -1386,14 +1386,14 @@ void FemMesh::readNastran(const std::string& Filename) it->addToMesh(meshds); } - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readNastran95(const std::string& Filename) { Base::TimeElapsed Start; - Base::Console().Log("Start: FemMesh::readNastran95() =================================\n"); + Base::Console().log("Start: FemMesh::readNastran95() =================================\n"); _Mtrx = Base::Matrix4D(); @@ -1428,7 +1428,7 @@ void FemMesh::readNastran95(const std::string& Filename) } else if (line1.find("GRID") != std::string::npos) // We found a Grid line { - // Base::Console().Log("Found a GRID\n"); + // Base::Console().log("Found a GRID\n"); // D06.inp // GRID 109 .9 .7 // Now lets extract the GRID Points = Nodes @@ -1502,7 +1502,7 @@ void FemMesh::readNastran95(const std::string& Filename) } while (inputfile.good()); inputfile.close(); - Base::Console().Log(" %f: File read, start building mesh\n", + Base::Console().log(" %f: File read, start building mesh\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // Now fill the SMESH datastructure @@ -1517,14 +1517,14 @@ void FemMesh::readNastran95(const std::string& Filename) it->addToMesh(meshds); } - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readAbaqus(const std::string& FileName) { Base::TimeElapsed Start; - Base::Console().Log("Start: FemMesh::readAbaqus() =================================\n"); + Base::Console().log("Start: FemMesh::readAbaqus() =================================\n"); /* Python command to read Abaqus inp mesh file from test suite: @@ -1557,14 +1557,14 @@ void FemMesh::readAbaqus(const std::string& FileName) catch (Py::Exception& e) { e.clear(); } - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readZ88(const std::string& FileName) { Base::TimeElapsed Start; - Base::Console().Log("Start: FemMesh::readZ88() =================================\n"); + Base::Console().log("Start: FemMesh::readZ88() =================================\n"); /* Python command to read Z88 mesh file from test suite: @@ -1597,7 +1597,7 @@ void FemMesh::readZ88(const std::string& FileName) catch (Py::Exception& e) { e.clear(); } - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } @@ -1653,7 +1653,9 @@ void FemMesh::read(const char* FileName) void FemMesh::writeVTK(const std::string& fileName, bool highest) const { +#ifdef FC_USE_VTK FemVTKTools::writeVTKMesh(fileName.c_str(), this, highest); +#endif } void FemMesh::writeABAQUS(const std::string& Filename, @@ -2226,7 +2228,7 @@ void FemMesh::writeABAQUS(const std::string& Filename, void FemMesh::writeZ88(const std::string& FileName) const { Base::TimeElapsed Start; - Base::Console().Log("Start: FemMesh::writeZ88() =================================\n"); + Base::Console().log("Start: FemMesh::writeZ88() =================================\n"); /* Python command to export FemMesh from StartWB FEM 3D example: @@ -2258,41 +2260,41 @@ void FemMesh::write(const char* FileName) const Base::FileInfo File(FileName); if (File.hasExtension("unv")) { - Base::Console().Log("FEM mesh object will be exported to unv format.\n"); + Base::Console().log("FEM mesh object will be exported to unv format.\n"); // write UNV file myMesh->ExportUNV(File.filePath().c_str()); } else if (File.hasExtension("med")) { - Base::Console().Log("FEM mesh object will be exported to med format.\n"); + Base::Console().log("FEM mesh object will be exported to med format.\n"); myMesh->ExportMED(File.filePath().c_str(), File.fileNamePure().c_str(), false, 2); // 2 means MED_V2_2 version! } else if (File.hasExtension("stl")) { - Base::Console().Log("FEM mesh object will be exported to stl format.\n"); + Base::Console().log("FEM mesh object will be exported to stl format.\n"); // export to stl file myMesh->ExportSTL(File.filePath().c_str(), false); } else if (File.hasExtension("dat")) { - Base::Console().Log("FEM mesh object will be exported to dat format.\n"); + Base::Console().log("FEM mesh object will be exported to dat format.\n"); // export to dat file myMesh->ExportDAT(File.filePath().c_str()); } else if (File.hasExtension("inp")) { - Base::Console().Log("FEM mesh object will be exported to inp format.\n"); + Base::Console().log("FEM mesh object will be exported to inp format.\n"); // write ABAQUS Output writeABAQUS(File.filePath(), 1, false); } #ifdef FC_USE_VTK else if (File.hasExtension({"vtk", "vtu"})) { - Base::Console().Log("FEM mesh object will be exported to either vtk or vtu format.\n"); + Base::Console().log("FEM mesh object will be exported to either vtk or vtu format.\n"); // write unstructure mesh to VTK format *.vtk and *.vtu writeVTK(File.filePath().c_str()); } #endif else if (File.hasExtension("z88")) { - Base::Console().Log("FEM mesh object will be exported to z88 format.\n"); + Base::Console().log("FEM mesh object will be exported to z88 format.\n"); // write z88 file writeZ88(File.filePath()); } diff --git a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp index 64cba0c980..9a361093d7 100644 --- a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp +++ b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp @@ -131,7 +131,7 @@ App::DocumentObjectExecReturn* FemMeshShapeNetgenObject::execute() // int numPris = info.NbPrisms(); // int numHedr = info.NbPolyhedrons(); - Base::Console().Log("NetgenMesh: %i Nodes, %i Volumes, %i Faces\n", numNode, numVolu, numFaces); + Base::Console().log("NetgenMesh: %i Nodes, %i Volumes, %i Faces\n", numNode, numVolu, numFaces); FemMesh.setValue(newMesh); return App::DocumentObject::StdReturn; diff --git a/src/Mod/Fem/App/FemPostFilter.cpp b/src/Mod/Fem/App/FemPostFilter.cpp index 338dec9e89..24531c1790 100644 --- a/src/Mod/Fem/App/FemPostFilter.cpp +++ b/src/Mod/Fem/App/FemPostFilter.cpp @@ -31,10 +31,13 @@ #include #endif +#include #include #include #include "FemPostFilter.h" +#include "FemPostFilterPy.h" + #include "FemPostPipeline.h" #include "FemPostBranchFilter.h" @@ -52,22 +55,42 @@ FemPostFilter::FemPostFilter() "Data", App::Prop_ReadOnly, "The step used to calculate the data"); + + // the default pipeline: just a passthrough + // this is used to simplify the python filter handling, + // as those do not have filter pipelines setup till later + // in the document loading process. + auto filter = vtkPassThrough::New(); + auto pipeline = FemPostFilter::FilterPipeline(); + pipeline.algorithmStorage.push_back(filter); + pipeline.source = filter; + pipeline.target = filter; + addFilterPipeline(pipeline, "__passthrough__"); } FemPostFilter::~FemPostFilter() = default; + void FemPostFilter::addFilterPipeline(const FemPostFilter::FilterPipeline& p, std::string name) { m_pipelines[name] = p; + + if (m_activePipeline.empty()) { + m_activePipeline = name; + } } FemPostFilter::FilterPipeline& FemPostFilter::getFilterPipeline(std::string name) { - return m_pipelines[name]; + return m_pipelines.at(name); } void FemPostFilter::setActiveFilterPipeline(std::string name) { + if (m_pipelines.count(name) == 0) { + throw Base::ValueError("Not a filter pipline name"); + } + if (m_activePipeline != name && isValid()) { // disable all inputs of current pipeline @@ -129,6 +152,7 @@ void FemPostFilter::onChanged(const App::Property* prop) { if (prop == &Placement) { + if (Placement.getValue().isIdentity() && m_use_transform) { // remove transform from pipeline if (m_transform_location == TransformLocation::output) { @@ -191,7 +215,6 @@ DocumentObjectExecReturn* FemPostFilter::execute() Data.setValue(output->GetOutputDataObject(0)); } - return StdReturn; } @@ -203,8 +226,19 @@ vtkSmartPointer FemPostFilter::getInputData() } vtkAlgorithmOutput* output = active.source->GetInputConnection(0, 0); + if (!output) { + return nullptr; + } vtkAlgorithm* algo = output->GetProducer(); - algo->Update(); + if (!algo) { + return nullptr; + } + if (Frame.getValue() > 0) { + algo->UpdateTimeStep(Frame.getValue()); + } + else { + algo->Update(); + } return vtkDataSet::SafeDownCast(algo->GetOutputDataObject(0)); } @@ -251,6 +285,45 @@ void FemPostFilter::setTransformLocation(TransformLocation loc) m_transform_location = loc; } +PyObject* FemPostFilter::getPyObject() +{ + if (PythonObject.is(Py::_None())) { + // ref counter is set to 1 + PythonObject = Py::Object(new FemPostFilterPy(this), true); + } + + return Py::new_reference_to(PythonObject); +} + + +// Python Filter feature --------------------------------------------------------- + +namespace App +{ +/// @cond DOXERR +PROPERTY_SOURCE_TEMPLATE(Fem::PostFilterPython, Fem::FemPostFilter) +template<> +const char* Fem::PostFilterPython::getViewProviderName(void) const +{ + return "FemGui::ViewProviderPostFilterPython"; +} +template<> +PyObject* Fem::PostFilterPython::getPyObject() +{ + if (PythonObject.is(Py::_None())) { + // ref counter is set to 1 + PythonObject = Py::Object(new App::FeaturePythonPyT(this), true); + } + return Py::new_reference_to(PythonObject); +} + +/// @endcond + +// explicit template instantiation +template class FemExport FeaturePythonT; +} // namespace App + + // *************************************************************************** // in the following, the different filters sorted alphabetically // *************************************************************************** diff --git a/src/Mod/Fem/App/FemPostFilter.h b/src/Mod/Fem/App/FemPostFilter.h index d137b68bcf..273bd63c0f 100644 --- a/src/Mod/Fem/App/FemPostFilter.h +++ b/src/Mod/Fem/App/FemPostFilter.h @@ -40,6 +40,7 @@ #include #include +#include #include "FemPostObject.h" @@ -53,6 +54,8 @@ enum class TransformLocation : size_t output }; +class FemPostFilterPy; + class FemExport FemPostFilter: public Fem::FemPostObject { PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostFilter); @@ -69,12 +72,16 @@ protected: std::vector> algorithmStorage; }; + // pipeline handling void addFilterPipeline(const FilterPipeline& p, std::string name); - void setActiveFilterPipeline(std::string name); FilterPipeline& getFilterPipeline(std::string name); + void setActiveFilterPipeline(std::string name); + // Transformation handling void setTransformLocation(TransformLocation loc); + friend class FemPostFilterPy; + public: /// Constructor FemPostFilter(); @@ -88,16 +95,21 @@ public: vtkSmartPointer getFilterInput(); vtkSmartPointer getFilterOutput(); + PyObject* getPyObject() override; + private: // handling of multiple pipelines which can be the filter std::map m_pipelines; std::string m_activePipeline; bool m_use_transform = false; + bool m_running_setup = false; TransformLocation m_transform_location = TransformLocation::output; void pipelineChanged(); // inform parents that the pipeline changed }; +using PostFilterPython = App::FeaturePythonT; + class FemExport FemPostSmoothFilterExtension: public App::DocumentObjectExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostSmoothFilterExtension); diff --git a/src/Mod/Fem/App/FemPostFilterPy.xml b/src/Mod/Fem/App/FemPostFilterPy.xml new file mode 100644 index 0000000000..28d1823f69 --- /dev/null +++ b/src/Mod/Fem/App/FemPostFilterPy.xml @@ -0,0 +1,56 @@ + + + + + + The FemPostFilter class. + + + + Registers a new vtk filter pipeline for data processing. Arguments are (name, source algorithm, target algorithm). + + + + + Sets the filter pipeline that shall be used for data processing. Argument is the name of the filter pipeline to activate. + + + + + Returns the postprocessing group the filter is in (e.g. a pipeline or branch object). None is returned if not in any. + + + + + +Returns the dataset available at the filter's input. +Note: Can lead to a full recompute of the whole pipeline, hence best to call this only in "execute", where the user expects long calculation cycles. + + + + + + +Returns the names of all vector fields available on this filter's input. +Note: Can lead to a full recompute of the whole pipeline, hence best to call this only in "execute", where the user expects long calculation cycles. + + + + + + +Returns the names of all scalar fields available on this filter's input. +Note: Can lead to a full recompute of the whole pipeline, hence best to call this only in "execute", where the user expects long calculation cycles. + + + " + + diff --git a/src/Mod/Fem/App/FemPostFilterPyImp.cpp b/src/Mod/Fem/App/FemPostFilterPyImp.cpp new file mode 100644 index 0000000000..dddf9048e1 --- /dev/null +++ b/src/Mod/Fem/App/FemPostFilterPyImp.cpp @@ -0,0 +1,194 @@ +/*************************************************************************** + * Copyright (c) 2017 Werner Mayer * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + +#include "PreCompiled.h" +#ifndef _PreComp_ +#include +#endif + +#include +#include + +// clang-format off +#include "FemPostGroupExtension.h" +#include "FemPostFilter.h" +#include "FemPostFilterPy.h" +#include "FemPostFilterPy.cpp" +// clang-format on + +#ifdef FC_USE_VTK_PYTHON +#include +#include +#endif // BUILD_FEM_VTK + +using namespace Fem; + +// returns a string which represents the object e.g. when printed in python +std::string FemPostFilterPy::representation() const +{ + std::stringstream str; + str << ""; + + return str.str(); +} + + +PyObject* FemPostFilterPy::addFilterPipeline(PyObject* args) +{ +#ifdef FC_USE_VTK_PYTHON + const char* name; + PyObject* source = nullptr; + PyObject* target = nullptr; + + if (PyArg_ParseTuple(args, "sOO", &name, &source, &target)) { + + // extract the algorithms + vtkObjectBase* obj = vtkPythonUtil::GetPointerFromObject(source, "vtkAlgorithm"); + if (!obj) { + // error marker is set by PythonUtil + return nullptr; + } + auto source_algo = static_cast(obj); + + obj = vtkPythonUtil::GetPointerFromObject(target, "vtkAlgorithm"); + if (!obj) { + // error marker is set by PythonUtil + return nullptr; + } + auto target_algo = static_cast(obj); + + // add the pipeline + FemPostFilter::FilterPipeline pipe; + pipe.source = source_algo; + pipe.target = target_algo; + getFemPostFilterPtr()->addFilterPipeline(pipe, name); + } + Py_Return; +#else + PyErr_SetString(PyExc_NotImplementedError, "VTK python wrapper not available"); + Py_Return; +#endif +} + +PyObject* FemPostFilterPy::setActiveFilterPipeline(PyObject* args) +{ + const char* name; + if (PyArg_ParseTuple(args, "s", &name)) { + getFemPostFilterPtr()->setActiveFilterPipeline(std::string(name)); + } + + Py_Return; +} + +PyObject* FemPostFilterPy::getParentPostGroup(PyObject* args) +{ + // we take no arguments + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } + + auto group = Fem::FemPostGroupExtension::getGroupOfObject(getFemPostFilterPtr()); + if (group) { + return group->getPyObject(); + } + + return Py_None; +} + +PyObject* FemPostFilterPy::getInputData(PyObject* args) +{ +#ifdef FC_USE_VTK_PYTHON + // we take no arguments + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } + + // make a copy of the dataset + auto dataset = getFemPostFilterPtr()->getInputData(); + vtkDataSet* copy; + switch (dataset->GetDataObjectType()) { + case VTK_UNSTRUCTURED_GRID: + copy = vtkUnstructuredGrid::New(); + break; + default: + PyErr_SetString(PyExc_TypeError, + "cannot return datatype object; not unstructured grid"); + Py_Return; + } + + // return the python wrapper + copy->DeepCopy(dataset); + PyObject* py_dataset = vtkPythonUtil::GetObjectFromPointer(copy); + + return Py::new_reference_to(py_dataset); +#else + PyErr_SetString(PyExc_NotImplementedError, "VTK python wrapper not available"); + Py_Return; +#endif +} + +PyObject* FemPostFilterPy::getInputVectorFields(PyObject* args) +{ + // we take no arguments + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } + + std::vector vector_fields = getFemPostFilterPtr()->getInputVectorFields(); + + // convert to python list of strings + Py::List list; + for (std::string& field : vector_fields) { + list.append(Py::String(field)); + } + + return Py::new_reference_to(list); +} + + +PyObject* FemPostFilterPy::getInputScalarFields(PyObject* args) +{ + // we take no arguments + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } + + std::vector scalar_fields = getFemPostFilterPtr()->getInputScalarFields(); + + // convert to python list of strings + Py::List list; + for (std::string& field : scalar_fields) { + list.append(Py::String(field)); + } + + return Py::new_reference_to(list); +} + +PyObject* FemPostFilterPy::getCustomAttributes(const char* /*attr*/) const +{ + return nullptr; +} + +int FemPostFilterPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) +{ + return 0; +} diff --git a/src/Mod/Fem/App/FemPostPipeline.cpp b/src/Mod/Fem/App/FemPostPipeline.cpp index e76954d4a9..2689b66278 100644 --- a/src/Mod/Fem/App/FemPostPipeline.cpp +++ b/src/Mod/Fem/App/FemPostPipeline.cpp @@ -633,11 +633,11 @@ unsigned int FemPostPipeline::getFrameNumber() void FemPostPipeline::load(FemResultObject* res) { if (!res->Mesh.getValue()) { - Base::Console().Log("Result mesh object is empty.\n"); + Base::Console().log("Result mesh object is empty.\n"); return; } if (!res->Mesh.getValue()->isDerivedFrom()) { - Base::Console().Log("Result mesh object is not derived from Fem::FemMeshObject.\n"); + Base::Console().log("Result mesh object is not derived from Fem::FemMeshObject.\n"); return; } diff --git a/src/Mod/Fem/App/FemVTKTools.cpp b/src/Mod/Fem/App/FemVTKTools.cpp index e8cb884d93..d17b0b590a 100644 --- a/src/Mod/Fem/App/FemVTKTools.cpp +++ b/src/Mod/Fem/App/FemVTKTools.cpp @@ -155,8 +155,8 @@ void FemVTKTools::importVTKMesh(vtkSmartPointer dataset, FemMesh* me { const vtkIdType nPoints = dataset->GetNumberOfPoints(); const vtkIdType nCells = dataset->GetNumberOfCells(); - Base::Console().Log("%d nodes/points and %d cells/elements found!\n", nPoints, nCells); - Base::Console().Log("Build SMESH mesh out of the vtk mesh data.\n", nPoints, nCells); + Base::Console().log("%d nodes/points and %d cells/elements found!\n", nPoints, nCells); + Base::Console().log("Build SMESH mesh out of the vtk mesh data.\n", nPoints, nCells); // Now fill the SMESH datastructure SMESH_Mesh* smesh = mesh->getSMesh(); @@ -295,7 +295,7 @@ void FemVTKTools::importVTKMesh(vtkSmartPointer dataset, FemMesh* me // not handled cases default: { - Base::Console().Error( + Base::Console().error( "Only common 1D, 2D and 3D Cells are supported in VTK mesh import\n"); break; } @@ -306,13 +306,13 @@ void FemVTKTools::importVTKMesh(vtkSmartPointer dataset, FemMesh* me FemMesh* FemVTKTools::readVTKMesh(const char* filename, FemMesh* mesh) { Base::TimeElapsed Start; - Base::Console().Log("Start: read FemMesh from VTK unstructuredGrid ======================\n"); + Base::Console().log("Start: read FemMesh from VTK unstructuredGrid ======================\n"); Base::FileInfo f(filename); if (f.hasExtension("vtu")) { vtkSmartPointer dataset = readVTKFile(filename); if (!dataset.Get()) { - Base::Console().Error("Failed to load file %s\n", filename); + Base::Console().error("Failed to load file %s\n", filename); return nullptr; } importVTKMesh(dataset, mesh); @@ -320,7 +320,7 @@ FemMesh* FemVTKTools::readVTKMesh(const char* filename, FemMesh* mesh) else if (f.hasExtension("pvtu")) { vtkSmartPointer dataset = readVTKFile(filename); if (!dataset.Get()) { - Base::Console().Error("Failed to load file %s\n", filename); + Base::Console().error("Failed to load file %s\n", filename); return nullptr; } importVTKMesh(dataset, mesh); @@ -328,18 +328,18 @@ FemMesh* FemVTKTools::readVTKMesh(const char* filename, FemMesh* mesh) else if (f.hasExtension("vtk")) { vtkSmartPointer dataset = readVTKFile(filename); if (!dataset.Get()) { - Base::Console().Error("Failed to load file %s\n", filename); + Base::Console().error("Failed to load file %s\n", filename); return nullptr; } importVTKMesh(dataset, mesh); } else { - Base::Console().Error("file name extension is not supported\n"); + Base::Console().error("file name extension is not supported\n"); return nullptr; } // Mesh should link to the part feature, in order to set up FemConstraint - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); return mesh; } @@ -348,7 +348,7 @@ void exportFemMeshEdges(vtkSmartPointer& elemArray, std::vector& types, const SMDS_EdgeIteratorPtr& aEdgeIter) { - Base::Console().Log(" Start: VTK mesh builder edges.\n"); + Base::Console().log(" Start: VTK mesh builder edges.\n"); while (aEdgeIter->more()) { const SMDS_MeshEdge* aEdge = aEdgeIter->next(); @@ -365,14 +365,14 @@ void exportFemMeshEdges(vtkSmartPointer& elemArray, } } - Base::Console().Log(" End: VTK mesh builder edges.\n"); + Base::Console().log(" End: VTK mesh builder edges.\n"); } void exportFemMeshFaces(vtkSmartPointer& elemArray, std::vector& types, const SMDS_FaceIteratorPtr& aFaceIter) { - Base::Console().Log(" Start: VTK mesh builder faces.\n"); + Base::Console().log(" Start: VTK mesh builder faces.\n"); while (aFaceIter->more()) { const SMDS_MeshFace* aFace = aFaceIter->next(); @@ -397,14 +397,14 @@ void exportFemMeshFaces(vtkSmartPointer& elemArray, } } - Base::Console().Log(" End: VTK mesh builder faces.\n"); + Base::Console().log(" End: VTK mesh builder faces.\n"); } void exportFemMeshCells(vtkSmartPointer& elemArray, std::vector& types, const SMDS_VolumeIteratorPtr& aVolIter) { - Base::Console().Log(" Start: VTK mesh builder volumes.\n"); + Base::Console().log(" Start: VTK mesh builder volumes.\n"); while (aVolIter->more()) { const SMDS_MeshVolume* aVol = aVolIter->next(); @@ -438,7 +438,7 @@ void exportFemMeshCells(vtkSmartPointer& elemArray, } } - Base::Console().Log(" End: VTK mesh builder volumes.\n"); + Base::Console().log(" End: VTK mesh builder volumes.\n"); } void FemVTKTools::exportVTKMesh(const FemMesh* mesh, @@ -447,12 +447,12 @@ void FemVTKTools::exportVTKMesh(const FemMesh* mesh, float scale) { - Base::Console().Log("Start: VTK mesh builder ======================\n"); + Base::Console().log("Start: VTK mesh builder ======================\n"); const SMESH_Mesh* smesh = mesh->getSMesh(); const SMESHDS_Mesh* meshDS = smesh->GetMeshDS(); // nodes - Base::Console().Log(" Start: VTK mesh builder nodes.\n"); + Base::Console().log(" Start: VTK mesh builder nodes.\n"); vtkSmartPointer points = vtkSmartPointer::New(); SMDS_NodeIteratorPtr aNodeIter = meshDS->nodesIterator(); @@ -472,10 +472,10 @@ void FemVTKTools::exportVTKMesh(const FemMesh* mesh, grid->SetPoints(points); // nodes debugging const SMDS_MeshInfo& info = meshDS->GetMeshInfo(); - Base::Console().Log(" Size of nodes in SMESH grid: %i.\n", info.NbNodes()); + Base::Console().log(" Size of nodes in SMESH grid: %i.\n", info.NbNodes()); const vtkIdType nNodes = grid->GetNumberOfPoints(); - Base::Console().Log(" Size of nodes in VTK grid: %i.\n", nNodes); - Base::Console().Log(" End: VTK mesh builder nodes.\n"); + Base::Console().log(" Size of nodes in VTK grid: %i.\n", nNodes); + Base::Console().log(" End: VTK mesh builder nodes.\n"); vtkSmartPointer elemArray = vtkSmartPointer::New(); std::vector types; @@ -512,19 +512,19 @@ void FemVTKTools::exportVTKMesh(const FemMesh* mesh, grid->SetCells(types.data(), elemArray); } - Base::Console().Log("End: VTK mesh builder ======================\n"); + Base::Console().log("End: VTK mesh builder ======================\n"); } void FemVTKTools::writeVTKMesh(const char* filename, const FemMesh* mesh, bool highest) { Base::TimeElapsed Start; - Base::Console().Log("Start: write FemMesh from VTK unstructuredGrid ======================\n"); + Base::Console().log("Start: write FemMesh from VTK unstructuredGrid ======================\n"); Base::FileInfo f(filename); vtkSmartPointer grid = vtkSmartPointer::New(); exportVTKMesh(mesh, grid, highest); - Base::Console().Log("Start: writing mesh data ======================\n"); + Base::Console().log("Start: writing mesh data ======================\n"); if (f.hasExtension("vtu")) { writeVTKFile(filename, grid); } @@ -532,10 +532,10 @@ void FemVTKTools::writeVTKMesh(const char* filename, const FemMesh* mesh, bool h writeVTKFile(filename, grid); } else { - Base::Console().Error("file name extension is not supported to write VTK\n"); + Base::Console().error("file name extension is not supported to write VTK\n"); } - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } @@ -544,7 +544,7 @@ App::DocumentObject* getObjectByType(const Base::Type type) { App::Document* pcDoc = App::GetApplication().getActiveDocument(); if (!pcDoc) { - Base::Console().Message("No active document is found thus created\n"); + Base::Console().message("No active document is found thus created\n"); pcDoc = App::GetApplication().newDocument(); } App::DocumentObject* obj = pcDoc->getActiveObject(); @@ -568,7 +568,7 @@ App::DocumentObject* createObjectByType(const Base::Type type) { App::Document* pcDoc = App::GetApplication().getActiveDocument(); if (!pcDoc) { - Base::Console().Message("No active document is found thus created\n"); + Base::Console().message("No active document is found thus created\n"); pcDoc = App::GetApplication().newDocument(); } App::DocumentObject* obj = pcDoc->getActiveObject(); @@ -587,7 +587,7 @@ App::DocumentObject* createObjectByType(const Base::Type type) App::DocumentObject* FemVTKTools::readResult(const char* filename, App::DocumentObject* res) { Base::TimeElapsed Start; - Base::Console().Log( + Base::Console().log( "Start: read FemResult with FemMesh from VTK file ======================\n"); Base::FileInfo f(filename); @@ -599,12 +599,12 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document ds = readVTKFile(filename); } else { - Base::Console().Error("file name extension is not supported\n"); + Base::Console().error("file name extension is not supported\n"); } App::Document* pcDoc = App::GetApplication().getActiveDocument(); if (!pcDoc) { - Base::Console().Message("No active document is found thus created\n"); + Base::Console().message("No active document is found thus created\n"); pcDoc = App::GetApplication().newDocument(); } App::DocumentObject* obj = pcDoc->getActiveObject(); @@ -613,13 +613,13 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document App::DocumentObject* result = nullptr; if (res) { - Base::Console().Message( + Base::Console().message( "FemResultObject pointer is NULL, trying to get the active object\n"); if (obj->getTypeId() == Base::Type::fromName("Fem::FemResultObjectPython")) { result = obj; } else { - Base::Console().Message("the active object is not the correct type, do nothing\n"); + Base::Console().message("the active object is not the correct type, do nothing\n"); return nullptr; } } @@ -642,9 +642,9 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document } pcDoc->recompute(); - Base::Console().Log(" %f: Done \n", + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); - Base::Console().Log("End: read FemResult with FemMesh from VTK file ======================\n"); + Base::Console().log("End: read FemResult with FemMesh from VTK file ======================\n"); return result; } @@ -655,18 +655,18 @@ void FemVTKTools::writeResult(const char* filename, const App::DocumentObject* r if (!res) { App::Document* pcDoc = App::GetApplication().getActiveDocument(); if (!pcDoc) { - Base::Console().Message("No active document is found thus do nothing and return\n"); + Base::Console().message("No active document is found thus do nothing and return\n"); return; } res = pcDoc->getActiveObject(); // type checking is done by caller } if (!res) { - Base::Console().Error("Result object pointer is invalid and it is not active object"); + Base::Console().error("Result object pointer is invalid and it is not active object"); return; } Base::TimeElapsed Start; - Base::Console().Log("Start: write FemResult to VTK unstructuredGrid dataset =======\n"); + Base::Console().log("Start: write FemResult to VTK unstructuredGrid dataset =======\n"); Base::FileInfo f(filename); // mesh @@ -677,7 +677,7 @@ void FemVTKTools::writeResult(const char* filename, const App::DocumentObject* r static_cast(mesh->getPropertyByName("FemMesh"))->getValue(); FemVTKTools::exportVTKMesh(&fmesh, grid); - Base::Console().Log(" %f: vtk mesh builder finished\n", + Base::Console().log(" %f: vtk mesh builder finished\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // result @@ -690,12 +690,12 @@ void FemVTKTools::writeResult(const char* filename, const App::DocumentObject* r writeVTKFile(filename, grid); } else { - Base::Console().Error("file name extension is not supported to write VTK\n"); + Base::Console().error("file name extension is not supported to write VTK\n"); } - Base::Console().Log(" %f: writing result object to vtk finished\n", + Base::Console().log(" %f: writing result object to vtk finished\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); - Base::Console().Log("End: write FemResult to VTK unstructuredGrid dataset =======\n"); + Base::Console().log("End: write FemResult to VTK unstructuredGrid dataset =======\n"); } @@ -779,7 +779,7 @@ std::map _getFreeCADMechResultScalarProperties() void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, App::DocumentObject* result) { - Base::Console().Log("Start: import vtk result file data into a FreeCAD result object.\n"); + Base::Console().log("Start: import vtk result file data into a FreeCAD result object.\n"); std::map vectors = _getFreeCADMechResultVectorProperties(); std::map scalars = _getFreeCADMechResultScalarProperties(); @@ -789,7 +789,7 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, vtkSmartPointer pd = dataset->GetPointData(); if (pd->GetNumberOfArrays() == 0) { - Base::Console().Error("No point data array is found in vtk data set, do nothing\n"); + Base::Console().error("No point data array is found in vtk data set, do nothing\n"); // if pointData is empty, data may be in cellDate, // cellData -> pointData interpolation is possible in VTK return; @@ -803,7 +803,7 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, } static_cast(result->getPropertyByName("NodeNumbers")) ->setValues(nodeIds); - Base::Console().Log(" NodeNumbers have been filled with values.\n"); + Base::Console().log(" NodeNumbers have been filled with values.\n"); // vectors for (const auto& it : vectors) { @@ -822,18 +822,18 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, } // PropertyVectorList will not show up in PropertyEditor vector_list->setValues(vec); - Base::Console().Log(" A PropertyVectorList has been filled with values: %s\n", + Base::Console().log(" A PropertyVectorList has been filled with values: %s\n", it.first.c_str()); } else { - Base::Console().Error("static_cast((result->" + Base::Console().error("static_cast((result->" "getPropertyByName(\"%s\")) failed.\n", it.first.c_str()); continue; } } else { - Base::Console().Message(" PropertyVectorList NOT found in vkt file data: %s\n", + Base::Console().message(" PropertyVectorList NOT found in vkt file data: %s\n", it.first.c_str()); } } @@ -845,7 +845,7 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, App::PropertyFloatList* field = static_cast( result->getPropertyByName(scalar.first.c_str())); if (!field) { - Base::Console().Error("static_cast((result->" + Base::Console().error("static_cast((result->" "getPropertyByName(\"%s\")) failed.\n", scalar.first.c_str()); continue; @@ -864,11 +864,11 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, } } field->setValues(values); - Base::Console().Log(" A PropertyFloatList has been filled with vales: %s\n", + Base::Console().log(" A PropertyFloatList has been filled with vales: %s\n", scalar.first.c_str()); } else { - Base::Console().Message(" PropertyFloatList NOT found in vkt file data %s\n", + Base::Console().message(" PropertyFloatList NOT found in vkt file data %s\n", scalar.first.c_str()); } } @@ -876,14 +876,14 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, // stats // stats are added by importVTKResults - Base::Console().Log("End: import vtk result file data into a FreeCAD result object.\n"); + Base::Console().log("End: import vtk result file data into a FreeCAD result object.\n"); } void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, vtkSmartPointer grid) { - Base::Console().Log("Start: Create VTK result data from FreeCAD result data.\n"); + Base::Console().log("Start: Create VTK result data from FreeCAD result data.\n"); std::map vectors = _getFreeCADMechResultVectorProperties(); std::map scalars = _getFreeCADMechResultScalarProperties(); @@ -897,7 +897,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, // filled with points. Then the mapping must be correct) App::DocumentObject* meshObj = res->Mesh.getValue(); if (!meshObj || !meshObj->isDerivedFrom()) { - Base::Console().Error("Result object does not correctly link to mesh"); + Base::Console().error("Result object does not correctly link to mesh"); return; } const SMESH_Mesh* smesh = static_cast(meshObj)->FemMesh.getValue().getSMesh(); @@ -916,7 +916,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, field = static_cast(res->getPropertyByName(it.first.c_str())); } else { - Base::Console().Error(" PropertyVectorList not found: %s\n", it.first.c_str()); + Base::Console().error(" PropertyVectorList not found: %s\n", it.first.c_str()); } if (field && field->getSize() > 0) { @@ -950,13 +950,13 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, data->SetTuple(node->GetID() - 1, tuple); } grid->GetPointData()->AddArray(data); - Base::Console().Log( + Base::Console().log( " The PropertyVectorList %s was exported to VTK vector list: %s\n", it.first.c_str(), it.second.c_str()); } else if (field) { - Base::Console().Log(" PropertyVectorList NOT exported to vtk: %s size is: %i\n", + Base::Console().log(" PropertyVectorList NOT exported to vtk: %s size is: %i\n", it.first.c_str(), field->getSize()); } @@ -970,7 +970,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, static_cast(res->getPropertyByName(scalar.first.c_str())); } else { - Base::Console().Error("PropertyFloatList %s not found \n", scalar.first.c_str()); + Base::Console().error("PropertyFloatList %s not found \n", scalar.first.c_str()); } if (field && field->getSize() > 0) { @@ -1019,19 +1019,19 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, } grid->GetPointData()->AddArray(data); - Base::Console().Log( + Base::Console().log( " The PropertyFloatList %s was exported to VTK scalar list: %s\n", scalar.first.c_str(), scalar.second.c_str()); } else if (field) { - Base::Console().Log(" PropertyFloatList NOT exported to vtk: %s size is: %i\n", + Base::Console().log(" PropertyFloatList NOT exported to vtk: %s size is: %i\n", scalar.first.c_str(), field->getSize()); } } - Base::Console().Log("End: Create VTK result data from FreeCAD result data.\n"); + Base::Console().log("End: Create VTK result data from FreeCAD result data.\n"); } @@ -1543,7 +1543,7 @@ void readResults(std::ifstream& ifstr, } } catch (const std::out_of_range&) { - Base::Console().Warning("Invalid node: %d\n", node); + Base::Console().warning("Invalid node: %d\n", node); } ++countNodes; } diff --git a/src/Mod/Fem/App/PropertyPostDataObject.cpp b/src/Mod/Fem/App/PropertyPostDataObject.cpp index b8d953fcca..cbcb914552 100644 --- a/src/Mod/Fem/App/PropertyPostDataObject.cpp +++ b/src/Mod/Fem/App/PropertyPostDataObject.cpp @@ -42,6 +42,12 @@ #include #endif +#ifdef FC_USE_VTK_PYTHON +#include +#else +#include +#endif + #include #include #include @@ -162,12 +168,39 @@ int PropertyPostDataObject::getDataType() PyObject* PropertyPostDataObject::getPyObject() { - // TODO: fetch the vtk python object from the data set and return it - return Py::new_reference_to(Py::None()); +#ifdef FC_USE_VTK_PYTHON + // create a copy first + auto copy = static_cast(Copy()); + + // get the data python wrapper + PyObject* py_dataset = vtkPythonUtil::GetObjectFromPointer(copy->getValue()); + auto result = Py::new_reference_to(py_dataset); + delete copy; + + return result; +#else + PyErr_SetString(PyExc_NotImplementedError, "VTK python wrapper not available"); + Py_Return; +#endif } -void PropertyPostDataObject::setPyObject(PyObject* /*value*/) -{} +void PropertyPostDataObject::setPyObject(PyObject* value) +{ +#ifdef FC_USE_VTK_PYTHON + vtkObjectBase* obj = vtkPythonUtil::GetPointerFromObject(value, "vtkDataObject"); + if (!obj) { + throw Base::TypeError("Can only set vtkDataObject"); + } + auto dobj = static_cast(obj); + createDataObjectByExternalType(dobj); + + aboutToSetValue(); + m_dataObject->DeepCopy(dobj); + hasSetValue(); +#else + throw Base::NotImplementedError(); +#endif +} App::Property* PropertyPostDataObject::Copy() const { @@ -375,12 +408,12 @@ void PropertyPostDataObject::SaveDocFile(Base::Writer& writer) const App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().Error("Dataset of '%s' cannot be written to vtk file '%s'\n", + Base::Console().error("Dataset of '%s' cannot be written to vtk file '%s'\n", obj->Label.getValue(), fi.filePath().c_str()); } else { - Base::Console().Error("Cannot save vtk file '%s'\n", fi.filePath().c_str()); + Base::Console().error("Cannot save vtk file '%s'\n", fi.filePath().c_str()); } std::stringstream ss; @@ -501,12 +534,12 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader& reader) App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().Error("Dataset file '%s' with data of '%s' seems to be empty\n", + Base::Console().error("Dataset file '%s' with data of '%s' seems to be empty\n", fi.filePath().c_str(), obj->Label.getValue()); } else { - Base::Console().Warning("Loaded Dataset file '%s' seems to be empty\n", + Base::Console().warning("Loaded Dataset file '%s' seems to be empty\n", fi.filePath().c_str()); } } @@ -518,7 +551,7 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader& reader) } } else { - Base::Console().Error( + Base::Console().error( "Dataset file '%s' is of unsupported type: %s. Data not loaded.\n", fi.filePath().c_str(), extension); diff --git a/src/Mod/Fem/CMakeLists.txt b/src/Mod/Fem/CMakeLists.txt index 1e30655868..e90422449e 100755 --- a/src/Mod/Fem/CMakeLists.txt +++ b/src/Mod/Fem/CMakeLists.txt @@ -1,6 +1,12 @@ if(BUILD_FEM_VTK) add_definitions(-DFC_USE_VTK) + + # we may use VTK but do not have the python wrappers available + if(BUILD_FEM_VTK_PYTHON) + add_definitions(-DFC_USE_VTK_PYTHON) + endif(BUILD_FEM_VTK_PYTHON) + endif(BUILD_FEM_VTK) @@ -207,6 +213,13 @@ SET(FemObjects_SRCS femobjects/solver_ccxtools.py ) +if(BUILD_FEM_VTK_PYTHON) + SET(FemObjects_SRCS + ${FemObjects_SRCS} + femobjects/post_glyphfilter.py + ) +endif(BUILD_FEM_VTK_PYTHON) + SET(FemResult_SRCS femresult/__init__.py femresult/resulttools.py @@ -609,6 +622,13 @@ SET(FemGuiTaskPanels_SRCS femtaskpanels/task_solver_ccxtools.py ) +if(BUILD_FEM_VTK_PYTHON) + SET(FemGuiTaskPanels_SRCS + ${FemGuiTaskPanels_SRCS} + femtaskpanels/task_post_glyphfilter.py + ) +endif(BUILD_FEM_VTK_PYTHON) + SET(FemGuiTests_SRCS femtest/gui/__init__.py femtest/gui/test_open.py @@ -619,6 +639,7 @@ SET(FemGuiUtils_SRCS femguiutils/disambiguate_solid_selection.py femguiutils/migrate_gui.py femguiutils/selection_widgets.py + femguiutils/vtk_module_handling.py ) SET(FemGuiViewProvider_SRCS @@ -659,6 +680,13 @@ SET(FemGuiViewProvider_SRCS femviewprovider/view_solver_ccxtools.py ) +if(BUILD_FEM_VTK_PYTHON) + SET(FemGuiViewProvider_SRCS + ${FemGuiViewProvider_SRCS} + femviewprovider/view_post_glyphfilter.py + ) +endif(BUILD_FEM_VTK_PYTHON) + SET(FemGuiPreferencePages_SRCS fempreferencepages/__init__.py fempreferencepages/dlg_settings_netgen.py diff --git a/src/Mod/Fem/Gui/AppFemGui.cpp b/src/Mod/Fem/Gui/AppFemGui.cpp index 65364059eb..139fa2a4ef 100644 --- a/src/Mod/Fem/Gui/AppFemGui.cpp +++ b/src/Mod/Fem/Gui/AppFemGui.cpp @@ -104,7 +104,7 @@ PyMOD_INIT_FUNC(FemGui) } PyObject* mod = FemGui::initModule(); - Base::Console().Log("Loading GUI of Fem module... done\n"); + Base::Console().log("Loading GUI of Fem module... done\n"); // instantiating the commands CreateFemCommands(); @@ -161,6 +161,8 @@ PyMOD_INIT_FUNC(FemGui) #ifdef FC_USE_VTK FemGui::ViewProviderFemPostObject ::init(); FemGui::ViewProviderFemPostPipeline ::init(); + FemGui::ViewProviderFemPostFilterPythonBase ::init(); + FemGui::ViewProviderPostFilterPython ::init(); FemGui::ViewProviderFemPostBranchFilter ::init(); FemGui::ViewProviderFemPostCalculator ::init(); FemGui::ViewProviderFemPostClip ::init(); diff --git a/src/Mod/Fem/Gui/CMakeLists.txt b/src/Mod/Fem/Gui/CMakeLists.txt index 2a83b2f50e..7abc3b4df0 100755 --- a/src/Mod/Fem/Gui/CMakeLists.txt +++ b/src/Mod/Fem/Gui/CMakeLists.txt @@ -36,15 +36,24 @@ set(FemGui_LIBS generate_from_xml(ViewProviderFemConstraintPy) generate_from_xml(ViewProviderFemMeshPy) generate_from_xml(ViewProviderFemPostPipelinePy) +generate_from_xml(ViewProviderFemPostFilterPy) SET(Python_SRCS ViewProviderFemConstraintPy.xml ViewProviderFemConstraintPyImp.cpp ViewProviderFemMeshPy.xml ViewProviderFemMeshPyImp.cpp - ViewProviderFemPostPipelinePy.xml - ViewProviderFemPostPipelinePyImp.cpp ) +if(BUILD_FEM_VTK) + set(Python_SRCS + ${Python_SRCS} + ViewProviderFemPostPipelinePy.xml + ViewProviderFemPostPipelinePyImp.cpp + ViewProviderFemPostFilterPy.xml + ViewProviderFemPostFilterPyImp.cpp + ) +endif(BUILD_FEM_VTK) + SOURCE_GROUP("Python" FILES ${Python_SRCS}) @@ -430,6 +439,7 @@ SET(FemGuiPythonUI_SRCS Resources/ui/ResultShow.ui Resources/ui/SolverCalculiX.ui Resources/ui/SolverCcxTools.ui + Resources/ui/TaskPostGlyph.ui ) ADD_CUSTOM_TARGET(FemPythonUi ALL diff --git a/src/Mod/Fem/Gui/Command.cpp b/src/Mod/Fem/Gui/Command.cpp index 04e7e66d4d..3711b1df7a 100644 --- a/src/Mod/Fem/Gui/Command.cpp +++ b/src/Mod/Fem/Gui/Command.cpp @@ -2675,11 +2675,11 @@ void CmdFemPostPipelineFromResult::activated(int) /* Gui::SelectionFilter ResultFilter("SELECT Fem::FemResultObject COUNT 1"); if (ResultFilter.match()) { - Base::Console().Message("Debug: `SELECT Fem::FemResultObject COUNT 1` has matched obj"); + Base::Console().message("Debug: `SELECT Fem::FemResultObject COUNT 1` has matched obj"); Fem::FemResultObject* result = static_cast(ResultFilter.Result[0][0].getObject()); //static_cast failed here - Base::Console().Message("Debug: FemResultObject pointer = %p", result ); + Base::Console().message("Debug: FemResultObject pointer = %p", result ); */ diff --git a/src/Mod/Fem/Gui/Resources/Fem.qrc b/src/Mod/Fem/Gui/Resources/Fem.qrc index f57b979456..7e15fdf17e 100755 --- a/src/Mod/Fem/Gui/Resources/Fem.qrc +++ b/src/Mod/Fem/Gui/Resources/Fem.qrc @@ -82,6 +82,7 @@ icons/FEM_PostFilterDataAtPoint.svg icons/FEM_PostFilterLinearizedStresses.svg icons/FEM_PostFilterWarp.svg + icons/FEM_PostFilterGlyph.svg icons/FEM_PostFrames.svg icons/FEM_PostBranchFilter.svg icons/FEM_PostPipelineFromResult.svg @@ -150,5 +151,6 @@ ui/ResultShow.ui ui/SolverCalculiX.ui ui/SolverCcxTools.ui + ui/TaskPostGlyph.ui diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterGlyph.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterGlyph.svg new file mode 100644 index 0000000000..980e51de21 --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterGlyph.svg @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + image/svg+xml + + + + [Alexander Gryson] + + + fem-warp + 2017-03-11 + https://www.freecad.org/wiki/index.php?title=Artwork + + + FreeCAD + + + FreeCAD/src/Mod/ + + + FreeCAD LGPL2+ + + + https://www.gnu.org/copyleft/lesser.html + + + [agryson] Alexander Gryson + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/ui/TaskPostGlyph.ui b/src/Mod/Fem/Gui/Resources/ui/TaskPostGlyph.ui new file mode 100644 index 0000000000..303f3c368f --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/ui/TaskPostGlyph.ui @@ -0,0 +1,355 @@ + + + TaskPostGlyph + + + + 0 + 0 + 440 + 428 + + + + Glyph settings + + + + + + + + The form of the glyph + + + Form + + + + + + + + 0 + 0 + + + + The form of the glyph + + + + Arrow + + + + + Cube + + + + + + + + Which vector field is used to orient the glyphs + + + Orientation + + + + + + + + 0 + 0 + + + + Which vector field is used to orient the glyphs + + + + None + + + + + + + + + + + 1 + 0 + + + + Sca&le + + + false + + + false + + + false + + + + + + If the scale data is a vector this property decides if the glyph is scaled by vector magnitude or by the individual components + + + Data + + + + + + + + + + 1 + 0 + + + + If the scale data is a vector this property decides if the glyph is scaled by vector magnitude or by the individual components + + + + None + + + + + + + + + + A constant multiplier the glyphs are scaled with + + + Factor + + + + + + + + + + 0 + 0 + + + + A constant multiplier the glyphs are scaled with + + + 99999999999.000000000000000 + + + 0.000000000000000 + + + QAbstractSpinBox::StepType::AdaptiveDecimalStepType + + + 1.000000000000000 + + + + + + + + + + + Changes the scale factor by +/- 50% of the set scale factor + + + 100 + + + 5 + + + 50 + + + Qt::Orientation::Horizontal + + + + + + + + + + 1 + 0 + + + + Which data field is used to scale the glyphs + + + + Not a vector + + + + + By magnitude + + + + + By components + + + + + + + + + + + Vertex Mas&king + + + false + + + false + + + + + + Which vertices are used as glyph locations + + + Mode + + + + + + + true + + + + 0 + 0 + + + + Defines the maximal number of vertices used for "Uniform Sampling" masking mode + + + 1 + + + 999999999 + + + + + + + true + + + Define the stride for "Every Nth" masking mode + + + Stride + + + + + + + true + + + Defines the maximal number of vertices used for "Uniform Sampling" masking mode + + + Max + + + + + + + true + + + + 0 + 0 + + + + Define the stride for "Every Nth" masking mode + + + 1 + + + 999999999 + + + + + + + + 0 + 0 + + + + Which vertices are used as glyph locations + + + + All + + + + + Every Nth + + + + + Uniform Sampling + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/TaskCreateElementSet.cpp b/src/Mod/Fem/Gui/TaskCreateElementSet.cpp index ae47593322..04c23a4512 100644 --- a/src/Mod/Fem/Gui/TaskCreateElementSet.cpp +++ b/src/Mod/Fem/Gui/TaskCreateElementSet.cpp @@ -219,10 +219,10 @@ void myCopyResultsMesh(std::string oldName, std::string newName) { int error = 0; - Base::Console().Warning("copy: %s and %s\n", oldName.c_str(), newName.c_str()); + Base::Console().warning("copy: %s and %s\n", oldName.c_str(), newName.c_str()); if (oldName.compare(newName) == 0 && error == 0) { error = 1; - Base::Console().Warning("Can't copy ResultMesh to ResultMesh: %s and %s\n", + Base::Console().warning("Can't copy ResultMesh to ResultMesh: %s and %s\n", oldName.c_str(), newName.c_str()); QMessageBox::warning( @@ -234,7 +234,7 @@ void myCopyResultsMesh(std::string oldName, std::string newName) if ((oldName.find("Result") == std::string::npos || newName.find("Result") == std::string::npos) && error == 0) { error = 1; - Base::Console().Warning("Mesh must be results: %s\n", oldName.c_str()); + Base::Console().warning("Mesh must be results: %s\n", oldName.c_str()); QMessageBox::warning( Gui::getMainWindow(), // QMessageBox::warning(Gui::MainWindow(), @@ -746,7 +746,7 @@ void TaskCreateElementSet::DefineNodes(const Base::Polygon2d& polygon, erase = nElements - keepElement; } if (keepElement > 0) { - Base::Console().Warning("Number of Elements Kept: %d, Number of Elements Erased: %d\n", + Base::Console().warning("Number of Elements Kept: %d, Number of Elements Erased: %d\n", keepElement, erase); writeToFile(inp_file, newMeshDS, nodeNumbers, nodeCoords, maxNode, requiredType); diff --git a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp index cd512af306..80369b37ff 100644 --- a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp +++ b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp @@ -203,7 +203,7 @@ void TaskCreateNodeSet::onSelectionChanged(const Gui::SelectionChanges& msg) tempSet.clear(); - Base::Console().Message("Picked Element:%i Face:%i\n", elem, face); + Base::Console().message("Picked Element:%i Face:%i\n", elem, face); if (!ui->checkBox_Add->isChecked()) { diff --git a/src/Mod/Fem/Gui/TaskDlgAnalysis.cpp b/src/Mod/Fem/Gui/TaskDlgAnalysis.cpp index a1f8d6a8f0..9fbaeaafcc 100644 --- a/src/Mod/Fem/Gui/TaskDlgAnalysis.cpp +++ b/src/Mod/Fem/Gui/TaskDlgAnalysis.cpp @@ -79,7 +79,7 @@ bool TaskDlgAnalysis::accept() // return true; //} // catch (const Base::Exception& e) { - // Base::Console().Warning("TaskDlgAnalysis::accept(): %s\n", e.what()); + // Base::Console().warning("TaskDlgAnalysis::accept(): %s\n", e.what()); //} return false; diff --git a/src/Mod/Fem/Gui/TaskDlgCreateElementSet.cpp b/src/Mod/Fem/Gui/TaskDlgCreateElementSet.cpp index f591ff014f..85c764ed69 100644 --- a/src/Mod/Fem/Gui/TaskDlgCreateElementSet.cpp +++ b/src/Mod/Fem/Gui/TaskDlgCreateElementSet.cpp @@ -76,7 +76,7 @@ bool TaskDlgCreateElementSet::accept() return true; } catch (const Base::Exception& e) { - Base::Console().Warning("TaskDlgCreateElementSet::accept(): %s\n", e.what()); + Base::Console().warning("TaskDlgCreateElementSet::accept(): %s\n", e.what()); } return false; diff --git a/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.cpp b/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.cpp index ac507e7198..5fb6733095 100644 --- a/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.cpp +++ b/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.cpp @@ -78,7 +78,7 @@ bool TaskDlgCreateNodeSet::accept() return true; } catch (const Base::Exception& e) { - Base::Console().Warning("TaskDlgCreateNodeSet::accept(): %s\n", e.what()); + Base::Console().warning("TaskDlgCreateNodeSet::accept(): %s\n", e.what()); } return false; diff --git a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp index 3f047bacc0..068209de3b 100644 --- a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp +++ b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp @@ -85,7 +85,7 @@ void TaskDlgMeshShapeNetgen::clicked(int button) } } catch (const Base::Exception& e) { - Base::Console().Warning("FemMeshShapeNetgenObject::execute(): %s\n", e.what()); + Base::Console().warning("FemMeshShapeNetgenObject::execute(): %s\n", e.what()); } } @@ -120,7 +120,7 @@ bool TaskDlgMeshShapeNetgen::accept() return true; } catch (const Base::Exception& e) { - Base::Console().Warning("TaskDlgMeshShapeNetgen::accept(): %s\n", e.what()); + Base::Console().warning("TaskDlgMeshShapeNetgen::accept(): %s\n", e.what()); } return false; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp index 2db9ff25ee..cbec0958a9 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp @@ -235,7 +235,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } } else { - Base::Console().Log("FemAnalysis object is not activated or no FemAnalysis in the active " + Base::Console().log("FemAnalysis object is not activated or no FemAnalysis in the active " "document, mesh dimension is unknown\n"); dimension = -1; // unknown dimension of mesh } @@ -296,7 +296,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } else { ui->tabThermalBoundary->setEnabled(false); // could be hidden - // Base::Console().Message("retrieve solver property HeatTransferring as false\n"); + // Base::Console().message("retrieve solver property HeatTransferring as false\n"); } } else { @@ -327,7 +327,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } } else { - Base::Console().Warning( + Base::Console().warning( "No solver object inside FemAnalysis object, default to non-thermal, non-turbulence\n"); } ui->tabWidget->setTabText(0, tr("Basic")); @@ -417,7 +417,7 @@ void TaskFemConstraintFluidBoundary::updateBoundaryTypeUI() pcConstraint->Reversed.setValue(false); // outlet must point outward } else { - Base::Console().Error("Error: Fluid boundary type `%s` is not defined\n", + Base::Console().error("Error: Fluid boundary type `%s` is not defined\n", boundaryType.c_str()); } // std::string subtypeLabel = boundaryType + std::string(" type"); @@ -495,7 +495,7 @@ void TaskFemConstraintFluidBoundary::updateSubtypeUI() ui->tabBasicBoundary->setEnabled(true); } else { - Base::Console().Error("Fluid boundary type `%s` is not defined\n", boundaryType.c_str()); + Base::Console().error("Fluid boundary type `%s` is not defined\n", boundaryType.c_str()); } } @@ -519,7 +519,7 @@ void TaskFemConstraintFluidBoundary::updateTurbulenceUI() ui->labelTurbulentLengthValue->setText(tr("Hydraulic Diameter [m]")); } else { - Base::Console().Error("turbulence Spec type `%s` is not defined\n", turbulenceSpec.c_str()); + Base::Console().error("turbulence Spec type `%s` is not defined\n", turbulenceSpec.c_str()); } } @@ -560,7 +560,7 @@ void TaskFemConstraintFluidBoundary::updateThermalBoundaryUI() ui->spinTemperatureValue->setEnabled(true); } else { - Base::Console().Error("Thermal boundary type `%s` is not defined\n", + Base::Console().error("Thermal boundary type `%s` is not defined\n", thermalBoundaryType.c_str()); } } @@ -581,7 +581,7 @@ void TaskFemConstraintFluidBoundary::onBoundaryTypeChanged() bool ret = pcConstraint->recomputeFeature(); if (!ret) { std::string boundaryType = ui->comboBoundaryType->currentText().toStdString(); - Base::Console().Error("Fluid boundary recomputationg failed for boundaryType `%s` \n", + Base::Console().error("Fluid boundary recomputationg failed for boundaryType `%s` \n", boundaryType.c_str()); } } @@ -1080,7 +1080,7 @@ bool TaskDlgFemConstraintFluidBoundary::accept() } } else { - Base::Console().Warning("FemSolverObject is not found in the FemAnalysis object, " + Base::Console().warning("FemSolverObject is not found in the FemAnalysis object, " "thermal and turbulence setting is not accepted\n"); } } diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.cpp b/src/Mod/Fem/Gui/TaskPostBoxes.cpp index fefe174507..805977f6d2 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.cpp +++ b/src/Mod/Fem/Gui/TaskPostBoxes.cpp @@ -203,29 +203,33 @@ void DataAlongLineMarker::customEvent(QEvent*) // *************************************************************************** // main task dialog -TaskPostBox::TaskPostBox(Gui::ViewProviderDocumentObject* view, - const QPixmap& icon, - const QString& title, - QWidget* parent) - : TaskBox(icon, title, true, parent) +TaskPostWidget::TaskPostWidget(Gui::ViewProviderDocumentObject* view, + const QPixmap& icon, + const QString& title, + QWidget* parent) + : QWidget(parent) , m_object(view->getObject()) , m_view(view) -{} +{ + setWindowTitle(title); + setWindowIcon(icon); + m_icon = icon; +} -TaskPostBox::~TaskPostBox() = default; +TaskPostWidget::~TaskPostWidget() = default; -bool TaskPostBox::autoApply() +bool TaskPostWidget::autoApply() { return FemSettings().getPostAutoRecompute(); } -App::Document* TaskPostBox::getDocument() const +App::Document* TaskPostWidget::getDocument() const { App::DocumentObject* obj = getObject(); return (obj ? obj->getDocument() : nullptr); } -void TaskPostBox::recompute() +void TaskPostWidget::recompute() { if (autoApply()) { App::Document* doc = getDocument(); @@ -235,7 +239,7 @@ void TaskPostBox::recompute() } } -void TaskPostBox::updateEnumerationList(App::PropertyEnumeration& prop, QComboBox* box) +void TaskPostWidget::updateEnumerationList(App::PropertyEnumeration& prop, QComboBox* box) { QStringList list; std::vector vec = prop.getEnumVector(); @@ -266,10 +270,20 @@ TaskDlgPost::~TaskDlgPost() = default; QDialogButtonBox::StandardButtons TaskDlgPost::getStandardButtons() const { - // check if we only have gui task boxes bool guionly = true; - for (auto it : m_boxes) { - guionly = guionly && it->isGuiTaskOnly(); + for (auto& widget : Content) { + if (auto task_box = dynamic_cast(widget)) { + + // get the task widget and check if it is a post widget + auto widget = task_box->groupLayout()->itemAt(0)->widget(); + if (auto post_widget = dynamic_cast(widget)) { + guionly = guionly && post_widget->isGuiTaskOnly(); + } + else { + // unknown panel, we can only assume + guionly = false; + } + } } if (!guionly) { @@ -285,7 +299,7 @@ void TaskDlgPost::connectSlots() // Connect emitAddedFunction() with slotAddedFunction() QObject* sender = nullptr; int indexSignal = 0; - for (const auto dlg : m_boxes) { + for (const auto dlg : Content) { indexSignal = dlg->metaObject()->indexOfSignal( QMetaObject::normalizedSignature("emitAddedFunction()")); if (indexSignal >= 0) { @@ -295,7 +309,7 @@ void TaskDlgPost::connectSlots() } if (sender) { - for (const auto dlg : m_boxes) { + for (const auto dlg : Content) { int indexSlot = dlg->metaObject()->indexOfSlot( QMetaObject::normalizedSignature("slotAddedFunction()")); if (indexSlot >= 0) { @@ -308,12 +322,6 @@ void TaskDlgPost::connectSlots() } } -void TaskDlgPost::appendBox(TaskPostBox* box) -{ - m_boxes.push_back(box); - Content.push_back(box); -} - void TaskDlgPost::open() { // only open a new command if none is pending (e.g. if the object was newly created) @@ -326,8 +334,14 @@ void TaskDlgPost::open() void TaskDlgPost::clicked(int button) { if (button == QDialogButtonBox::Apply) { - for (auto box : m_boxes) { - box->apply(); + for (auto& widget : Content) { + if (auto task_box = dynamic_cast(widget)) { + // get the task widget and check if it is a post widget + auto widget = task_box->groupLayout()->itemAt(0)->widget(); + if (auto post_widget = dynamic_cast(widget)) { + post_widget->apply(); + } + } } recompute(); } @@ -336,8 +350,14 @@ void TaskDlgPost::clicked(int button) bool TaskDlgPost::accept() { try { - for (auto& box : m_boxes) { - box->applyPythonCode(); + for (auto& widget : Content) { + if (auto task_box = dynamic_cast(widget)) { + // get the task widget and check if it is a post widget + auto widget = task_box->groupLayout()->itemAt(0)->widget(); + if (auto post_widget = dynamic_cast(widget)) { + post_widget->applyPythonCode(); + } + } } } catch (const Base::Exception& e) { @@ -377,19 +397,15 @@ void TaskDlgPost::modifyStandardButtons(QDialogButtonBox* box) // *************************************************************************** // box to set the coloring TaskPostDisplay::TaskPostDisplay(ViewProviderFemPostObject* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_ResultShow"), - tr("Result display options"), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_ResultShow"), QString(), parent) , ui(new Ui_TaskPostDisplay) { - // we need a separate container widget to add all controls to - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle( + tr("Result display options")); // set title here as setupUi overrides the constructor title setupConnections(); - this->groupLayout()->addWidget(proxy); - // update all fields updateEnumerationList(getTypedView()->DisplayMode, ui->Representation); @@ -463,16 +479,19 @@ void TaskPostDisplay::applyPythonCode() // *************************************************************************** // functions TaskPostFunction::TaskPostFunction(ViewProviderFemPostFunction* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("fem-post-geo-plane"), - tr("Implicit function"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("fem-post-geo-plane"), + tr("Implicit function"), + parent) { // we load the views widget FunctionWidget* w = getTypedView()->createControlWidget(); w->setParent(this); w->setViewProvider(getTypedView()); - this->groupLayout()->addWidget(w); + + QVBoxLayout* layout = new QVBoxLayout; + layout->addWidget(w); + setLayout(layout); } TaskPostFunction::~TaskPostFunction() = default; @@ -486,13 +505,12 @@ void TaskPostFunction::applyPythonCode() // *************************************************************************** // Frames TaskPostFrames::TaskPostFrames(ViewProviderFemPostObject* view, QWidget* parent) - : TaskPostBox(view, Gui::BitmapFactory().pixmap("FEM_PostFrames"), tr("Result Frames"), parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFrames"), QString(), parent) , ui(new Ui_TaskPostFrames) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); - this->groupLayout()->addWidget(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Result Frames")); setupConnections(); // populate the data @@ -548,16 +566,12 @@ void TaskPostFrames::applyPythonCode() // *************************************************************************** // Branch TaskPostBranch::TaskPostBranch(ViewProviderFemPostBranchFilter* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostBranchFilter"), - tr("Branch behaviour"), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostBranchFilter"), QString(), parent) , ui(new Ui_TaskPostBranch) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); - this->groupLayout()->addWidget(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Branch behaviour")); setupConnections(); // populate the data @@ -603,19 +617,17 @@ void TaskPostBranch::applyPythonCode() // data along line filter TaskPostDataAlongLine::TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterDataAlongLine"), - tr("Data along a line options"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterDataAlongLine"), + QString(), + parent) , ui(new Ui_TaskPostDataAlongLine) , marker(nullptr) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); - + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Data along a line options")); setupConnectionsStep1(); - this->groupLayout()->addWidget(proxy); QSize size = ui->point1X->sizeForText(QStringLiteral("000000000000")); ui->point1X->setMinimumWidth(size.width()); @@ -877,7 +889,7 @@ void TaskPostDataAlongLine::point1Changed(double) getObject()->GetAxisData(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -936,7 +948,7 @@ void TaskPostDataAlongLine::pointCallback(void* ud, SoEventCallback* n) if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = n->getPickedPoint(); if (!point) { - Base::Console().Message("No point picked.\n"); + Base::Console().message("No point picked.\n"); return; } @@ -1025,21 +1037,19 @@ plt.show()\n"; // *************************************************************************** // data at point filter TaskPostDataAtPoint::TaskPostDataAtPoint(ViewProviderFemPostDataAtPoint* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterDataAtPoint"), - tr("Data at point options"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterDataAtPoint"), + QString(), + parent) , viewer(nullptr) , connSelectPoint(QMetaObject::Connection()) , ui(new Ui_TaskPostDataAtPoint) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Data at point options")); setupConnections(); - this->groupLayout()->addWidget(proxy); - QSize size = ui->centerX->sizeForText(QStringLiteral("000000000000")); ui->centerX->setMinimumWidth(size.width()); ui->centerY->setMinimumWidth(size.width()); @@ -1194,7 +1204,7 @@ void TaskPostDataAtPoint::centerChanged(double) onFieldActivated(currentField); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -1211,7 +1221,7 @@ void TaskPostDataAtPoint::pointCallback(void* ud, SoEventCallback* n) if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = n->getPickedPoint(); if (!point) { - Base::Console().Message("No point picked.\n"); + Base::Console().message("No point picked.\n"); return; } @@ -1357,7 +1367,7 @@ void TaskPostDataAtPoint::showValue(double pointValue, const char* unitStr) QString posZ = ui->centerZ->text(); QString result = tr("%1 at (%2; %3; %4) is: %5 %6").arg(field, posX, posY, posZ, value, unit); - Base::Console().Message("%s\n", result.toUtf8().data()); + Base::Console().message("%s\n", result.toUtf8().data()); } std::string TaskPostDataAtPoint::toString(double val) const @@ -1382,10 +1392,10 @@ std::string TaskPostDataAtPoint::toString(double val) const TaskPostClip::TaskPostClip(ViewProviderFemPostClip* view, App::PropertyLink* function, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterClipRegion"), - tr("Clip region, choose implicit function"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterClipRegion"), + QString(), + parent) , ui(new Ui_TaskPostClip) { assert(function); @@ -1393,11 +1403,10 @@ TaskPostClip::TaskPostClip(ViewProviderFemPostClip* view, fwidget = nullptr; - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Clip region, choose implicit function")); setupConnections(); - this->groupLayout()->addWidget(proxy); // the layout for the container widget QVBoxLayout* layout = new QVBoxLayout(); @@ -1542,17 +1551,13 @@ void TaskPostClip::onInsideOutToggled(bool val) // *************************************************************************** // contours filter TaskPostContours::TaskPostContours(ViewProviderFemPostContours* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterContours"), - tr("Contours filter options"), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterContours"), QString(), parent) , ui(new Ui_TaskPostContours) { - // load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Contours filter options")); QMetaObject::connectSlotsByName(this); - this->groupLayout()->addWidget(proxy); auto obj = getObject(); @@ -1697,10 +1702,10 @@ void TaskPostContours::onRelaxationChanged(double value) // *************************************************************************** // cut filter TaskPostCut::TaskPostCut(ViewProviderFemPostCut* view, App::PropertyLink* function, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterCutFunction"), - tr("Function cut, choose implicit function"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterCutFunction"), + QString(), + parent) , ui(new Ui_TaskPostCut) { assert(function); @@ -1708,11 +1713,10 @@ TaskPostCut::TaskPostCut(ViewProviderFemPostCut* view, App::PropertyLink* functi fwidget = nullptr; - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Function cut, choose implicit function")); setupConnections(); - this->groupLayout()->addWidget(proxy); // the layout for the container widget QVBoxLayout* layout = new QVBoxLayout(); @@ -1836,17 +1840,16 @@ void TaskPostCut::onFunctionBoxCurrentIndexChanged(int idx) // *************************************************************************** // scalar clip filter TaskPostScalarClip::TaskPostScalarClip(ViewProviderFemPostScalarClip* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterClipScalar"), - tr("Scalar clip options"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterClipScalar"), + QString(), + parent) , ui(new Ui_TaskPostScalarClip) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Scalar clip options")); setupConnections(); - this->groupLayout()->addWidget(proxy); // load the default values updateEnumerationList(getTypedObject()->Scalars, ui->Scalar); @@ -1871,7 +1874,7 @@ TaskPostScalarClip::TaskPostScalarClip(ViewProviderFemPostScalarClip* view, QWid ui->Slider->blockSignals(true); ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); - Base::Console().Log("init: scalar_factor, slider_value: %f, %i: \n", + Base::Console().log("init: scalar_factor, slider_value: %f, %i: \n", scalar_factor, slider_value); } @@ -1961,17 +1964,13 @@ void TaskPostScalarClip::onInsideOutToggled(bool val) // *************************************************************************** // warp vector filter TaskPostWarpVector::TaskPostWarpVector(ViewProviderFemPostWarpVector* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterWarp"), - tr("Warp options"), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterWarp"), QString(), parent) , ui(new Ui_TaskPostWarpVector) { - // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + // setup the ui + ui->setupUi(this); + setWindowTitle(tr("Warp options")); setupConnections(); - this->groupLayout()->addWidget(proxy); // load the default values for warp display updateEnumerationList(getTypedObject()->Vector, ui->Vector); @@ -2005,7 +2004,7 @@ TaskPostWarpVector::TaskPostWarpVector(ViewProviderFemPostWarpVector* view, QWid (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100.; ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); - Base::Console().Log("init: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); + Base::Console().log("init: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); } TaskPostWarpVector::~TaskPostWarpVector() = default; @@ -2059,7 +2058,7 @@ void TaskPostWarpVector::onSliderValueChanged(int slider_value) ui->Value->blockSignals(true); ui->Value->setValue(warp_factor); ui->Value->blockSignals(false); - Base::Console().Log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); + Base::Console().log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); } void TaskPostWarpVector::onValueValueChanged(double warp_factor) @@ -2077,7 +2076,7 @@ void TaskPostWarpVector::onValueValueChanged(double warp_factor) (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100.; ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); - Base::Console().Log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); + Base::Console().log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); } void TaskPostWarpVector::onMaxValueChanged(double) @@ -2113,7 +2112,7 @@ void TaskPostWarpVector::onMaxValueChanged(double) ui->Value->blockSignals(true); ui->Value->setValue(warp_factor); ui->Value->blockSignals(false); - Base::Console().Log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); + Base::Console().log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); } */ } @@ -2136,17 +2135,15 @@ static const std::vector calculatorOperators = { "log", "pow", "sqrt", "iHat", "jHat", "kHat", "cross", "dot", "mag", "norm"}; TaskPostCalculator::TaskPostCalculator(ViewProviderFemPostCalculator* view, QWidget* parent) - : TaskPostBox(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterCalculator"), - tr("Calculator options"), - parent) + : TaskPostWidget(view, + Gui::BitmapFactory().pixmap("FEM_PostFilterCalculator"), + tr("Calculator options"), + parent) , ui(new Ui_TaskPostCalculator) { // we load the views widget - proxy = new QWidget(this); - ui->setupUi(proxy); + ui->setupUi(this); setupConnections(); - this->groupLayout()->addWidget(proxy); // load the default values auto obj = getObject(); diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.h b/src/Mod/Fem/Gui/TaskPostBoxes.h index a13f9a6d7e..d37742dd27 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.h +++ b/src/Mod/Fem/Gui/TaskPostBoxes.h @@ -131,18 +131,22 @@ protected: // *************************************************************************** // main task dialog -class TaskPostBox: public Gui::TaskView::TaskBox +class TaskPostWidget: public QWidget { - Q_OBJECT + // Q_OBJECT public: - TaskPostBox(Gui::ViewProviderDocumentObject* view, - const QPixmap& icon, - const QString& title, - QWidget* parent = nullptr); - ~TaskPostBox() override; + TaskPostWidget(Gui::ViewProviderDocumentObject* view, + const QPixmap& icon, + const QString& title = QString(), + QWidget* parent = nullptr); + ~TaskPostWidget() override; virtual void applyPythonCode() {}; + QPixmap getIcon() + { + return m_icon; + } virtual bool isGuiTaskOnly() { return false; @@ -184,6 +188,7 @@ protected: static void updateEnumerationList(App::PropertyEnumeration&, QComboBox* box); private: + QPixmap m_icon; App::DocumentObjectWeakPtrT m_object; Gui::ViewProviderWeakPtrT m_view; }; @@ -200,7 +205,6 @@ public: ~TaskDlgPost() override; void connectSlots(); - void appendBox(TaskPostBox* box); Gui::ViewProviderDocumentObject* getView() const { return *m_view; @@ -230,7 +234,6 @@ protected: protected: Gui::ViewProviderWeakPtrT m_view; - std::vector m_boxes; }; @@ -238,7 +241,7 @@ protected: // box to set the coloring class ViewProviderFemPostObject; -class TaskPostDisplay: public TaskPostBox +class TaskPostDisplay: public TaskPostWidget { Q_OBJECT @@ -261,7 +264,6 @@ private: void slotAddedFunction(); private: - QWidget* proxy; std::unique_ptr ui; }; @@ -270,7 +272,7 @@ private: // functions class ViewProviderFemPostFunction; -class TaskPostFunction: public TaskPostBox +class TaskPostFunction: public TaskPostWidget { Q_OBJECT @@ -283,7 +285,7 @@ public: // *************************************************************************** // frames -class TaskPostFrames: public TaskPostBox +class TaskPostFrames: public TaskPostWidget { Q_OBJECT @@ -297,7 +299,6 @@ private: void setupConnections(); void onSelectionChanged(); - QWidget* proxy; std::unique_ptr ui; }; @@ -311,7 +312,7 @@ private: // branch class ViewProviderFemPostBranchFilter; -class TaskPostBranch: public TaskPostBox +class TaskPostBranch: public TaskPostWidget { Q_OBJECT @@ -326,7 +327,6 @@ private: void onModeIndexChanged(int); void onOutputIndexChanged(int); - QWidget* proxy; std::unique_ptr ui; }; @@ -334,7 +334,7 @@ private: // data along line filter class ViewProviderFemPostDataAlongLine; -class TaskPostDataAlongLine: public TaskPostBox +class TaskPostDataAlongLine: public TaskPostWidget { Q_OBJECT @@ -362,7 +362,6 @@ private: private: std::string Plot(); std::string ObjectVisible(); - QWidget* proxy; std::unique_ptr ui; DataAlongLineMarker* marker; }; @@ -372,7 +371,7 @@ private: // data at point filter class ViewProviderFemPostDataAtPoint; -class TaskPostDataAtPoint: public TaskPostBox +class TaskPostDataAtPoint: public TaskPostWidget { Q_OBJECT @@ -400,7 +399,6 @@ private: std::string toString(double val) const; void showValue(double value, const char* unit); std::string objectVisible(bool visible) const; - QWidget* proxy; std::unique_ptr ui; }; @@ -409,7 +407,7 @@ private: // clip filter class ViewProviderFemPostClip; -class TaskPostClip: public TaskPostBox +class TaskPostClip: public TaskPostWidget { Q_OBJECT @@ -435,7 +433,6 @@ private: void collectImplicitFunctions(); // App::PropertyLink* m_functionProperty; - QWidget* proxy; std::unique_ptr ui; FunctionWidget* fwidget; }; @@ -445,7 +442,7 @@ private: // contours filter class ViewProviderFemPostContours; -class TaskPostContours: public TaskPostBox +class TaskPostContours: public TaskPostWidget { Q_OBJECT @@ -464,7 +461,6 @@ private: void onRelaxationChanged(double v); private: - QWidget* proxy; std::unique_ptr ui; bool blockVectorUpdate = false; void updateFields(); @@ -475,7 +471,7 @@ private: // cut filter class ViewProviderFemPostCut; -class TaskPostCut: public TaskPostBox +class TaskPostCut: public TaskPostWidget { Q_OBJECT @@ -499,7 +495,6 @@ private: void collectImplicitFunctions(); // App::PropertyLink* m_functionProperty; - QWidget* proxy; std::unique_ptr ui; FunctionWidget* fwidget; }; @@ -509,7 +504,7 @@ private: // scalar clip filter class ViewProviderFemPostScalarClip; -class TaskPostScalarClip: public TaskPostBox +class TaskPostScalarClip: public TaskPostWidget { Q_OBJECT @@ -527,7 +522,6 @@ private: void onInsideOutToggled(bool val); private: - QWidget* proxy; std::unique_ptr ui; }; @@ -536,7 +530,7 @@ private: // warp vector filter class ViewProviderFemPostWarpVector; -class TaskPostWarpVector: public TaskPostBox +class TaskPostWarpVector: public TaskPostWidget { Q_OBJECT @@ -555,7 +549,6 @@ private: void onVectorCurrentIndexChanged(int idx); private: - QWidget* proxy; std::unique_ptr ui; }; @@ -564,7 +557,7 @@ private: // calculator filter class ViewProviderFemPostCalculator; -class TaskPostCalculator: public TaskPostBox +class TaskPostCalculator: public TaskPostWidget { Q_OBJECT diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp index 44a26aaa7e..5b4e98d286 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp @@ -70,7 +70,7 @@ void ViewProviderFemConstraintBearing::updateData(const App::Property* prop) Fem::ConstraintBearing* pcConstraint = this->getObject(); if (prop == &pcConstraint->References) { - Base::Console().Error("\n"); // enable a breakpoint here + Base::Console().error("\n"); // enable a breakpoint here } if (prop == &pcConstraint->BasePoint) { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp index 326853ca15..e088fd7a01 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp @@ -94,7 +94,7 @@ void ViewProviderFemConstraintGear::updateData(const App::Property* prop) SbVec3f b(base.x, base.y, base.z); SbVec3f ax(axis.x, axis.y, axis.z); SbVec3f dir(direction.x, direction.y, direction.z); - // Base::Console().Error("DirectionVector: %f, %f, %f\n", direction.x, direction.y, + // Base::Console().error("DirectionVector: %f, %f, %f\n", direction.x, direction.y, // direction.z); GuiTools::createPlacement(pShapeSep, b, SbRotation(SbVec3f(0, 1, 0), ax)); @@ -148,14 +148,14 @@ void ViewProviderFemConstraintGear::updateData(const App::Property* prop) SbVec3f ax(axis.x, axis.y, axis.z); SbVec3f dir(direction.x, direction.y, direction.z); - /*Base::Console().Error("Axis: %f, %f, %f\n", axis.x, axis.y, axis.z); - Base::Console().Error("Direction: %f, %f, %f\n", direction.x, direction.y, direction.z); + /*Base::Console().error("Axis: %f, %f, %f\n", axis.x, axis.y, axis.z); + Base::Console().error("Direction: %f, %f, %f\n", direction.x, direction.y, direction.z); SbRotation rot = SbRotation(ax, dir); SbMatrix m; rot.getValue(m); SbMat m2; m.getValue(m2); - Base::Console().Error("Matrix: %f, %f, %f, %f\n", m[0][0], m[1][0], m[2][0], m[3][0]); + Base::Console().error("Matrix: %f, %f, %f, %f\n", m[0][0], m[1][0], m[2][0], m[3][0]); // Note: In spite of the fact that the rotation matrix takes on 3 different values if 3 // normal directions are chosen, the resulting arrow will only point in two different // directions when ax = (1,0,0) (but for ax=(0,1,0) it points in 3 different diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp index 23f9c793c1..47028d56cd 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp @@ -953,7 +953,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, return; } Base::TimeElapsed Start; - Base::Console().Log( + Base::Console().log( "Start: ViewProviderFEMMeshBuilder::createMesh() =================================\n"); const SMDS_MeshInfo& info = data->GetMeshInfo(); @@ -989,7 +989,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, std::vector facesHelper(numTries); - Base::Console().Log(" %f: Start build up %i face helper\n", + Base::Console().log(" %f: Start build up %i face helper\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()), facesHelper.size()); Base::BoundBox3d BndBox; @@ -1514,7 +1514,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, if (FaceSize < MaxFacesShowInner) { - Base::Console().Log(" %f: Start eliminate internal faces SIMPLE\n", + Base::Console().log(" %f: Start eliminate internal faces SIMPLE\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // search for double (inside) faces and hide them @@ -1531,7 +1531,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } else { - Base::Console().Log(" %f: Start eliminate internal faces GRID\n", + Base::Console().log(" %f: Start eliminate internal faces GRID\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); BndBox.Enlarge(BndBox.CalcDiagonalLength() / 10000.0); // calculate grid properties @@ -1543,7 +1543,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, unsigned int NbrX = (unsigned int)(BndBox.LengthX() / size) + 1; unsigned int NbrY = (unsigned int)(BndBox.LengthY() / size) + 1; unsigned int NbrZ = (unsigned int)(BndBox.LengthZ() / size) + 1; - Base::Console().Log(" Size:F:%f, X:%i ,Y:%i ,Z:%i\n", gridFactor, NbrX, NbrY, NbrZ); + Base::Console().log(" Size:F:%f, X:%i ,Y:%i ,Z:%i\n", gridFactor, NbrX, NbrY, NbrZ); double Xmin = BndBox.MinX; double Ymin = BndBox.MinY; @@ -1570,7 +1570,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, iZ = z; if (iX >= NbrX || iY >= NbrY || iZ >= NbrZ) { - Base::Console().Log(" Outof range!\n"); + Base::Console().log(" Outof range!\n"); } Grid[iX + iY * NbrX + iZ * NbrX * NbrY].push_back(&facesHelper[l]); @@ -1594,12 +1594,12 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } avg = avg / Grid.size(); - Base::Console().Log(" VoxelSize: Max:%i ,Average:%i\n", max, avg); + Base::Console().log(" VoxelSize: Max:%i ,Average:%i\n", max, avg); } // if( FaceSize < 1000) - Base::Console().Log(" %f: Start build up node map\n", + Base::Console().log(" %f: Start build up node map\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // sort out double nodes and build up index map @@ -1632,7 +1632,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } } - Base::Console().Log(" %f: Start set point vector\n", + Base::Console().log(" %f: Start set point vector\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // set the point coordinates @@ -1650,7 +1650,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // count triangle size - Base::Console().Log(" %f: Start count triangle size\n", + Base::Console().log(" %f: Start count triangle size\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); int triangleCount = 0; for (int l = 0; l < FaceSize; l++) { @@ -1675,7 +1675,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } } - Base::Console().Log(" NumTriangles:%i\n", triangleCount); + Base::Console().log(" NumTriangles:%i\n", triangleCount); // edge map collect and sort edges of the faces to be shown. std::map> EdgeMap; @@ -1706,7 +1706,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } - Base::Console().Log(" %f: Start build up triangle vector\n", + Base::Console().log(" %f: Start build up triangle vector\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // set the triangle face indices faces->coordIndex.setNum(4 * triangleCount); @@ -3126,7 +3126,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, faces->coordIndex.finishEditing(); - Base::Console().Log(" %f: Start build up edge vector\n", + Base::Console().log(" %f: Start build up edge vector\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); // std::map > EdgeMap; // count edges @@ -3152,9 +3152,9 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } lines->coordIndex.finishEditing(); - Base::Console().Log(" NumEdges:%i\n", EdgeSize); + Base::Console().log(" NumEdges:%i\n", EdgeSize); - Base::Console().Log( + Base::Console().log( " %f: Finish =========================================================\n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp index 5faa50b58d..f3871c5873 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp @@ -25,6 +25,7 @@ #include "TaskPostBoxes.h" #include "ViewProviderFemPostBranchFilter.h" #include +#include using namespace FemGui; @@ -46,7 +47,8 @@ ViewProviderFemPostBranchFilter::~ViewProviderFemPostBranchFilter() void ViewProviderFemPostBranchFilter::setupTaskDialog(TaskDlgPost* dlg) { // add the branch ui - dlg->appendBox(new TaskPostBranch(this)); + auto panel = new TaskPostBranch(this); + dlg->addTaskBox(panel->windowIcon().pixmap(32), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp index fe0ad21fcf..4cbacb5cad 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp @@ -30,10 +30,43 @@ #include "TaskPostBoxes.h" #include "ViewProviderFemPostFilter.h" +#include "ViewProviderFemPostFilterPy.h" using namespace FemGui; +PROPERTY_SOURCE(FemGui::ViewProviderFemPostFilterPythonBase, FemGui::ViewProviderFemPostObject) + +ViewProviderFemPostFilterPythonBase::ViewProviderFemPostFilterPythonBase() +{} + +ViewProviderFemPostFilterPythonBase::~ViewProviderFemPostFilterPythonBase() = default; + +std::vector ViewProviderFemPostFilterPythonBase::getDisplayModes() const +{ + return std::vector(); +} + +namespace Gui +{ +PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderPostFilterPython, + FemGui::ViewProviderFemPostFilterPythonBase) + +template<> +PyObject* FemGui::ViewProviderPostFilterPython::getPyObject() +{ + if (!pyViewObject) { + pyViewObject = new ViewProviderFemPostFilterPy(this); + } + pyViewObject->IncRef(); + return pyViewObject; +} + +// explicit template instantiation +template class FemGuiExport ViewProviderFeaturePythonT; + +} // namespace Gui + // *************************************************************************** // in the following, the different filters sorted alphabetically // *************************************************************************** @@ -54,7 +87,8 @@ void ViewProviderFemPostDataAlongLine::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox(new TaskPostDataAlongLine(this)); + auto panel = new TaskPostDataAlongLine(this); + dlg->addTaskBox(panel->getIcon(), panel); } @@ -102,7 +136,8 @@ void ViewProviderFemPostDataAtPoint::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox(new TaskPostDataAtPoint(this)); + auto panel = new TaskPostDataAtPoint(this); + dlg->addTaskBox(panel->getIcon(), panel); } @@ -123,8 +158,9 @@ void ViewProviderFemPostClip::setupTaskDialog(TaskDlgPost* dlg) // add the function box assert(dlg->getView() == this); - dlg->appendBox( - new TaskPostClip(this, &dlg->getView()->getObject()->Function)); + auto panel = + new TaskPostClip(this, &dlg->getView()->getObject()->Function); + dlg->addTaskBox(panel->getIcon(), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); @@ -146,7 +182,8 @@ void ViewProviderFemPostContours::setupTaskDialog(TaskDlgPost* dlg) { // the filter-specific task panel assert(dlg->getView() == this); - dlg->appendBox(new TaskPostContours(this)); + auto panel = new TaskPostContours(this); + dlg->addTaskBox(panel->getIcon(), panel); } @@ -165,8 +202,9 @@ void ViewProviderFemPostCut::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox( - new TaskPostCut(this, &dlg->getView()->getObject()->Function)); + auto panel = + new TaskPostCut(this, &dlg->getView()->getObject()->Function); + dlg->addTaskBox(panel->getIcon(), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); @@ -188,7 +226,8 @@ void ViewProviderFemPostScalarClip::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox(new TaskPostScalarClip(this)); + auto panel = new TaskPostScalarClip(this); + dlg->addTaskBox(panel->getIcon(), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); @@ -210,7 +249,8 @@ void ViewProviderFemPostWarpVector::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox(new TaskPostWarpVector(this)); + auto panel = new TaskPostWarpVector(this); + dlg->addTaskBox(panel->getIcon(), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); @@ -245,7 +285,8 @@ void ViewProviderFemPostCalculator::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - dlg->appendBox(new TaskPostCalculator(this)); + auto panel = new TaskPostCalculator(this); + dlg->addTaskBox(panel->getIcon(), panel); // add the display options FemGui::ViewProviderFemPostObject::setupTaskDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h index e728e5fcd0..82b7f16bf8 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h @@ -23,12 +23,37 @@ #ifndef FEM_VIEWPROVIDERFEMPOSTFILTER_H #define FEM_VIEWPROVIDERFEMPOSTFILTER_H +#include #include "ViewProviderFemPostObject.h" - namespace FemGui { +// *************************************************************************** +// Special classes to enable python filter view providers +// *************************************************************************** + +// Special class for the python view providers, which need some special behaviour +class FemGuiExport ViewProviderFemPostFilterPythonBase: public ViewProviderFemPostObject +{ + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostFilterPythonBase); + +public: + /// constructor. + ViewProviderFemPostFilterPythonBase(); + ~ViewProviderFemPostFilterPythonBase() override; + + // we do not use default display modes but let the python implementation choose + // Python view provider needs to return a sublist of PostObject supporter DisplayModes + std::vector getDisplayModes() const override; +}; + + +// Viewprovider for the python filters +using ViewProviderPostFilterPython = + Gui::ViewProviderFeaturePythonT; + + // *************************************************************************** // in the following, the different filters sorted alphabetically // *************************************************************************** diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilterPy.xml b/src/Mod/Fem/Gui/ViewProviderFemPostFilterPy.xml new file mode 100644 index 0000000000..c41959e24d --- /dev/null +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilterPy.xml @@ -0,0 +1,24 @@ + + + + + + ViewProviderFemPostPipeline class + + + + Returns the display option task panel for a post processing edit task dialog. + + + + diff --git a/src/Base/UnitsSchemaMmMin.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFilterPyImp.cpp similarity index 53% rename from src/Base/UnitsSchemaMmMin.cpp rename to src/Mod/Fem/Gui/ViewProviderFemPostFilterPyImp.cpp index ab7752a0c4..c922d76840 100644 --- a/src/Base/UnitsSchemaMmMin.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilterPyImp.cpp @@ -1,60 +1,71 @@ -/*************************************************************************** - * Copyright (c) 2009 Jürgen Riegel * - * * - * This file is part of the FreeCAD CAx development system. * - * * - * This library is free software; you can redistribute it and/or * - * modify it under the terms of the GNU Library General Public * - * License as published by the Free Software Foundation; either * - * version 2 of the License, or (at your option) any later version. * - * * - * This library 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 this library; see the file COPYING.LIB. If not, * - * write to the Free Software Foundation, Inc., 59 Temple Place, * - * Suite 330, Boston, MA 02111-1307, USA * - * * - ***************************************************************************/ - - -#include "PreCompiled.h" -#ifndef _PreComp_ -#include -#include -#endif - -#include "Quantity.h" -#include "Unit.h" -#include "UnitsSchemaMmMin.h" - -using namespace Base; - -std::string -UnitsSchemaMmMin::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) -{ - static std::array>, 3> unitSpecs {{ - {Unit::Length, {"mm", 1.0}}, - {Unit::Angle, {"\xC2\xB0", 1.0}}, - {Unit::Velocity, {"mm/min", 1.0 / 60.0}}, - }}; - - const auto unit = quant.getUnit(); - const auto spec = std::find_if(unitSpecs.begin(), unitSpecs.end(), [&](const auto& pair) { - return pair.first == unit; - }); - - if (spec != std::end(unitSpecs)) { - unitString = spec->second.first; - factor = spec->second.second; - } - else { - unitString = quant.getUnit().getString(); - factor = 1.0; - } - - return toLocale(quant, factor, unitString); -} +/*************************************************************************** + * Copyright (c) 2025 Stefan Tröger * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + +#include "PreCompiled.h" + +// clang-format off +#include +#include +#include "ViewProviderFemPostFilter.h" +#include "TaskPostBoxes.h" +// inclusion of the generated files (generated out of ViewProviderFemPostFilterPy.xml) +#include "ViewProviderFemPostFilterPy.h" +#include "ViewProviderFemPostFilterPy.cpp" +#include +// clang-format on + + +using namespace FemGui; + +// returns a string which represents the object e.g. when printed in python +std::string ViewProviderFemPostFilterPy::representation() const +{ + return {""}; +} + +PyObject* ViewProviderFemPostFilterPy::createDisplayTaskWidget(PyObject* args) +{ + // we take no arguments + if (!PyArg_ParseTuple(args, "")) { + return nullptr; + } + + auto panel = new TaskPostDisplay(getViewProviderFemPostObjectPtr()); + + Gui::PythonWrapper wrap; + if (wrap.loadCoreModule()) { + return Py::new_reference_to(wrap.fromQWidget(panel)); + } + + PyErr_SetString(PyExc_TypeError, "creating the panel failed"); + return nullptr; +} + +PyObject* ViewProviderFemPostFilterPy::getCustomAttributes(const char* /*attr*/) const +{ + return nullptr; +} + +int ViewProviderFemPostFilterPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) +{ + return 0; +} diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp index 200622da31..1c7132aa07 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp @@ -343,7 +343,8 @@ bool ViewProviderFemPostFunction::setEdit(int ModNum) } else { postDlg = new TaskDlgPost(this); - postDlg->appendBox(new TaskPostFunction(this)); + auto panel = new TaskPostFunction(this); + postDlg->addTaskBox(panel->windowIcon().pixmap(32), panel); Gui::Control().showDialog(postDlg); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp index 0eaeb5047b..0d44e6486e 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp @@ -53,7 +53,6 @@ #endif #include -#include #include #include #include @@ -187,7 +186,7 @@ ViewProviderFemPostObject::ViewProviderFemPostObject() LineWidth.setConstraints(&sizeRange); PointSize.setConstraints(&sizeRange); - sPixmap = "fem-femmesh-from-shape"; + sPixmap = "FEM_PostPipelineFromResult"; // create the subnodes which do the visualization work m_transpType = new SoTransparencyType(); @@ -287,13 +286,13 @@ ViewProviderFemPostObject::~ViewProviderFemPostObject() deleteColorBar(); } catch (Base::Exception& e) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderFemPostObject", "ViewProviderFemPostObject destructor threw an exception: %s\n", e.what()); } catch (...) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderFemPostObject", "ViewProviderFemPostObject destructor threw an unknown exception"); } @@ -408,7 +407,9 @@ void ViewProviderFemPostObject::updateVtk() } m_currentAlgorithm->Update(); - updateProperties(); + if (!isRestoring()) { + updateProperties(); + } update3D(); } @@ -673,7 +674,7 @@ void ViewProviderFemPostObject::setRangeOfColorBar(float min, float max) m_colorBar->setRange(min, max); } catch (const Base::ValueError& e) { - e.ReportException(); + e.reportException(); } } @@ -931,7 +932,9 @@ void ViewProviderFemPostObject::onChanged(const App::Property* prop) } if (prop == &Field && setupPipeline()) { - updateProperties(); + if (!isRestoring()) { + updateProperties(); + } WriteColorData(ResetColorBarRange); } else if (prop == &Component && setupPipeline()) { @@ -1016,7 +1019,8 @@ bool ViewProviderFemPostObject::setEdit(int ModNum) void ViewProviderFemPostObject::setupTaskDialog(TaskDlgPost* dlg) { assert(dlg->getView() == this); - dlg->appendBox(new TaskPostDisplay(this)); + auto panel = new TaskPostDisplay(this); + dlg->addTaskBox(panel->windowIcon().pixmap(32), panel); } void ViewProviderFemPostObject::unsetEdit(int ModNum) diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h index 0e2e74954e..948ad96f13 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h @@ -114,27 +114,14 @@ public: bool canDelete(App::DocumentObject* obj) const override; virtual void onSelectionChanged(const Gui::SelectionChanges& sel); - /** @name Selection handling - * This group of methods do the selection handling. - * Here you can define how the selection for your ViewProvider - * works. - */ - //@{ - // /// indicates if the ViewProvider use the new Selection model - // virtual bool useNewSelectionModel(void) const {return true;} - // /// return a hit element to the selection path or 0 - // virtual std::string getElement(const SoDetail*) const; - // virtual SoDetail* getDetail(const char*) const; - // /// return the highlight lines for a given element or the whole shape - // virtual std::vector getSelectionShape(const char* Element) const; - // //@} + // setting up task dialogs + virtual void setupTaskDialog(TaskDlgPost* dlg); protected: void handleChangedPropertyName(Base::XMLReader& reader, const char* typeName, const char* propName) override; - virtual void setupTaskDialog(TaskDlgPost* dlg); bool setupPipeline(); void updateVtk(); void setRangeOfColorBar(float min, float max); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp index 6e83a9f24d..a78af62cd7 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp @@ -221,7 +221,8 @@ void ViewProviderFemPostPipeline::setupTaskDialog(TaskDlgPost* dlg) // add the function box assert(dlg->getView() == this); ViewProviderFemPostObject::setupTaskDialog(dlg); - dlg->appendBox(new TaskPostFrames(this)); + auto panel = new TaskPostFrames(this); + dlg->addTaskBox(panel->windowIcon().pixmap(32), panel); } diff --git a/src/Mod/Fem/Gui/Workbench.cpp b/src/Mod/Fem/Gui/Workbench.cpp index 66d46af435..3ae3219705 100644 --- a/src/Mod/Fem/Gui/Workbench.cpp +++ b/src/Mod/Fem/Gui/Workbench.cpp @@ -206,6 +206,9 @@ Gui::ToolBarItem* Workbench::setupToolBars() const << "FEM_PostFilterCutFunction" << "FEM_PostFilterClipRegion" << "FEM_PostFilterContours" +#ifdef FC_USE_VTK_PYTHON + << "FEM_PostFilterGlyph" +#endif << "FEM_PostFilterDataAlongLine" << "FEM_PostFilterLinearizedStresses" << "FEM_PostFilterDataAtPoint" @@ -355,6 +358,9 @@ Gui::MenuItem* Workbench::setupMenuBar() const << "FEM_PostFilterCutFunction" << "FEM_PostFilterClipRegion" << "FEM_PostFilterContours" +#ifdef FC_USE_VTK_PYTHON + << "FEM_PostFilterGlyph" +#endif << "FEM_PostFilterDataAlongLine" << "FEM_PostFilterLinearizedStresses" << "FEM_PostFilterDataAtPoint" diff --git a/src/Mod/Fem/InitGui.py b/src/Mod/Fem/InitGui.py index 621a278f17..8ac271d379 100644 --- a/src/Mod/Fem/InitGui.py +++ b/src/Mod/Fem/InitGui.py @@ -80,6 +80,11 @@ class FemWorkbench(Workbench): False if FemGui.__name__ else True False if femcommands.commands.__name__ else True + # check vtk version to potentially find missmatchs + from femguiutils.vtk_module_handling import vtk_module_handling + + vtk_module_handling() + def GetClassName(self): # see https://forum.freecad.org/viewtopic.php?f=10&t=43300 return "FemGui::Workbench" diff --git a/src/Mod/Fem/ObjectsFem.py b/src/Mod/Fem/ObjectsFem.py index 72c407b3bc..c05ecc6108 100644 --- a/src/Mod/Fem/ObjectsFem.py +++ b/src/Mod/Fem/ObjectsFem.py @@ -653,6 +653,22 @@ def makePostVtkFilterContours(doc, base_vtk_result, name="VtkFilterContours"): return obj +def makePostFilterGlyph(doc, base_vtk_result, name="Glyph"): + """makePostVtkFilterGlyph(document, [name]): + creates a FEM post processing filter that visualizes vector fields with glyphs + """ + obj = doc.addObject("Fem::PostFilterPython", name) + from femobjects import post_glyphfilter + + post_glyphfilter.PostGlyphFilter(obj) + base_vtk_result.addObject(obj) + if FreeCAD.GuiUp: + from femviewprovider import view_post_glyphfilter + + view_post_glyphfilter.VPPostGlyphFilter(obj.ViewObject) + return obj + + def makePostVtkResult(doc, result_data, name="VtkResult"): """makePostVtkResult(document, base_result, [name]): creates a FEM post processing result data (vtk based) to hold FEM results diff --git a/src/Mod/Fem/femcommands/commands.py b/src/Mod/Fem/femcommands/commands.py index 2025fbaabd..0c61dcff2b 100644 --- a/src/Mod/Fem/femcommands/commands.py +++ b/src/Mod/Fem/femcommands/commands.py @@ -1217,6 +1217,21 @@ class _SolverZ88(CommandManager): self.do_activated = "add_obj_on_gui_expand_noset_edit" +class _PostFilterGlyph(CommandManager): + "The FEM_PostFilterGlyph command definition" + + def __init__(self): + super().__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP("FEM_PostFilterGlyph", "Glyph filter") + self.accel = "F, G" + self.tooltip = Qt.QT_TRANSLATE_NOOP( + "FEM_PostFilterGlyph", + "Post processing filter that adds glyphs to the mesh vertices for vertex data visualization", + ) + self.is_active = "with_vtk_selresult" + self.do_activated = "add_filter_set_edit" + + # the string in add command will be the page name on FreeCAD wiki FreeCADGui.addCommand("FEM_Analysis", _Analysis()) FreeCADGui.addCommand("FEM_ClippingPlaneAdd", _ClippingPlaneAdd()) @@ -1271,3 +1286,6 @@ FreeCADGui.addCommand("FEM_SolverElmer", _SolverElmer()) FreeCADGui.addCommand("FEM_SolverMystran", _SolverMystran()) FreeCADGui.addCommand("FEM_SolverRun", _SolverRun()) FreeCADGui.addCommand("FEM_SolverZ88", _SolverZ88()) + +if "BUILD_FEM_VTK_PYTHON" in FreeCAD.__cmake__: + FreeCADGui.addCommand("FEM_PostFilterGlyph", _PostFilterGlyph()) diff --git a/src/Mod/Fem/femcommands/manager.py b/src/Mod/Fem/femcommands/manager.py index 16529a94eb..44c5d2dc0a 100644 --- a/src/Mod/Fem/femcommands/manager.py +++ b/src/Mod/Fem/femcommands/manager.py @@ -34,6 +34,7 @@ import FreeCAD from femtools.femutils import expandParentObject from femtools.femutils import is_of_type +from femguiutils.vtk_module_handling import vtk_compatibility_abort if FreeCAD.GuiUp: from PySide import QtCore @@ -89,6 +90,8 @@ class CommandManager: FreeCADGui.ActiveDocument is not None and self.result_selected() ) + elif self.is_active == "with_vtk_selresult": + active = self.vtk_result_selected() elif self.is_active == "with_part_feature": active = FreeCADGui.ActiveDocument is not None and self.part_feature_selected() elif self.is_active == "with_femmesh": @@ -144,6 +147,8 @@ class CommandManager: self.add_obj_on_gui_selobj_set_edit(self.__class__.__name__.lstrip("_")) elif self.do_activated == "add_obj_on_gui_selobj_expand_noset_edit": self.add_obj_on_gui_selobj_expand_noset_edit(self.__class__.__name__.lstrip("_")) + elif self.do_activated == "add_filter_set_edit": + self.add_filter_set_edit(self.__class__.__name__.lstrip("_")) # in all other cases Activated is implemented it the command class def results_present(self): @@ -169,6 +174,13 @@ class CommandManager: return True return False + def vtk_result_selected(self): + sel = FreeCADGui.Selection.getSelection() + if len(sel) == 1 and sel[0].isDerivedFrom("Fem::FemPostObject"): + self.selobj = sel[0] + return True + return False + def part_feature_selected(self): sel = FreeCADGui.Selection.getSelection() if len(sel) == 1 and sel[0].isDerivedFrom("Part::Feature"): @@ -363,3 +375,48 @@ class CommandManager: ) # expand selobj in tree view expandParentObject() + + def add_filter_set_edit(self, filtertype): + # like add_obj_on_gui_selobj_noset_edit but the selection is kept + # and the selobj is expanded in the tree to see the added obj + + # check if we should use python fitler + if vtk_compatibility_abort(True): + return + + # Note: we know selobj is a FemPostObject as otherwise the command should not have been active + # We also assume the all filters are in PostGroups and not astray + group = None + if self.selobj.hasExtension("Fem::FemPostGroupExtension"): + group = self.selobj + else: + group = self.selobj.getParentPostGroup() + + FreeCAD.ActiveDocument.openTransaction(f"Create Fem{filtertype}") + FreeCADGui.addModule("ObjectsFem") + FreeCADGui.doCommand( + "ObjectsFem.make{}(" + "FreeCAD.ActiveDocument, FreeCAD.ActiveDocument.{})".format(filtertype, group.Name) + ) + # set display and selection style to assure the user sees the new object + FreeCADGui.doCommand( + 'FreeCAD.ActiveDocument.ActiveObject.ViewObject.DisplayMode = "Surface"' + ) + FreeCADGui.doCommand( + 'FreeCAD.ActiveDocument.ActiveObject.ViewObject.SelectionStyle = "BoundBox"' + ) + + # hide selected filter + FreeCADGui.doCommand( + "FreeCAD.ActiveDocument.{}.ViewObject.Visibility = False".format(self.selobj.Name) + ) + + # recompute, expand selobj in tree view + expandParentObject() + FreeCADGui.doCommand("FreeCAD.ActiveDocument.ActiveObject.recompute()") + + # set edit + FreeCADGui.Selection.clearSelection() + FreeCADGui.doCommand( + "FreeCADGui.ActiveDocument.setEdit(FreeCAD.ActiveDocument.ActiveObject.Name)" + ) diff --git a/src/Mod/Fem/femguiutils/vtk_module_handling.py b/src/Mod/Fem/femguiutils/vtk_module_handling.py new file mode 100644 index 0000000000..dd5934af7e --- /dev/null +++ b/src/Mod/Fem/femguiutils/vtk_module_handling.py @@ -0,0 +1,258 @@ +# *************************************************************************** +# * Copyright (c) 2025 Stefan Tröger * +# * * +# * 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 Lesser 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. * +# * * +# * This program 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 this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +"""Methods to verify if the python VTK module is the correct one + +FreeCAD is linked with VTK libraries during its build process. To use the VTK +python module and pass objects between python and c++ the compiled module library +needs to be linked to the exact same vtk library as FreeCAD is. This is ensured by +installing VTK via linux app managers: All known distros install the python side +packages together with vtk libs. Libpack and other OS systems ensure this too. + +However, if a vtk python package is installed manually, e.g. by "pip install vtk", +it could be found instead of the system module. This python API brings its own +set of VTK libs, and hence object passing in FreeCAD fails. (Note: import and +pure vtk python code still works, only passing to c++ fails) + +This file provides functions that detect this situation and inform the user. +Additionally we try to find the correct module in the path and offer to use +it instead. + +Note that this problem occurs with all "compiled binary" python APIs, also +with PySide. It is the users responsibility to handle his python path and keep +it clean/working. The functions provided here are a workaround only. +""" + +__title__ = "FEM GUI vtk python module check" +__author__ = "Stefan Tröger" +__url__ = "https://www.freecad.org" + +__user_input_received = False + + +def vtk_module_compatible(): + # checks if the VTK library FreeCAD is build against is the one used by + # the python module + + # make sure we do not contaminate the modules with vtk to not trick + # the check later + unload = not _vtk_is_loaded() + + import Fem + from vtkmodules.vtkCommonCore import vtkVersion, vtkBitArray + + # simple version check + if Fem.getVtkVersion() != vtkVersion.GetVTKVersion(): + return False + + # check binary compatibility + result = Fem.isVtkCompatible(vtkBitArray()) + + if unload: + # cleanup our own import + _unload_vtk_modules() + + return result + + +def _vtk_is_loaded(): + import sys + + return any("vtkmodules" in module for module in sys.modules) + + +def _unload_vtk_modules(): + # unloads all loaded vtk modules + # NOTE: does not remove any stored references in objects + + import sys + + for module in sys.modules.copy(): + if "vtkmodules" in module: + del sys.modules[module] + + +def _find_compatible_module(): + # Check all python path folders if they contain a vtk module + + import Fem + import sys + + # remove module from runtime + _unload_vtk_modules() + + path = sys.path.copy() + + for folder in reversed(path): + try: + # use a single folder as path and try to load vtk + sys.path = [folder] + if vtk_module_compatible(): + # we do still unload, to let the user descide if he wants to use it + _unload_vtk_modules() + sys.path = path + return folder + + except: + continue + + # reset the correct path and indicate that we failed + sys.path = path + return None + + +def _load_vtk_from(folder): + + import sys + + path = sys.path + try: + sys.path = [folder] + import vtkmodules + finally: + sys.path = path + + +# If FreeCAD is build with VTK python support this function checks if the +# used python module is compatible with the c++ lib. Does inform the user +# if not so and offers the correct module, if available +# +# Note: Call this also from Python feature module, as on document load +# this can be loaded before initializing FEM workbench. +def vtk_module_handling(): + + import sys + import FreeCAD + + if not "BUILD_FEM_VTK_PYTHON" in FreeCAD.__cmake__: + # no VTK python api support in FreeCAD + return + + # only ask user once per session + global __user_input_received + if __user_input_received: + return + __user_input_received = True + + loaded = _vtk_is_loaded() + + # check if we are compatible + if not vtk_module_compatible(): + + if not FreeCAD.GuiUp: + FreeCAD.Console.PrintError( + "FEM: vtk python module is not compatible with internal vtk library" + ) + return + + import FreeCAD, Fem + from vtkmodules.vtkCommonCore import vtkVersion + import inspect + from PySide import QtGui + + translate = FreeCAD.Qt.translate + + path = inspect.getfile(vtkVersion) + path = path[: path.find("vtkmodules")] + + message = translate( + "FEM", + ( + "FreeCAD is linked to a different VTK library then the imported " + "VTK python module. This is incompatible and will lead to errors." + "\n\nWrong python module is imported from: \n{}" + ), + ).format(path) + + buttons = QtGui.QMessageBox.Discard + + # check if there is any compatible vtk module + compatible_module = _find_compatible_module() + + if compatible_module: + # there is a compatible module of VTK available. + message += translate("FEM", "\n\nCorrect module found in: \n{}").format( + compatible_module + ) + + if not loaded: + # vtk was not loaded beforehand, therefore we can realistically reload + message += translate("FEM", "\n\nShould this module be loaded instead?") + + buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No + + else: + message += translate( + "FEM", + ( + "\n\nAs the wrong module was already loaded, a reload is not possible. " + "Restart FreeCAD to get the option for loading this module." + ), + ) + + else: + message += translate( + "FEM", "\n\nNo matching module was found in the current python path." + ) + + # raise a dialog to the user + import FreeCADGui + + button = QtGui.QMessageBox.critical( + FreeCADGui.getMainWindow(), + translate("FEM", "VTK module conflict"), + message, + buttons=buttons, + ) + + if button == QtGui.QMessageBox.Yes: + # try to reload the correct vtk module + _load_vtk_from(compatible_module) + + +# Returns if vtk python is incompatible and hence operations need to be aborted. +# If inform=True the user gets informed by dialog about incompatibilities +def vtk_compatibility_abort(inform=True): + + if not vtk_module_compatible(): + + if inform: + # raise a dialog to the user that this functionality is not available + import FreeCAD + import FreeCADGui + from PySide import QtGui + + translate = FreeCAD.Qt.translate + + button = QtGui.QMessageBox.critical( + FreeCADGui.getMainWindow(), + translate("FEM", "VTK module conflict"), + translate( + "FEM", "This functionality is not available due to VTK python module conflict" + ), + buttons=QtGui.QMessageBox.Discard, + ) + + return True + + return False diff --git a/src/Mod/Fem/feminout/importCcxFrdResults.py b/src/Mod/Fem/feminout/importCcxFrdResults.py index 82859cd10d..32735e28ff 100644 --- a/src/Mod/Fem/feminout/importCcxFrdResults.py +++ b/src/Mod/Fem/feminout/importCcxFrdResults.py @@ -63,6 +63,9 @@ def setupPipeline(doc, analysis, results_name, result_data): import ObjectsFem from . import importToolsFem + if not "BUILD_FEM_VTK" in FreeCAD.__cmake__: + return + # create a results pipeline if not already existing pipeline_name = "Pipeline_" + results_name pipeline_obj = doc.getObject(pipeline_name) diff --git a/src/Mod/Fem/femobjects/post_glyphfilter.py b/src/Mod/Fem/femobjects/post_glyphfilter.py new file mode 100644 index 0000000000..936c47e233 --- /dev/null +++ b/src/Mod/Fem/femobjects/post_glyphfilter.py @@ -0,0 +1,271 @@ +# *************************************************************************** +# * Copyright (c) 2025 Stefan Tröger * +# * * +# * 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 Lesser 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. * +# * * +# * This program 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 this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +__title__ = "FreeCAD post glyph filter" +__author__ = "Stefan Tröger" +__url__ = "https://www.freecad.org" + +## @package post_glyphfilter +# \ingroup FEM +# \brief Post processing filter creating glyphs for vector fields + +import FreeCAD + +# check vtk version to potentially find missmatchs +from femguiutils.vtk_module_handling import vtk_module_handling + +vtk_module_handling() + +# IMPORTANT: Never import vtk directly. Often vtk is compiled with different QT +# version than FreeCAD, and "import vtk" crashes by importing qt components. +# Always import the filter and data modules only. +from vtkmodules.vtkFiltersCore import vtkMaskPoints +from vtkmodules.vtkFiltersCore import vtkGlyph3D +import vtkmodules.vtkFiltersSources as vtkSources + +from . import base_fempythonobject + +_PropHelper = base_fempythonobject._PropHelper + + +class PostGlyphFilter(base_fempythonobject.BaseFemPythonObject): + """ + A post processing filter adding glyphs + """ + + Type = "Fem::PostFilterPython" + + def __init__(self, obj): + super().__init__(obj) + + for prop in self._get_properties(): + prop.add_to_object(obj) + + self.__setupFilterPipeline(obj) + + def _get_properties(self): + + prop = [ + _PropHelper( + type="App::PropertyEnumeration", + name="Glyph", + group="Glyph", + doc="The form of the glyph", + value=["Arrow", "Cube"], + ), + _PropHelper( + type="App::PropertyEnumeration", + name="OrientationData", + group="Glyph", + doc="Which vector field is used to orient the glyphs", + value=["None"], + ), + _PropHelper( + type="App::PropertyEnumeration", + name="ScaleData", + group="Scale", + doc="Which data field is used to scale the glyphs", + value=["None"], + ), + _PropHelper( + type="App::PropertyEnumeration", + name="VectorScaleMode", + group="Scale", + doc="If the scale data is a vector this property decides if the glyph is scaled by vector magnitude or by the individual components", + value=["Not a vector"], + ), + _PropHelper( + type="App::PropertyFloatConstraint", + name="ScaleFactor", + group="Scale", + doc="A constant multiplier the glyphs are scaled with", + value=(1, 0, 1e12, 1e-12), + ), + _PropHelper( + type="App::PropertyEnumeration", + name="MaskMode", + group="Masking", + doc="Which vertices are used as glyph locations", + value=["Use All", "Every Nth", "Uniform Samping"], + ), + _PropHelper( + type="App::PropertyIntegerConstraint", + name="Stride", + group="Masking", + doc='Define the stride for "Every Nth" masking mode', + value=(2, 1, 999999999, 1), + ), + _PropHelper( + type="App::PropertyIntegerConstraint", + name="MaxNumber", + group="Masking", + doc='Defines the maximal number of vertices used for "Uniform Sampling" masking mode', + value=(1000, 1, 999999999, 1), + ), + ] + return prop + + def __setupMaskingFilter(self, obj, masking): + + if obj.MaskMode == "Use All": + masking.RandomModeOff() + masking.SetOnRatio(1) + masking.SetMaximumNumberOfPoints(int(1e10)) + elif obj.MaskMode == "Every Nth": + masking.RandomModeOff() + masking.SetOnRatio(obj.Stride) + masking.SetMaximumNumberOfPoints(int(1e10)) + else: + masking.SetOnRatio(1) + masking.SetMaximumNumberOfPoints(obj.MaxNumber) + masking.RandomModeOn() + + def __setupGlyphFilter(self, obj, glyph): + + # scaling + if obj.ScaleData != "None": + + glyph.ScalingOn() + if obj.ScaleData in obj.getInputVectorFields(): + + # make sure the vector mode is set correctly + if obj.VectorScaleMode == "Not a vector": + obj.VectorScaleMode = ["Scale by magnitude", "Scale by components"] + obj.VectorScaleMode = "Scale by magnitude" + + if obj.VectorScaleMode == "Scale by magnitude": + glyph.SetScaleModeToScaleByVector() + else: + glyph.SetScaleModeToScaleByVectorComponents() + + glyph.SetInputArrayToProcess(2, 0, 0, 0, obj.ScaleData) + + else: + # scalar scaling mode + if obj.VectorScaleMode != "Not a vector": + obj.VectorScaleMode = ["Not a vector"] + + glyph.SetInputArrayToProcess(2, 0, 0, 0, obj.ScaleData) + glyph.SetScaleModeToScaleByScalar() + else: + glyph.ScalingOff() + + glyph.SetScaleFactor(obj.ScaleFactor) + + # Orientation + if obj.OrientationData != "None": + glyph.OrientOn() + glyph.SetInputArrayToProcess(1, 0, 0, 0, obj.OrientationData) + else: + glyph.OrientOff() + + def __setupFilterPipeline(self, obj): + + # store of all algorithms for later access + # its map filter_name : [source, mask, glyph] + self._algorithms = {} + + # create all vtkalgorithm combinations and set them as filter pipeline + sources = {"Arrow": vtkSources.vtkArrowSource, "Cube": vtkSources.vtkCubeSource} + + for source_name in sources: + + source = sources[source_name]() + + masking = vtkMaskPoints() + self.__setupMaskingFilter(obj, masking) + + glyph = vtkGlyph3D() + glyph.SetSourceConnection(source.GetOutputPort(0)) + glyph.SetInputConnection(masking.GetOutputPort(0)) + self.__setupGlyphFilter(obj, glyph) + + self._algorithms[source_name] = [source, masking, glyph] + obj.addFilterPipeline(source_name, masking, glyph) + + obj.setActiveFilterPipeline(obj.Glyph) + + def onDocumentRestored(self, obj): + # resetup the pipeline + self.__setupFilterPipeline(obj) + + def execute(self, obj): + # we check what new inputs + + vector_fields = obj.getInputVectorFields() + all_fields = vector_fields + obj.getInputScalarFields() + + vector_fields.sort() + all_fields.sort() + + current_orient = obj.OrientationData + enumeration = ["None"] + vector_fields + obj.OrientationData = enumeration + if current_orient in enumeration: + obj.OrientationData = current_orient + + current_scale = obj.ScaleData + enumeration = ["None"] + all_fields + obj.ScaleData = enumeration + if current_scale in enumeration: + obj.ScaleData = current_scale + + # make sure parent class execute is called! + return False + + def onChanged(self, obj, prop): + + # check if we are setup already + if not hasattr(self, "_algorithms"): + return + + if prop == "Glyph": + obj.setActiveFilterPipeline(obj.Glyph) + + if prop == "MaskMode": + for filter in self._algorithms: + masking = self._algorithms[filter][1] + self.__setupMaskingFilter(obj, masking) + + if prop == "Stride": + # if mode is use all stride setting needs to stay at one + if obj.MaskMode == "Every Nth": + for filter in self._algorithms: + masking = self._algorithms[filter][1] + masking.SetOnRatio(obj.Stride) + + if prop == "MaxNumber": + if obj.MaskMode == "Uniform Sampling": + for filter in self._algorithms: + masking = self._algorithms[filter][1] + masking.SetMaximumNumberOfPoints(obj.MaxNumber) + + if prop == "OrientationData" or prop == "ScaleData": + for filter in self._algorithms: + glyph = self._algorithms[filter][2] + self.__setupGlyphFilter(obj, glyph) + + if prop == "ScaleFactor": + for filter in self._algorithms: + glyph = self._algorithms[filter][2] + glyph.SetScaleFactor(obj.ScaleFactor) diff --git a/src/Mod/Fem/femtaskpanels/task_post_glyphfilter.py b/src/Mod/Fem/femtaskpanels/task_post_glyphfilter.py new file mode 100644 index 0000000000..a0658812e6 --- /dev/null +++ b/src/Mod/Fem/femtaskpanels/task_post_glyphfilter.py @@ -0,0 +1,209 @@ +# *************************************************************************** +# * Copyright (c) 2025 Stefan Tröger * +# * * +# * 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 Lesser 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. * +# * * +# * This program 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 this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +__title__ = "FreeCAD FEM glyph filter task panel for the document object" +__author__ = "Stefan Tröger" +__url__ = "https://www.freecad.org" + +## @package task_post_glyphfilter +# \ingroup FEM +# \brief task panel for post glyph filter object + +from PySide import QtCore, QtGui + +import FreeCAD +import FreeCADGui + +from femguiutils import selection_widgets +from . import base_femtaskpanel + + +class _TaskPanel(base_femtaskpanel._BaseTaskPanel): + """ + The TaskPanel for editing properties of glyph filter + """ + + def __init__(self, vobj): + super().__init__(vobj.Object) + + # glyph parameter widget + self.widget = FreeCADGui.PySideUic.loadUi( + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/TaskPostGlyph.ui" + ) + self.widget.setWindowIcon(FreeCADGui.getIcon(":/icons/FEM_PostFilterGlyph.svg")) + self.__init_widget() + + # form made from param and selection widget + self.form = [self.widget, vobj.createDisplayTaskWidget()] + + # get the settings group + self.__settings_grp = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem") + + # Implement parent functions + # ########################## + + def getStandardButtons(self): + return ( + QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel + ) + + def clicked(self, button): + # apply button hit? + if button == QtGui.QDialogButtonBox.Apply: + self.obj.Document.recompute() + + def accept(self): + # self.obj.CharacteristicLength = self.elelen + # self.obj.References = self.selection_widget.references + # self.selection_widget.finish_selection() + return super().accept() + + def reject(self): + # self.selection_widget.finish_selection() + return super().reject() + + # Helper functions + # ################## + + def _recompute(self): + # only recompute if the user wants automatic recompute + if self.__settings_grp.GetBool("PostAutoRecompute", True): + self.obj.Document.recompute() + + def _enumPropertyToCombobox(self, obj, prop, cbox): + cbox.blockSignals(True) + cbox.clear() + entries = obj.getEnumerationsOfProperty(prop) + for entry in entries: + cbox.addItem(entry) + + cbox.setCurrentText(getattr(obj, prop)) + cbox.blockSignals(False) + + # Setup functions + # ############### + + def __init_widget(self): + + # set current values to ui + self._enumPropertyToCombobox(self.obj, "Glyph", self.widget.FormComboBox) + self._enumPropertyToCombobox(self.obj, "OrientationData", self.widget.OrientationComboBox) + self._enumPropertyToCombobox(self.obj, "ScaleData", self.widget.ScaleComboBox) + self._enumPropertyToCombobox(self.obj, "VectorScaleMode", self.widget.VectorModeComboBox) + self._enumPropertyToCombobox(self.obj, "MaskMode", self.widget.MaskModeComboBox) + + self.widget.ScaleFactorBox.setValue(self.obj.ScaleFactor) + self.__slide_min = self.obj.ScaleFactor * 0.5 + self.__slide_max = self.obj.ScaleFactor * 1.5 + self.widget.ScaleSlider.setValue(50) + self.widget.StrideBox.setValue(self.obj.Stride) + self.widget.MaxBox.setValue(self.obj.MaxNumber) + self.__update_scaling_ui() + self.__update_masking_ui() + + # connect all signals + self.widget.FormComboBox.currentTextChanged.connect(self._form_changed) + self.widget.OrientationComboBox.currentTextChanged.connect(self._orientation_changed) + self.widget.ScaleComboBox.currentTextChanged.connect(self._scale_data_changed) + self.widget.VectorModeComboBox.currentTextChanged.connect(self._scale_vector_mode_changed) + self.widget.ScaleFactorBox.valueChanged.connect(self._scale_factor_changed) + self.widget.ScaleSlider.valueChanged.connect(self._scale_slider_changed) + self.widget.MaskModeComboBox.currentTextChanged.connect(self._mask_mode_changed) + self.widget.StrideBox.valueChanged.connect(self._stride_changed) + self.widget.MaxBox.valueChanged.connect(self._max_number_changed) + + def __update_scaling_ui(self): + enabled = self.widget.ScaleComboBox.currentIndex() != 0 + self.widget.VectorModeComboBox.setEnabled(enabled) + self.widget.ScaleFactorBox.setEnabled(enabled) + self.widget.ScaleSlider.setEnabled(enabled) + + def __update_masking_ui(self): + enabled = self.widget.MaskModeComboBox.currentIndex() != 0 + self.widget.StrideBox.setEnabled(enabled) + self.widget.MaxBox.setEnabled(enabled) + + # callbacks and logic + # ################### + + def _form_changed(self, value): + self.obj.Glyph = value + self._recompute() + + def _orientation_changed(self, value): + self.obj.OrientationData = value + self._recompute() + + def _scale_data_changed(self, value): + self.obj.ScaleData = value + self._enumPropertyToCombobox(self.obj, "VectorScaleMode", self.widget.VectorModeComboBox) + self.__update_scaling_ui() + self._recompute() + + def _scale_vector_mode_changed(self, value): + self.obj.VectorScaleMode = value + self._recompute() + + def _scale_factor_changed(self, value): + + # set slider + self.__slide_min = value * 0.5 + self.__slide_max = value * 1.5 + slider_value = (value - self.__slide_min) / (self.__slide_max - self.__slide_min) * 100.0 + self.widget.ScaleSlider.blockSignals(True) + self.widget.ScaleSlider.setValue(slider_value) + self.widget.ScaleSlider.blockSignals(False) + + self.obj.ScaleFactor = value + self._recompute() + + def _scale_slider_changed(self, value): + + # calculate value + # ( max - min ) + # factor = min + ( slider_value x ------------- ) + # 100 + # + f = self.__slide_min + (value * (self.__slide_max - self.__slide_min) / 100) + + # sync factor spin box + self.widget.ScaleFactorBox.blockSignals(True) + self.widget.ScaleFactorBox.setValue(f) + self.widget.ScaleFactorBox.blockSignals(False) + + # set value + self.obj.ScaleFactor = f + self._recompute() + + def _mask_mode_changed(self, value): + self.obj.MaskMode = value + self.__update_masking_ui() + self._recompute() + + def _stride_changed(self, value): + self.obj.Stride = value + self._recompute() + + def _max_number_changed(self, value): + self.obj.MaxNumber = value + self._recompute() diff --git a/src/Mod/Fem/femtest/app/support_utils.py b/src/Mod/Fem/femtest/app/support_utils.py index 10ff3b3433..7046ce712c 100644 --- a/src/Mod/Fem/femtest/app/support_utils.py +++ b/src/Mod/Fem/femtest/app/support_utils.py @@ -87,7 +87,7 @@ def get_defmake_count(fem_vtk_post=True): # we are not able to create VTK post objects new_lines = [] for li in lines_defmake: - if "PostVtk" not in li: + if "Post" not in li: new_lines.append(li) lines_defmake = new_lines return len(lines_defmake) diff --git a/src/Mod/Fem/femtest/app/test_common.py b/src/Mod/Fem/femtest/app/test_common.py index d791149671..587b263b8c 100644 --- a/src/Mod/Fem/femtest/app/test_common.py +++ b/src/Mod/Fem/femtest/app/test_common.py @@ -122,8 +122,12 @@ class TestFemCommon(unittest.TestCase): fcc_print(f"Try importing {mod} ...") try: im = __import__(f"{mod}") - except ImportError: - im = False + except ImportError as e: + # check if it is a VTK module that is missing, because maybe we should not need it + if "vtkmodules" in e.name and not "BUILD_FEM_VTK_PYTHON" in FreeCAD.__cmake__: + im = True + else: + im = False if not im: # to get an error message what was going wrong __import__(f"{mod}") diff --git a/src/Mod/Fem/femtest/app/test_object.py b/src/Mod/Fem/femtest/app/test_object.py index cf9ed123ac..93d331ea94 100644 --- a/src/Mod/Fem/femtest/app/test_object.py +++ b/src/Mod/Fem/femtest/app/test_object.py @@ -68,10 +68,9 @@ class TestObjectCreate(unittest.TestCase): # count the def make in ObjectsFem module # if FEM VTK post processing is disabled, we are not able to create VTK post objects - if "BUILD_FEM_VTK" in FreeCAD.__cmake__: - count_defmake = testtools.get_defmake_count() - else: - count_defmake = testtools.get_defmake_count(False) + vtk_objects_used = "BUILD_FEM_VTK" in FreeCAD.__cmake__ + count_defmake = testtools.get_defmake_count(vtk_objects_used) + # TODO if the children are added to the analysis, they show up twice on Tree # thus they are not added to the analysis group ATM # https://forum.freecad.org/viewtopic.php?t=25283 @@ -79,12 +78,23 @@ class TestObjectCreate(unittest.TestCase): # solver children: equations --> 10 # gmsh mesh children: group, region, boundary layer --> 3 # result children: mesh result --> 1 - # post pipeline children: region, scalar, cut, wrap --> 5 # analysis itself is not in analysis group --> 1 - # thus: -20 + # vtk post pipeline children: region, scalar, cut, wrap, glyph --> 5 + # vtk python post objects: glyph --> 1 - self.assertEqual(len(doc.Analysis.Group), count_defmake - 20) - self.assertEqual(len(doc.Objects), count_defmake) + subtraction = 15 + if vtk_objects_used: + subtraction += 6 + + self.assertEqual(len(doc.Analysis.Group), count_defmake - subtraction) + + # if vtk used, but python API is not available, the vtk python based objects "def make" functions + # have been counted, but will not be executed to create objects + failed = 0 + if vtk_objects_used and not ("BUILD_FEM_VTK_PYTHON" in FreeCAD.__cmake__): + failed += 1 + + self.assertEqual(len(doc.Objects), count_defmake - failed) fcc_print( "doc objects count: {}, method: {}".format( @@ -1154,6 +1164,8 @@ def create_all_fem_objects_doc(doc): ObjectsFem.makePostVtkFilterCutFunction(doc, vres) ObjectsFem.makePostVtkFilterWarp(doc, vres) ObjectsFem.makePostVtkFilterContours(doc, vres) + if "BUILD_FEM_VTK_PYTHON" in FreeCAD.__cmake__: + ObjectsFem.makePostFilterGlyph(doc, vres) analysis.addObject(ObjectsFem.makeSolverCalculiXCcxTools(doc)) analysis.addObject(ObjectsFem.makeSolverCalculiX(doc)) diff --git a/src/Mod/Fem/femviewprovider/view_post_glyphfilter.py b/src/Mod/Fem/femviewprovider/view_post_glyphfilter.py new file mode 100644 index 0000000000..c35299f42a --- /dev/null +++ b/src/Mod/Fem/femviewprovider/view_post_glyphfilter.py @@ -0,0 +1,86 @@ +# *************************************************************************** +# * Copyright (c) 2025 Stefan Tröger * +# * * +# * 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 Lesser 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. * +# * * +# * This program 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 this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +__title__ = "FreeCAD FEM postprocessing glyph filter ViewProvider for the document object" +__author__ = "Stefan Tröger" +__url__ = "https://www.freecad.org" + +## @package view_post_glyphfilter +# \ingroup FEM +# \brief view provider for post glyph filter object + +import FreeCAD +import FreeCADGui + +import FemGui +from PySide import QtGui +from femtaskpanels import task_post_glyphfilter + + +class VPPostGlyphFilter: + """ + A View Provider for the PostGlyphFilter object + """ + + def __init__(self, vobj): + vobj.Proxy = self + + def getIcon(self): + return ":/icons/FEM_PostFilterGlyph.svg" + + def getDisplayModes(self, obj): + # Mandatory, as the ViewProviderPostFilterPython does not add any + # display modes. We can choose here any that is supported by it: + # "Outline", "Nodes", "Surface", "Surface with Edges", + # "Wireframe", "Wireframe (surface only)", "Nodes (surface only)" + + # only surface makes sense for the glyphs + return ["Surface"] + + def setDisplayMode(self, mode): + # the post object viewprovider implements the different display modes + # via vtk filter, not via masking modes. Hence we need to make sure + # to always stay in the "Default" masking mode, no matter the display mode + return "Default" + + def setEdit(self, vobj, mode): + # make sure we see what we edit + vobj.show() + + # build up the task panel + taskd = task_post_glyphfilter._TaskPanel(vobj) + + # show it + FreeCADGui.Control.showDialog(taskd) + + return True + + def unsetEdit(self, vobj, mode): + FreeCADGui.Control.closeDialog() + return True + + def dumps(self): + return None + + def loads(self, state): + return None diff --git a/src/Mod/Import/App/AppImport.cpp b/src/Mod/Import/App/AppImport.cpp index 2c5f1f9eeb..de5b5f3f78 100644 --- a/src/Mod/Import/App/AppImport.cpp +++ b/src/Mod/Import/App/AppImport.cpp @@ -51,6 +51,6 @@ PyMOD_INIT_FUNC(Import) Base::Interpreter().addType(&Import::StepShapePy ::Type, importModule, "StepShape"); - Base::Console().Log("Loading Import module... done\n"); + Base::Console().log("Loading Import module... done\n"); PyMOD_Return(importModule); } diff --git a/src/Mod/Import/App/AppImportPy.cpp b/src/Mod/Import/App/AppImportPy.cpp index 7aa936f1c2..b4349587ef 100644 --- a/src/Mod/Import/App/AppImportPy.cpp +++ b/src/Mod/Import/App/AppImportPy.cpp @@ -159,8 +159,8 @@ private: reader.read(hDoc); } catch (OSD_Exception& e) { - Base::Console().Error("%s\n", e.GetMessageString()); - Base::Console().Message("Try to load STEP file without colors...\n"); + Base::Console().error("%s\n", e.GetMessageString()); + Base::Console().message("Try to load STEP file without colors...\n"); Part::ImportStepParts(pcDoc, Utf8Name.c_str()); pcDoc->recompute(); @@ -172,8 +172,8 @@ private: reader.read(hDoc); } catch (OSD_Exception& e) { - Base::Console().Error("%s\n", e.GetMessageString()); - Base::Console().Message("Try to load IGES file without colors...\n"); + Base::Console().error("%s\n", e.GetMessageString()); + Base::Console().message("Try to load IGES file without colors...\n"); Part::ImportIgesParts(pcDoc, Utf8Name.c_str()); pcDoc->recompute(); @@ -428,7 +428,7 @@ private: Py::Object writeDXFShape(const Py::Tuple& args) { - Base::Console().Message("Imp:writeDXFShape()\n"); + Base::Console().message("Imp:writeDXFShape()\n"); PyObject* shapeObj = nullptr; char* fname = nullptr; std::string filePath; @@ -632,7 +632,7 @@ private: PyMem_Free(fname); App::DocumentObject* obj = static_cast(docObj)->getDocumentObjectPtr(); - Base::Console().Message("Imp:writeDXFObject - docObj: %s\n", obj->getNameInDocument()); + Base::Console().message("Imp:writeDXFObject - docObj: %s\n", obj->getNameInDocument()); if ((versionParm == 12) || (versionParm == 14)) { versionOverride = true; diff --git a/src/Mod/Import/App/ImportOCAF.cpp b/src/Mod/Import/App/ImportOCAF.cpp index 89d40ec7d7..65d92029a1 100644 --- a/src/Mod/Import/App/ImportOCAF.cpp +++ b/src/Mod/Import/App/ImportOCAF.cpp @@ -101,7 +101,7 @@ void ImportOCAF::tryPlacementFromMatrix(App::GeoFeature* part, const Base::Matri part->Placement.setValue(pl); } catch (const Base::ValueError& e) { - e.ReportException(); + e.reportException(); } } @@ -175,7 +175,7 @@ void ImportOCAF::loadShapes(const TDF_Label& label, } #ifdef FC_DEBUG - Base::Console().Log("H:%d, N:%s, T:%d, A:%d, S:%d, C:%d, SS:%d, F:%d, R:%d, C:%d, SS:%d\n", + Base::Console().log("H:%d, N:%s, T:%d, A:%d, S:%d, C:%d, SS:%d, F:%d, R:%d, C:%d, SS:%d\n", hash, part_name.c_str(), aShapeTool->IsTopLevel(label), diff --git a/src/Mod/Import/App/ImportOCAFAssembly.cpp b/src/Mod/Import/App/ImportOCAFAssembly.cpp index 3a904ce589..742e89f4f7 100644 --- a/src/Mod/Import/App/ImportOCAFAssembly.cpp +++ b/src/Mod/Import/App/ImportOCAFAssembly.cpp @@ -159,7 +159,7 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, std::stringstream str; - Base::Console().Log("H:%-9d \tN:%-30s \tTop:%d, Asm:%d, Shape:%d, Compound:%d, Simple:%d, " + Base::Console().log("H:%-9d \tN:%-30s \tTop:%d, Asm:%d, Shape:%d, Compound:%d, Simple:%d, " "Free:%d, Ref:%d, Component:%d, SubShape:%d\tTrf:%s-- Dep:%d \n", hash, part_name.c_str(), @@ -176,7 +176,7 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, dep); label.Dump(str); - Base::Console().Message(str.str().c_str()); + Base::Console().message(str.str().c_str()); #endif std::string asm_name = assembly; @@ -218,7 +218,7 @@ void ImportOCAFAssembly::createShape(const TDF_Label& label, const TopLoc_Location& loc, const std::string& name) { - Base::Console().Log("-create Shape\n"); + Base::Console().log("-create Shape\n"); const TopoDS_Shape& aShape = aShapeTool->GetShape(label); if (!aShape.IsNull() && aShape.ShapeType() == TopAbs_COMPOUND) { TopExp_Explorer xp; diff --git a/src/Mod/Import/App/Tools.cpp b/src/Mod/Import/App/Tools.cpp index 7efc54abe9..5888e6cacf 100644 --- a/src/Mod/Import/App/Tools.cpp +++ b/src/Mod/Import/App/Tools.cpp @@ -124,7 +124,7 @@ void Tools::printLabel(TDF_Label label, } ss << std::endl; - Base::Console().Notify("ImportOCAF2", ss.str().c_str()); + Base::Console().notify("ImportOCAF2", ss.str().c_str()); } void Tools::dumpLabels(TDF_Label label, diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.cpp b/src/Mod/Import/App/dxf/ImpExpDxf.cpp index ab9f87c2e9..115f9a1125 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.cpp +++ b/src/Mod/Import/App/dxf/ImpExpDxf.cpp @@ -189,7 +189,7 @@ bool ImpExpDxfRead::OnReadBlock(const std::string& name, int flags) // and don't want to be complaining about unhandled entity types. // Note that if it *is* for a hatch we could actually import it and use it to draw a hatch. } - else if (Blocks.count(name) > 0) { + else if (Blocks.contains(name)) { ImportError("Duplicate block name '%s'\n", name); } else { @@ -241,7 +241,7 @@ void ImpExpDxfRead::OnReadArc(const Base::Vector3d& start, Collector->AddObject(BRepBuilderAPI_MakeEdge(circle, p0, p1).Edge(), "Arc"); } else { - Base::Console().Warning("ImpExpDxf - ignore degenerate arc of circle\n"); + Base::Console().warning("ImpExpDxf - ignore degenerate arc of circle\n"); } } @@ -262,7 +262,7 @@ void ImpExpDxfRead::OnReadCircle(const Base::Vector3d& start, Collector->AddObject(BRepBuilderAPI_MakeEdge(circle).Edge(), "Circle"); } else { - Base::Console().Warning("ImpExpDxf - ignore degenerate circle\n"); + Base::Console().warning("ImpExpDxf - ignore degenerate circle\n"); } } @@ -379,7 +379,7 @@ void ImpExpDxfRead::OnReadSpline(struct SplineData& sd) Collector->AddObject(BRepBuilderAPI_MakeEdge(geom).Edge(), "Spline"); } catch (const Standard_Failure&) { - Base::Console().Warning("ImpExpDxf - failed to create bspline\n"); + Base::Console().warning("ImpExpDxf - failed to create bspline\n"); } } @@ -404,7 +404,7 @@ void ImpExpDxfRead::OnReadEllipse(const Base::Vector3d& center, Collector->AddObject(BRepBuilderAPI_MakeEdge(ellipse).Edge(), "Ellipse"); } else { - Base::Console().Warning("ImpExpDxf - ignore degenerate ellipse\n"); + Base::Console().warning("ImpExpDxf - ignore degenerate ellipse\n"); } } @@ -896,7 +896,7 @@ void ImpExpDxfWrite::exportShape(const TopoDS_Shape input) exportLine(adapt); } else { - Base::Console().Warning("ImpExpDxf - unknown curve type: %d\n", + Base::Console().warning("ImpExpDxf - unknown curve type: %d\n", static_cast(adapt.GetType())); } } @@ -1064,14 +1064,14 @@ void ImpExpDxfWrite::exportBSpline(BRepAdaptor_Curve& c) else { if (approx.HasResult()) { // result, but not within tolerance spline = approx.Curve(); - Base::Console().Message("DxfWrite::exportBSpline - result not within tolerance\n"); + Base::Console().message("DxfWrite::exportBSpline - result not within tolerance\n"); } else { f = c.FirstParameter(); l = c.LastParameter(); s = c.Value(f); ePt = c.Value(l); - Base::Console().Message( + Base::Console().message( "DxfWrite::exportBSpline - no result- from:(%.3f,%.3f) to:(%.3f,%.3f)\n", s.X(), s.Y(), @@ -1132,7 +1132,7 @@ void ImpExpDxfWrite::exportBSpline(BRepAdaptor_Curve& c) void ImpExpDxfWrite::exportBCurve(BRepAdaptor_Curve& c) { (void)c; - Base::Console().Message("BCurve dxf export not yet supported\n"); + Base::Console().message("BCurve dxf export not yet supported\n"); } void ImpExpDxfWrite::exportLine(BRepAdaptor_Curve& c) diff --git a/src/Mod/Import/App/dxf/dxf.cpp b/src/Mod/Import/App/dxf/dxf.cpp index 2672b264b2..2bd5330a84 100644 --- a/src/Mod/Import/App/dxf/dxf.cpp +++ b/src/Mod/Import/App/dxf/dxf.cpp @@ -434,7 +434,7 @@ std::string CDxfWrite::getPlateFile(std::string fileSpec) std::stringstream outString; Base::FileInfo fi(fileSpec); if (!fi.isReadable()) { - Base::Console().Message("dxf unable to open %s!\n", fileSpec.c_str()); + Base::Console().message("dxf unable to open %s!\n", fileSpec.c_str()); } else { string line; @@ -2689,7 +2689,7 @@ bool CDxfRead::ReadSection() } void CDxfRead::ProcessLayerReference(CDxfRead* object, void* target) { - if (object->Layers.count(object->m_record_data) == 0) { + if (!object->Layers.contains(object->m_record_data)) { object->ImportError("First reference to missing Layer '%s'", object->m_record_data); // Synthesize the Layer so we don't get the same error again. // We need to take copies of the string arguments because MakeLayer uses them as move @@ -2912,7 +2912,7 @@ bool CDxfRead::ReadEntitiesSection() } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { ImportError("CDxfRead::ReadEntity raised unknown exception\n"); diff --git a/src/Mod/Import/App/dxf/dxf.h b/src/Mod/Import/App/dxf/dxf.h index 2845d57bd0..c3da0d8fba 100644 --- a/src/Mod/Import/App/dxf/dxf.h +++ b/src/Mod/Import/App/dxf/dxf.h @@ -689,12 +689,12 @@ protected: template static void ImportError(const char* format, args&&... argValues) { - Base::ConsoleSingleton::Instance().Warning(format, std::forward(argValues)...); + Base::ConsoleSingleton::instance().warning(format, std::forward(argValues)...); } template static void ImportObservation(const char* format, args&&... argValues) { - Base::ConsoleSingleton::Instance().Message(format, std::forward(argValues)...); + Base::ConsoleSingleton::instance().message(format, std::forward(argValues)...); } template void UnsupportedFeature(const char* format, args&&... argValues); diff --git a/src/Mod/Import/Gui/AppImportGui.cpp b/src/Mod/Import/Gui/AppImportGui.cpp index e1d815bc98..516727fbd2 100644 --- a/src/Mod/Import/Gui/AppImportGui.cpp +++ b/src/Mod/Import/Gui/AppImportGui.cpp @@ -56,7 +56,7 @@ PyMOD_INIT_FUNC(ImportGui) } PyObject* mod = ImportGui::initModule(); - Base::Console().Log("Loading GUI of Import module... done\n"); + Base::Console().log("Loading GUI of Import module... done\n"); CreateImportCommands(); ImportGui::Workbench::init(); diff --git a/src/Mod/Import/Gui/AppImportGuiPy.cpp b/src/Mod/Import/Gui/AppImportGuiPy.cpp index 2a6143c21e..35319202c6 100644 --- a/src/Mod/Import/Gui/AppImportGuiPy.cpp +++ b/src/Mod/Import/Gui/AppImportGuiPy.cpp @@ -270,8 +270,8 @@ private: reader.read(hDoc); } catch (OSD_Exception& e) { - Base::Console().Error("%s\n", e.GetMessageString()); - Base::Console().Message("Try to load STEP file without colors...\n"); + Base::Console().error("%s\n", e.GetMessageString()); + Base::Console().message("Try to load STEP file without colors...\n"); Part::ImportStepParts(pcDoc, Utf8Name.c_str()); pcDoc->recompute(); @@ -283,8 +283,8 @@ private: reader.read(hDoc); } catch (OSD_Exception& e) { - Base::Console().Error("%s\n", e.GetMessageString()); - Base::Console().Message("Try to load IGES file without colors...\n"); + Base::Console().error("%s\n", e.GetMessageString()); + Base::Console().message("Try to load IGES file without colors...\n"); Part::ImportIgesParts(pcDoc, Utf8Name.c_str()); pcDoc->recompute(); diff --git a/src/Mod/Inspection/App/AppInspection.cpp b/src/Mod/Inspection/App/AppInspection.cpp index 48dbff3927..acbbfa5191 100644 --- a/src/Mod/Inspection/App/AppInspection.cpp +++ b/src/Mod/Inspection/App/AppInspection.cpp @@ -57,7 +57,7 @@ PyMOD_INIT_FUNC(Inspection) // // PyObject* mod = Inspection::initModule(); - Base::Console().Log("Loading Inspection module... done\n"); + Base::Console().log("Loading Inspection module... done\n"); // clang-format off Inspection::PropertyDistanceList ::init(); Inspection::Feature ::init(); diff --git a/src/Mod/Inspection/App/InspectionFeature.cpp b/src/Mod/Inspection/App/InspectionFeature.cpp index ce6868327f..5bb4bfcd44 100644 --- a/src/Mod/Inspection/App/InspectionFeature.cpp +++ b/src/Mod/Inspection/App/InspectionFeature.cpp @@ -896,7 +896,7 @@ App::DocumentObjectExecReturn* Feature::execute() fRMS = sqrt(fRMS); } - Base::Console().Message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", + Base::Console().message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", this->Label.getValue(), -this->SearchRadius.getValue(), this->SearchRadius.getValue(), fRMS); #else unsigned long count = actual->countPoints(); @@ -966,7 +966,7 @@ App::DocumentObjectExecReturn* Feature::execute() } } - Base::Console().Message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", + Base::Console().message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", this->Label.getValue(), -this->SearchRadius.getValue(), this->SearchRadius.getValue(), diff --git a/src/Mod/Inspection/Gui/AppInspectionGui.cpp b/src/Mod/Inspection/Gui/AppInspectionGui.cpp index 4ed78333ad..d19ececdb5 100644 --- a/src/Mod/Inspection/Gui/AppInspectionGui.cpp +++ b/src/Mod/Inspection/Gui/AppInspectionGui.cpp @@ -78,6 +78,6 @@ PyMOD_INIT_FUNC(InspectionGui) // PyObject* mod = InspectionGui::initModule(); - Base::Console().Log("Loading GUI of Inspection module... done\n"); + Base::Console().log("Loading GUI of Inspection module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp index 243a908335..b4b666525d 100644 --- a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp +++ b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp @@ -121,13 +121,13 @@ ViewProviderInspection::~ViewProviderInspection() deleteColorBar(); } catch (Base::Exception& e) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderInspection", "ViewProviderInspection::deleteColorBar() threw an exception: %s\n", e.what()); } catch (...) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderInspection", "ViewProviderInspection destructor threw an unknown exception"); } @@ -583,7 +583,7 @@ void ViewProviderInspection::inspectCallback(void* ud, SoEventCallback* n) && mbe->getState() == SoButtonEvent::UP) { const SoPickedPoint* point = n->getPickedPoint(); if (!point) { - Base::Console().Message("No point picked.\n"); + Base::Console().message("No point picked.\n"); return; } diff --git a/src/Mod/JtReader/App/AppJtReader.cpp b/src/Mod/JtReader/App/AppJtReader.cpp index f00d81eac1..3684bec02c 100644 --- a/src/Mod/JtReader/App/AppJtReader.cpp +++ b/src/Mod/JtReader/App/AppJtReader.cpp @@ -38,7 +38,7 @@ PyMOD_INIT_FUNC(JtReader) // load dependent module Base::Interpreter().loadModule("Mesh"); - Base::Console().Log("Loading JtReader module... done\n"); + Base::Console().log("Loading JtReader module... done\n"); PyMOD_Return(jtReaderModule); } diff --git a/src/Mod/JtReader/App/AppJtReaderPy.cpp b/src/Mod/JtReader/App/AppJtReaderPy.cpp index d4b369ede9..a2c020bdae 100644 --- a/src/Mod/JtReader/App/AppJtReaderPy.cpp +++ b/src/Mod/JtReader/App/AppJtReaderPy.cpp @@ -89,7 +89,7 @@ private: PyMem_Free(Name); - // Base::Console().Log("Open in Mesh with %s",Name); + // Base::Console().log("Open in Mesh with %s",Name); Base::FileInfo file(EncodedName); if (file.hasExtension("jt")) { TestJtReader reader; diff --git a/src/Mod/JtReader/App/FcLodHandler.cpp b/src/Mod/JtReader/App/FcLodHandler.cpp index 003924bbc9..cd3f997836 100644 --- a/src/Mod/JtReader/App/FcLodHandler.cpp +++ b/src/Mod/JtReader/App/FcLodHandler.cpp @@ -29,5 +29,5 @@ void FcLodHandler::startLod() { - Base::Console().Log("FcLodHandler::startLod()"); + Base::Console().log("FcLodHandler::startLod()"); } diff --git a/src/Mod/JtReader/App/TestJtReader.cpp b/src/Mod/JtReader/App/TestJtReader.cpp index 4a66f04a21..47839de734 100644 --- a/src/Mod/JtReader/App/TestJtReader.cpp +++ b/src/Mod/JtReader/App/TestJtReader.cpp @@ -54,6 +54,6 @@ void TestJtReader::read(void) } - Base::Console().Log(i->toString().c_str()); + Base::Console().log(i->toString().c_str()); } } diff --git a/src/Mod/Material/App/AppMaterial.cpp b/src/Mod/Material/App/AppMaterial.cpp index 266cf370db..50975b3330 100644 --- a/src/Mod/Material/App/AppMaterial.cpp +++ b/src/Mod/Material/App/AppMaterial.cpp @@ -85,7 +85,7 @@ PyMOD_INIT_FUNC(Materials) #endif PyObject* module = Materials::initModule(); - Base::Console().Log("Loading Material module... done\n"); + Base::Console().log("Loading Material module... done\n"); Base::Interpreter().addType(&Materials::Array2DPy::Type, module, "Array2D"); Base::Interpreter().addType(&Materials::Array3DPy::Type, module, "Array3D"); diff --git a/src/Mod/Material/App/Library.cpp b/src/Mod/Material/App/Library.cpp index 7e87310375..dcc1c0400a 100644 --- a/src/Mod/Material/App/Library.cpp +++ b/src/Mod/Material/App/Library.cpp @@ -68,8 +68,8 @@ void Library::validate(const Library& remote) const throw InvalidLibrary("Library names don't match"); } if (getIconPath() != remote.getIconPath()) { - Base::Console().Log("Icon path 1 '%s'\n", getIconPath().toStdString().c_str()); - Base::Console().Log("Icon path 2 '%s'\n", remote.getIconPath().toStdString().c_str()); + Base::Console().log("Icon path 1 '%s'\n", getIconPath().toStdString().c_str()); + Base::Console().log("Icon path 2 '%s'\n", remote.getIconPath().toStdString().c_str()); throw InvalidLibrary("Library icon paths don't match"); } diff --git a/src/Mod/Material/App/MaterialConfigLoader.cpp b/src/Mod/Material/App/MaterialConfigLoader.cpp index cd241acf18..c2271b2456 100644 --- a/src/Mod/Material/App/MaterialConfigLoader.cpp +++ b/src/Mod/Material/App/MaterialConfigLoader.cpp @@ -1041,7 +1041,7 @@ MaterialConfigLoader::getMaterialFromPath(const std::shared_ptr fcmat; if (!readFile(path, fcmat)) { - Base::Console().Log("Error reading '%s'\n", path.toStdString().c_str()); + Base::Console().log("Error reading '%s'\n", path.toStdString().c_str()); throw MaterialReadError(); } diff --git a/src/Mod/Material/App/MaterialLibrary.cpp b/src/Mod/Material/App/MaterialLibrary.cpp index f0af06492b..94ae7d3f11 100644 --- a/src/Mod/Material/App/MaterialLibrary.cpp +++ b/src/Mod/Material/App/MaterialLibrary.cpp @@ -92,7 +92,7 @@ MaterialLibrary::getMaterialTree(const std::shared_ptrcount(itp) == 0) { + if (!node->contains(itp)) { auto mapPtr = std::make_shared< std::map>>(); std::shared_ptr child = @@ -125,7 +125,7 @@ MaterialLibrary::getMaterialTree(const std::shared_ptrcount(itp) == 0) { + // if (!node->contains(itp)) { // std::shared_ptr>> // mapPtr = std::make_shared< // std::map>>(); @@ -167,7 +167,7 @@ void MaterialLibraryLocal::createFolder(const QString& path) QDir fileDir(filePath); if (!fileDir.exists()) { if (!fileDir.mkpath(filePath)) { - Base::Console().Error("Unable to create directory path '%s'\n", + Base::Console().error("Unable to create directory path '%s'\n", filePath.toStdString().c_str()); } } @@ -181,7 +181,7 @@ void MaterialLibraryLocal::renameFolder(const QString& oldPath, const QString& n QDir fileDir(filePath); if (fileDir.exists()) { if (!fileDir.rename(filePath, newFilePath)) { - Base::Console().Error("Unable to rename directory path '%s'\n", + Base::Console().error("Unable to rename directory path '%s'\n", filePath.toStdString().c_str()); } } @@ -257,7 +257,7 @@ void MaterialLibraryLocal::deleteFile(MaterialManager& manager, const QString& p manager.remove(material->getUUID()); } catch (const MaterialNotFound&) { - Base::Console().Log("Unable to remove file from materials list\n"); + Base::Console().log("Unable to remove file from materials list\n"); } _materialPathMap->erase(rPath); } @@ -300,14 +300,14 @@ MaterialLibraryLocal::saveMaterial(const std::shared_ptr& material, QDir fileDir(info.path()); if (!fileDir.exists()) { if (!fileDir.mkpath(info.path())) { - Base::Console().Error("Unable to create directory path '%s'\n", + Base::Console().error("Unable to create directory path '%s'\n", info.path().toStdString().c_str()); } } if (info.exists()) { if (!overwrite) { - Base::Console().Error("File already exists '%s'\n", info.path().toStdString().c_str()); + Base::Console().error("File already exists '%s'\n", info.path().toStdString().c_str()); throw MaterialExists(); } } diff --git a/src/Mod/Material/App/MaterialLoader.cpp b/src/Mod/Material/App/MaterialLoader.cpp index 7bdc4a881f..8aba6e07e2 100644 --- a/src/Mod/Material/App/MaterialLoader.cpp +++ b/src/Mod/Material/App/MaterialLoader.cpp @@ -246,19 +246,35 @@ void MaterialYamlEntry::addToTree( propertyValue = propertyValue.remove( QRegularExpression(QStringLiteral("[\r\n]"))); } - finalModel->setPhysicalValue(QString::fromStdString(propertyName), - propertyValue); + try { + finalModel->setPhysicalValue(QString::fromStdString(propertyName), + propertyValue); + } + catch (const Base::ValueError& e) { + // Units mismatch + Base::Console().log("Units mismatch in material '%s':'%s' = '%s', " + "setting to default property units '%s'\n", + name.toStdString().c_str(), + propertyName, + propertyValue.toStdString().c_str(), + prop->getUnits().toStdString().c_str()); + auto quantity = Base::Quantity::parse(propertyValue.toStdString()); + finalModel->setPhysicalValue( + QString::fromStdString(propertyName), + Base::Quantity(quantity.getValue(), + prop->getUnits().toStdString())); + } } } catch (const YAML::BadConversion& e) { - Base::Console().Log("Exception %s <%s:%s> - ignored\n", + Base::Console().log("Exception %s <%s:%s> - ignored\n", e.what(), name.toStdString().c_str(), propertyName.c_str()); } } else if (propertyName != "UUID") { - Base::Console().Log("\tProperty '%s' is not described by any model. Ignored\n", + Base::Console().log("\tProperty '%s' is not described by any model. Ignored\n", propertyName.c_str()); } } @@ -318,14 +334,14 @@ void MaterialYamlEntry::addToTree( } } catch (const YAML::BadConversion& e) { - Base::Console().Log("Exception %s <%s:%s> - ignored\n", + Base::Console().log("Exception %s <%s:%s> - ignored\n", e.what(), name.toStdString().c_str(), propertyName.c_str()); } } else if (propertyName != "UUID") { - Base::Console().Log("\tProperty '%s' is not described by any model. Ignored\n", + Base::Console().log("\tProperty '%s' is not described by any model. Ignored\n", propertyName.c_str()); } } @@ -377,8 +393,8 @@ MaterialLoader::getMaterialFromYAML(const std::shared_ptr& yamlroot); } catch (YAML::Exception const& e) { - Base::Console().Error("YAML parsing error: '%s'\n", path.toStdString().c_str()); - Base::Console().Error("\t'%s'\n", e.what()); + Base::Console().error("YAML parsing error: '%s'\n", path.toStdString().c_str()); + Base::Console().error("\t'%s'\n", e.what()); showYaml(yamlroot); } @@ -411,7 +427,7 @@ MaterialLoader::getMaterialFromPath(const std::shared_ptr& Base::FileInfo info(pathName); Base::ifstream fin(info); if (!fin) { - Base::Console().Error("YAML file open error: '%s'\n", pathName.c_str()); + Base::Console().error("YAML file open error: '%s'\n", pathName.c_str()); return model; } @@ -422,8 +438,8 @@ MaterialLoader::getMaterialFromPath(const std::shared_ptr& model = getMaterialFromYAML(materialLibrary, yamlroot, path); } catch (YAML::Exception const& e) { - Base::Console().Error("YAML parsing error: '%s'\n", pathName.c_str()); - Base::Console().Error("\t'%s'\n", e.what()); + Base::Console().error("YAML parsing error: '%s'\n", pathName.c_str()); + Base::Console().error("\t'%s'\n", e.what()); showYaml(yamlroot); } @@ -437,7 +453,7 @@ void MaterialLoader::showYaml(const YAML::Node& yaml) out << yaml; std::string logData = out.str(); - Base::Console().Log("%s\n", logData.c_str()); + Base::Console().log("%s\n", logData.c_str()); } @@ -457,7 +473,7 @@ void MaterialLoader::dereference( parent = materialMap->at(parentUUID); } catch (std::out_of_range&) { - Base::Console().Log( + Base::Console().log( "Unable to apply inheritance for material '%s', parent '%s' not found.\n", material->getName().toStdString().c_str(), parentUUID.toStdString().c_str()); diff --git a/src/Mod/Material/App/MaterialManager.cpp b/src/Mod/Material/App/MaterialManager.cpp index 67fb0d9b14..f5ca97b66e 100644 --- a/src/Mod/Material/App/MaterialManager.cpp +++ b/src/Mod/Material/App/MaterialManager.cpp @@ -103,7 +103,7 @@ void MaterialManager::OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp: { const ParameterGrp& rGrp = static_cast(rCaller); if (strcmp(Reason, "UseExternal") == 0) { - Base::Console().Log("Use external changed\n"); + Base::Console().log("Use external changed\n"); _useExternal = rGrp.GetBool("UseExternal", false); // _dbManager->refresh(); } diff --git a/src/Mod/Material/App/MaterialManagerLocal.cpp b/src/Mod/Material/App/MaterialManagerLocal.cpp index 7db46b2bad..3c96b905ce 100644 --- a/src/Mod/Material/App/MaterialManagerLocal.cpp +++ b/src/Mod/Material/App/MaterialManagerLocal.cpp @@ -559,7 +559,7 @@ MaterialManagerLocal::getConfiguredLibraries() if (!materialDir.exists()) { // Try creating the user dir if it doesn't exist if (!materialDir.mkpath(resourceDir)) { - Base::Console().Log("Unable to create user library '%s'\n", + Base::Console().log("Unable to create user library '%s'\n", resourceDir.toStdString().c_str()); } } diff --git a/src/Mod/Material/App/MaterialManagerPyImp.cpp b/src/Mod/Material/App/MaterialManagerPyImp.cpp index 61afb574f1..5b2fe808b2 100644 --- a/src/Mod/Material/App/MaterialManagerPyImp.cpp +++ b/src/Mod/Material/App/MaterialManagerPyImp.cpp @@ -255,8 +255,8 @@ PyObject* MaterialManagerPy::save(PyObject* args, PyObject* kwds) return nullptr; } - Base::Console().Log("library name %s\n", libraryName); - Base::Console().Log("path %s\n", path); + Base::Console().log("library name %s\n", libraryName); + Base::Console().log("path %s\n", path); MaterialPy* material; if (QLatin1String(obj->ob_type->tp_name) == QLatin1String("Materials.Material")) { diff --git a/src/Mod/Material/App/MaterialValue.cpp b/src/Mod/Material/App/MaterialValue.cpp index ba20eeb1c0..f8514c2845 100644 --- a/src/Mod/Material/App/MaterialValue.cpp +++ b/src/Mod/Material/App/MaterialValue.cpp @@ -431,11 +431,11 @@ void Array2D::validateColumn(int column) const void Array2D::validate(const Array2D& other) const { if (rows() != other.rows()) { - Base::Console().Log("Local row count %d, remote %d\n", rows(), other.rows()); + Base::Console().log("Local row count %d, remote %d\n", rows(), other.rows()); throw InvalidProperty("Material property value row counts don't match"); } if (columns() != other.columns()) { - Base::Console().Log("Local column count %d, remote %d\n", columns(), other.columns()); + Base::Console().log("Local column count %d, remote %d\n", columns(), other.columns()); throw InvalidProperty("Material property value column counts don't match"); } try { @@ -534,11 +534,11 @@ QVariant Array2D::getValue(int row, int column) const void Array2D::dumpRow(const std::shared_ptr>& row) { - Base::Console().Log("row: "); + Base::Console().log("row: "); for (auto& column : *row) { - Base::Console().Log("'%s' ", column.toString().toStdString().c_str()); + Base::Console().log("'%s' ", column.toString().toStdString().c_str()); } - Base::Console().Log("\n"); + Base::Console().log("\n"); } void Array2D::dump() const diff --git a/src/Mod/Material/App/Materials.cpp b/src/Mod/Material/App/Materials.cpp index 90ad18b073..3a0c9f1890 100644 --- a/src/Mod/Material/App/Materials.cpp +++ b/src/Mod/Material/App/Materials.cpp @@ -283,7 +283,20 @@ QVariant MaterialProperty::getColumnNull(int column) const void MaterialProperty::setValue(const QVariant& value) { - _valuePtr->setValue(value); + if (_valuePtr->getType() == MaterialValue::Quantity && value.canConvert()) { + // Ensure the units are set correctly + auto quantity = value.value(); + if (quantity.isValid()) { + setQuantity(quantity); + } + else { + // Set a default value with default units + setValue(QStringLiteral("0")); + } + } + else { + _valuePtr->setValue(value); + } } void MaterialProperty::setValue(const QString& value) @@ -309,7 +322,7 @@ void MaterialProperty::setValue(const QString& value) setQuantity(Base::Quantity::parse(value.toStdString())); } catch (const Base::ParserError& e) { - Base::Console().Log("MaterialProperty::setValue Error '%s' - '%s'\n", + Base::Console().log("MaterialProperty::setValue Error '%s' - '%s'\n", e.what(), value.toStdString().c_str()); // Save as a string @@ -386,6 +399,20 @@ void MaterialProperty::setFloat(const QString& value) void MaterialProperty::setQuantity(const Base::Quantity& value) { auto quantity = value; + if (quantity.isDimensionless()) { + // Assign the default units when none are provided. + // + // This needs to be parsed rather than just setting units. Otherwise we get mm->m conversion + // errors, etc + quantity = Base::Quantity::parse(quantity.getUserString() + getUnits().toStdString()); + } + else { + auto propertyUnit = Base::Quantity::parse(getUnits().toStdString()).getUnit(); + auto units = quantity.getUnit(); + if (propertyUnit != units) { + throw Base::ValueError("Incompatible material units"); + } + } quantity.setFormat(MaterialValue::getQuantityFormat()); _valuePtr->setValue(QVariant(QVariant::fromValue(quantity))); } @@ -703,7 +730,7 @@ void Material::addPhysical(const QString& uuid) _physical[propertyName] = std::make_shared(property, uuid); } catch (const UnknownValueType&) { - Base::Console().Error("Property '%s' has unknown type '%s'. Ignoring\n", + Base::Console().error("Property '%s' has unknown type '%s'. Ignoring\n", property.getName().toStdString().c_str(), property.getPropertyType().toStdString().c_str()); } @@ -745,7 +772,7 @@ void Material::removePhysical(const QString& uuid) setEditStateAlter(); } catch (ModelNotFound const&) { - Base::Console().Log("Physical model not found '%s'\n", uuid.toStdString().c_str()); + Base::Console().log("Physical model not found '%s'\n", uuid.toStdString().c_str()); } } @@ -781,7 +808,7 @@ void Material::addAppearance(const QString& uuid) } } catch (ModelNotFound const&) { - Base::Console().Log("Appearance model not found '%s'\n", uuid.toStdString().c_str()); + Base::Console().log("Appearance model not found '%s'\n", uuid.toStdString().c_str()); } } @@ -1399,7 +1426,7 @@ void Material::saveModels(QTextStream& stream, bool saveInherited) const } } catch (const PropertyNotFound&) { - Base::Console().Log("Material::saveModels Property not found '%s'\n", + Base::Console().log("Material::saveModels Property not found '%s'\n", propertyName.toStdString().c_str()); } @@ -1730,7 +1757,7 @@ App::Material Material::getMaterialAppearance() const if (hasAppearanceProperty(QStringLiteral("TextureImage"))) { auto property = getAppearanceProperty(QStringLiteral("TextureImage")); if (!property->isNull()) { - Base::Console().Log("Has 'TextureImage'\n"); + Base::Console().log("Has 'TextureImage'\n"); material.image = property->getString().toStdString(); } @@ -1739,7 +1766,7 @@ App::Material Material::getMaterialAppearance() const else if (hasAppearanceProperty(QStringLiteral("TexturePath"))) { auto property = getAppearanceProperty(QStringLiteral("TexturePath")); if (!property->isNull()) { - Base::Console().Log("Has 'TexturePath'\n"); + Base::Console().log("Has 'TexturePath'\n"); material.imagePath = property->getString().toStdString(); } @@ -1796,8 +1823,8 @@ void Material::validate(const std::shared_ptr& other) const } if (_tags.size() != other->_tags.size()) { - Base::Console().Log("Local tags count %d\n", _tags.size()); - Base::Console().Log("Remote tags count %d\n", other->_tags.size()); + Base::Console().log("Local tags count %d\n", _tags.size()); + Base::Console().log("Remote tags count %d\n", other->_tags.size()); throw InvalidMaterial("Material tags counts don't match"); } if (!other->_tags.contains(_tags)) { @@ -1805,8 +1832,8 @@ void Material::validate(const std::shared_ptr& other) const } if (_physicalUuids.size() != other->_physicalUuids.size()) { - Base::Console().Log("Local physical model count %d\n", _physicalUuids.size()); - Base::Console().Log("Remote physical model count %d\n", other->_physicalUuids.size()); + Base::Console().log("Local physical model count %d\n", _physicalUuids.size()); + Base::Console().log("Remote physical model count %d\n", other->_physicalUuids.size()); throw InvalidMaterial("Material physical model counts don't match"); } if (!other->_physicalUuids.contains(_physicalUuids)) { @@ -1814,8 +1841,8 @@ void Material::validate(const std::shared_ptr& other) const } if (_physicalUuids.size() != other->_physicalUuids.size()) { - Base::Console().Log("Local appearance model count %d\n", _physicalUuids.size()); - Base::Console().Log("Remote appearance model count %d\n", other->_physicalUuids.size()); + Base::Console().log("Local appearance model count %d\n", _physicalUuids.size()); + Base::Console().log("Remote appearance model count %d\n", other->_physicalUuids.size()); throw InvalidMaterial("Material appearance model counts don't match"); } if (!other->_physicalUuids.contains(_physicalUuids)) { @@ -1823,8 +1850,8 @@ void Material::validate(const std::shared_ptr& other) const } if (_allUuids.size() != other->_allUuids.size()) { - Base::Console().Log("Local model count %d\n", _allUuids.size()); - Base::Console().Log("Remote model count %d\n", other->_allUuids.size()); + Base::Console().log("Local model count %d\n", _allUuids.size()); + Base::Console().log("Remote model count %d\n", other->_allUuids.size()); throw InvalidMaterial("Material model counts don't match"); } if (!other->_allUuids.contains(_allUuids)) { diff --git a/src/Mod/Material/App/Model.cpp b/src/Mod/Material/App/Model.cpp index 9c7d0a7bcf..78eeac9d7e 100644 --- a/src/Mod/Material/App/Model.cpp +++ b/src/Mod/Material/App/Model.cpp @@ -113,8 +113,8 @@ void ModelProperty::validate(const ModelProperty& other) const throw InvalidProperty("Model names don't match"); } if (getDisplayName() != other.getDisplayName()) { - Base::Console().Log("Local display name '%s'\n", getDisplayName().toStdString().c_str()); - Base::Console().Log("Remote display name '%s'\n", + Base::Console().log("Local display name '%s'\n", getDisplayName().toStdString().c_str()); + Base::Console().log("Remote display name '%s'\n", other.getDisplayName().toStdString().c_str()); throw InvalidProperty("Model display names don't match"); } @@ -135,8 +135,8 @@ void ModelProperty::validate(const ModelProperty& other) const } if (_columns.size() != other._columns.size()) { - Base::Console().Log("Local property column count %d\n", _columns.size()); - Base::Console().Log("Remote property column count %d\n", other._columns.size()); + Base::Console().log("Local property column count %d\n", _columns.size()); + Base::Console().log("Remote property column count %d\n", other._columns.size()); throw InvalidProperty("Model property column counts don't match"); } for (size_t i = 0; i < _columns.size(); i++) { @@ -243,8 +243,8 @@ void Model::validate(const std::shared_ptr& other) const // Need to compare properties if (_properties.size() != other->_properties.size()) { - // Base::Console().Log("Local property count %d\n", _properties.size()); - // Base::Console().Log("Remote property count %d\n", other->_properties.size()); + // Base::Console().log("Local property count %d\n", _properties.size()); + // Base::Console().log("Remote property count %d\n", other->_properties.size()); throw InvalidModel("Model property counts don't match"); } for (auto& property : _properties) { diff --git a/src/Mod/Material/App/ModelLibrary.cpp b/src/Mod/Material/App/ModelLibrary.cpp index c05e39a6bb..a1346ae25c 100644 --- a/src/Mod/Material/App/ModelLibrary.cpp +++ b/src/Mod/Material/App/ModelLibrary.cpp @@ -87,7 +87,7 @@ ModelLibrary::getModelTree(ModelFilter filter) const std::shared_ptr>> node = modelTree; for (auto& itp : list) { // Add the folder only if it's not already there - if (node->count(itp) == 0) { + if (!node->contains(itp)) { auto mapPtr = std::make_shared>>(); std::shared_ptr child = std::make_shared(); diff --git a/src/Mod/Material/App/ModelLoader.cpp b/src/Mod/Material/App/ModelLoader.cpp index 36dd8b1db6..671cb8db3d 100644 --- a/src/Mod/Material/App/ModelLoader.cpp +++ b/src/Mod/Material/App/ModelLoader.cpp @@ -138,7 +138,7 @@ void ModelLoader::showYaml(const YAML::Node& yaml) const out << yaml; std::string logData = out.str(); - Base::Console().Log("%s\n", logData.c_str()); + Base::Console().log("%s\n", logData.c_str()); } void ModelLoader::dereference(const QString& uuid, @@ -163,7 +163,7 @@ void ModelLoader::dereference(const QString& uuid, auto childProperties = childYaml[childBase]; for (auto it = childProperties.begin(); it != childProperties.end(); it++) { std::string name = it->first.as(); - if (exclude.count(QString::fromStdString(name)) == 0) { + if (!exclude.contains(QString::fromStdString(name))) { // showYaml(it->second); if (!parentProperties[name]) { parentProperties[name] = it->second; @@ -198,7 +198,7 @@ void ModelLoader::dereference(std::shared_ptr model, dereference(model->getUUID(), model, child, inheritances); } catch (const std::out_of_range&) { - Base::Console().Log("Unable to find '%s' in model map\n", + Base::Console().log("Unable to find '%s' in model map\n", nodeName.toStdString().c_str()); } } @@ -261,7 +261,7 @@ void ModelLoader::addToTree(std::shared_ptr model, auto yamlProperties = yamlModel[base]; for (auto it = yamlProperties.begin(); it != yamlProperties.end(); it++) { std::string propName = it->first.as(); - if (exclude.count(QString::fromStdString(propName)) == 0) { + if (!exclude.contains(QString::fromStdString(propName))) { // showYaml(it->second); auto yamlProp = yamlProperties[propName]; auto propDisplayName = yamlValue(yamlProp, "DisplayName", ""); @@ -304,7 +304,7 @@ void ModelLoader::addToTree(std::shared_ptr model, } auto key = std::pair(uuid, QString::fromStdString(propName)); - if (inheritances->count(key) > 0) { + if (inheritances->contains(key)) { property.setInheritance((*inheritances)[key]); } @@ -333,7 +333,7 @@ void ModelLoader::loadLibrary(std::shared_ptr library) // showYaml(model->getModel()); } catch (InvalidModel const&) { - Base::Console().Log("Invalid model '%s'\n", pathname.toStdString().c_str()); + Base::Console().log("Invalid model '%s'\n", pathname.toStdString().c_str()); } } } diff --git a/src/Mod/Material/App/ModelManager.cpp b/src/Mod/Material/App/ModelManager.cpp index f0401dfff7..aeb0c1bece 100644 --- a/src/Mod/Material/App/ModelManager.cpp +++ b/src/Mod/Material/App/ModelManager.cpp @@ -95,7 +95,7 @@ void ModelManager::OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::Me { const ParameterGrp& rGrp = static_cast(rCaller); if (strcmp(Reason, "UseExternal") == 0) { - Base::Console().Log("Use external changed\n"); + Base::Console().log("Use external changed\n"); _useExternal = rGrp.GetBool("UseExternal", false); // _dbManager->refresh(); } diff --git a/src/Mod/Material/Gui/AppMatGui.cpp b/src/Mod/Material/Gui/AppMatGui.cpp index 8d6626d3c4..f406363590 100644 --- a/src/Mod/Material/Gui/AppMatGui.cpp +++ b/src/Mod/Material/Gui/AppMatGui.cpp @@ -94,7 +94,7 @@ PyMOD_INIT_FUNC(MatGui) PyObject* matGuiModule = MatGui::initModule(); - Base::Console().Log("Loading GUI of Material module... done\n"); + Base::Console().log("Loading GUI of Material module... done\n"); MatGui::Workbench ::init(); auto manip = std::make_shared(); diff --git a/src/Mod/Material/Gui/Array2D.cpp b/src/Mod/Material/Gui/Array2D.cpp index 2d2f6acefc..90062f96ec 100644 --- a/src/Mod/Material/Gui/Array2D.cpp +++ b/src/Mod/Material/Gui/Array2D.cpp @@ -58,7 +58,7 @@ Array2D::Array2D(const QString& propertyName, _property = material->getAppearanceProperty(propertyName); } else { - Base::Console().Log("Property '%s' not found\n", propertyName.toStdString().c_str()); + Base::Console().log("Property '%s' not found\n", propertyName.toStdString().c_str()); _property = nullptr; } if (_property) { diff --git a/src/Mod/Material/Gui/Array3D.cpp b/src/Mod/Material/Gui/Array3D.cpp index f91b3f5b83..fe32438761 100644 --- a/src/Mod/Material/Gui/Array3D.cpp +++ b/src/Mod/Material/Gui/Array3D.cpp @@ -54,7 +54,7 @@ Array3D::Array3D(const QString& propertyName, _property = material->getAppearanceProperty(propertyName); } else { - Base::Console().Log("Property '%s' not found\n", propertyName.toStdString().c_str()); + Base::Console().log("Property '%s' not found\n", propertyName.toStdString().c_str()); _property = nullptr; } if (_property) { diff --git a/src/Mod/Material/Gui/ArrayModel.cpp b/src/Mod/Material/Gui/ArrayModel.cpp index c51fa0062e..c8c72ecc86 100644 --- a/src/Mod/Material/Gui/ArrayModel.cpp +++ b/src/Mod/Material/Gui/ArrayModel.cpp @@ -391,7 +391,7 @@ QVariant Array3DModel::data(const QModelIndex& index, int role) const catch (const Materials::InvalidIndex&) { } catch (const std::exception& e) { - Base::Console().Error("The error message is: %s\n", e.what()); + Base::Console().error("The error message is: %s\n", e.what()); } try { @@ -442,7 +442,7 @@ bool Array3DModel::setData(const QModelIndex& index, const QVariant& value, int _value->setValue(index.row(), index.column(), value.value()); } catch (const Materials::InvalidIndex&) { - Base::Console().Error("Array3DModel::setData - InvalidIndex"); + Base::Console().error("Array3DModel::setData - InvalidIndex"); } Q_EMIT dataChanged(index, index); diff --git a/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp b/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp index b043b20ac0..aa2aaa0095 100644 --- a/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp +++ b/src/Mod/Material/Gui/DlgDisplayPropertiesImp.cpp @@ -421,7 +421,7 @@ void DlgDisplayPropertiesImp::onChangeModeActivated(const QString& s) void DlgDisplayPropertiesImp::onChangePlotActivated(const QString& s) { - Base::Console().Log("Plot = %s\n", (const char*)s.toLatin1()); + Base::Console().log("Plot = %s\n", (const char*)s.toLatin1()); } /** diff --git a/src/Mod/Material/Gui/DlgInspectMaterial.cpp b/src/Mod/Material/Gui/DlgInspectMaterial.cpp index 01b34c885b..e5512ba0a3 100644 --- a/src/Mod/Material/Gui/DlgInspectMaterial.cpp +++ b/src/Mod/Material/Gui/DlgInspectMaterial.cpp @@ -205,7 +205,7 @@ void DlgInspectMaterial::update(std::vector& views) void DlgInspectMaterial::updateMaterialTree(const Materials::Material& material) { - Base::Console().Log("Material '%s'\n", material.getName().toStdString().c_str()); + Base::Console().log("Material '%s'\n", material.getName().toStdString().c_str()); auto tree = ui->treeMaterials; auto model = qobject_cast(tree->model()); diff --git a/src/Mod/Material/Gui/ImageEdit.cpp b/src/Mod/Material/Gui/ImageEdit.cpp index d0ba4e70ba..4629b3b053 100644 --- a/src/Mod/Material/Gui/ImageEdit.cpp +++ b/src/Mod/Material/Gui/ImageEdit.cpp @@ -122,7 +122,7 @@ ImageEdit::ImageEdit(const QString& propertyName, _property = material->getAppearanceProperty(propertyName); } else { - Base::Console().Log("Property '%s' not found\n", propertyName.toStdString().c_str()); + Base::Console().log("Property '%s' not found\n", propertyName.toStdString().c_str()); _property = nullptr; } if (_property) { @@ -141,7 +141,7 @@ ImageEdit::ImageEdit(const QString& propertyName, } } else { - Base::Console().Log("No value loaded\n"); + Base::Console().log("No value loaded\n"); showPixmap(); } diff --git a/src/Mod/Material/Gui/ListEdit.cpp b/src/Mod/Material/Gui/ListEdit.cpp index a18022399b..4a74054cec 100644 --- a/src/Mod/Material/Gui/ListEdit.cpp +++ b/src/Mod/Material/Gui/ListEdit.cpp @@ -57,14 +57,14 @@ ListEdit::ListEdit(const QString& propertyName, _property = material->getAppearanceProperty(propertyName); } else { - Base::Console().Log("Property '%s' not found\n", propertyName.toStdString().c_str()); + Base::Console().log("Property '%s' not found\n", propertyName.toStdString().c_str()); _property = nullptr; } if (_property) { _value = _property->getList(); } else { - Base::Console().Log("No value loaded\n"); + Base::Console().log("No value loaded\n"); } setupListView(); diff --git a/src/Mod/Material/Gui/MaterialDelegate.cpp b/src/Mod/Material/Gui/MaterialDelegate.cpp index ad36b74462..5218b687d4 100644 --- a/src/Mod/Material/Gui/MaterialDelegate.cpp +++ b/src/Mod/Material/Gui/MaterialDelegate.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -143,7 +144,32 @@ void MaterialDelegate::setValue(QAbstractItemModel* model, auto propertyName = group->child(row, 0)->data().toString(); std::string _name = propertyName.toStdString(); auto property = material->getProperty(propertyName); - property->setValue(value); + + try { + property->setValue(value); + } + catch (const Base::ValueError& e) { + // Units mismatch + auto quantity = value.value(); + Base::Console().log("Units mismatch '%s' = '%s', " + "setting to default property units '%s'\n", + propertyName.toStdString().c_str(), + quantity.getUserString().c_str(), + property->getUnits().toStdString().c_str()); + + QMessageBox msgBox; + msgBox.setWindowTitle(QStringLiteral("Property units mismatch")); + msgBox.setText(QStringLiteral("Units mismatch '%1' = '%2', " + "setting to default property units '%3'\n") + .arg(propertyName) + .arg(QString::fromStdString(quantity.getUserString())) + .arg(property->getUnits())); + msgBox.exec(); + + property->setQuantity( + Base::Quantity(quantity.getValue(), property->getUnits().toStdString())); + } + group->child(row, 1)->setText(property->getString()); } diff --git a/src/Mod/Material/Gui/MaterialSave.cpp b/src/Mod/Material/Gui/MaterialSave.cpp index a0c2beca4a..6674baeae7 100644 --- a/src/Mod/Material/Gui/MaterialSave.cpp +++ b/src/Mod/Material/Gui/MaterialSave.cpp @@ -291,12 +291,10 @@ void MaterialSave::setLibraries() auto libraries = Materials::MaterialManager::getManager().getLibraries(); for (auto& library : *libraries) { if (library->isLocal()) { - auto materialLibrary = - reinterpret_cast&>(library); - if (!materialLibrary->isReadOnly()) { + if (!library->isReadOnly()) { QVariant libraryVariant; - libraryVariant.setValue(materialLibrary); - ui->comboLibrary->addItem(materialLibrary->getName(), libraryVariant); + libraryVariant.setValue(library); + ui->comboLibrary->addItem(library->getName(), libraryVariant); } } } @@ -333,8 +331,7 @@ void MaterialSave::addMaterials( for (auto& mat : *modelTree) { std::shared_ptr nodePtr = mat.second; if (nodePtr->getType() == Materials::MaterialTreeNode::NodeType::DataNode) { - std::shared_ptr material = nodePtr->getData(); - QString uuid = material->getUUID(); + QString uuid = nodePtr->getUUID(); auto card = new QStandardItem(icon, mat.first); card->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled @@ -404,7 +401,7 @@ void MaterialSave::onSelectModel(const QItemSelection& selected, const QItemSele _filename = QString(ui->editFilename->text()); // No filename by default auto model = static_cast(ui->treeMaterials->model()); QModelIndexList indexes = selected.indexes(); - if (indexes.count() == 0) { + if (indexes.isEmpty()) { _selectedPath = QStringLiteral("/") + _libraryName; _selectedFull = _selectedPath; _selectedUUID = QString(); diff --git a/src/Mod/Material/Gui/MaterialTreeWidget.cpp b/src/Mod/Material/Gui/MaterialTreeWidget.cpp index 13ae712033..0c7519667e 100644 --- a/src/Mod/Material/Gui/MaterialTreeWidget.cpp +++ b/src/Mod/Material/Gui/MaterialTreeWidget.cpp @@ -274,7 +274,7 @@ void MaterialTreeWidget::updateMaterial(const QString& uuid) material = std::make_shared(*getMaterialManager().getMaterial(uuid)); } catch (Materials::MaterialNotFound const&) { - Base::Console().Log("*** Unable to load material '%s'\n", uuid.toStdString().c_str()); + Base::Console().log("*** Unable to load material '%s'\n", uuid.toStdString().c_str()); } m_materialDisplay = material->getName(); diff --git a/src/Mod/Material/Gui/MaterialTreeWidget.h b/src/Mod/Material/Gui/MaterialTreeWidget.h index 4b58759c3c..02602e9a79 100644 --- a/src/Mod/Material/Gui/MaterialTreeWidget.h +++ b/src/Mod/Material/Gui/MaterialTreeWidget.h @@ -144,7 +144,7 @@ public: } void setIncludeEmptyLibraries(bool value) { - Base::Console().Log("setIncludeEmptyLibraries(%s)\n", (value ? "true" : "false")); + Base::Console().log("setIncludeEmptyLibraries(%s)\n", (value ? "true" : "false")); _filterOptions.setIncludeEmptyLibraries(value); } @@ -287,4 +287,4 @@ protected: } // namespace MatGui -#endif // MATGUI_MATERIALTREEWIDGET_H \ No newline at end of file +#endif // MATGUI_MATERIALTREEWIDGET_H diff --git a/src/Mod/Material/Gui/MaterialsEditor.cpp b/src/Mod/Material/Gui/MaterialsEditor.cpp index e351d5b07f..51302dbd8b 100644 --- a/src/Mod/Material/Gui/MaterialsEditor.cpp +++ b/src/Mod/Material/Gui/MaterialsEditor.cpp @@ -394,7 +394,7 @@ void MaterialsEditor::onPhysicalAdd(bool checked) updateMaterial(); } else { - Base::Console().Log("No model selected\n"); + Base::Console().log("No model selected\n"); } } @@ -440,7 +440,7 @@ void MaterialsEditor::onAppearanceAdd(bool checked) updateMaterial(); } else { - Base::Console().Log("No model selected\n"); + Base::Console().log("No model selected\n"); } } @@ -590,7 +590,7 @@ void MaterialsEditor::saveMaterial() void MaterialsEditor::accept() { if (_material->isOldFormat()) { - Base::Console().Log("*** Old Format File ***\n"); + Base::Console().log("*** Old Format File ***\n"); oldFormatError(); return; @@ -914,7 +914,7 @@ bool MaterialsEditor::updateTexturePreview() const try { auto property = _material->getAppearanceProperty(QStringLiteral("TextureImage")); if (!property->isNull()) { - // Base::Console().Log("Has 'TextureImage'\n"); + // Base::Console().log("Has 'TextureImage'\n"); auto propertyValue = property->getString(); if (!propertyValue.isEmpty()) { QByteArray by = QByteArray::fromBase64(propertyValue.toUtf8()); @@ -931,10 +931,10 @@ bool MaterialsEditor::updateTexturePreview() const try { auto property = _material->getAppearanceProperty(QStringLiteral("TexturePath")); if (!property->isNull()) { - // Base::Console().Log("Has 'TexturePath'\n"); + // Base::Console().log("Has 'TexturePath'\n"); auto filePath = property->getString(); if (!image.load(filePath)) { - Base::Console().Log("Unable to load image '%s'\n", + Base::Console().log("Unable to load image '%s'\n", filePath.toStdString().c_str()); // return; // ??? } @@ -950,7 +950,7 @@ bool MaterialsEditor::updateTexturePreview() const auto property = _material->getAppearanceProperty(QStringLiteral("TextureScaling")); if (!property->isNull()) { // scaling = property->getFloat(); - // Base::Console().Log("Has 'TextureScaling' = %g\n", scaling); + // Base::Console().log("Has 'TextureScaling' = %g\n", scaling); } } catch (const Materials::PropertyNotFound&) { @@ -1262,7 +1262,7 @@ void MaterialsEditor::onSelectMaterial(const QItemSelection& selected, _material = std::make_shared(*getMaterialManager().getMaterial(uuid)); } catch (Materials::ModelNotFound const&) { - Base::Console().Log("*** Unable to load material '%s'\n", uuid.toStdString().c_str()); + Base::Console().log("*** Unable to load material '%s'\n", uuid.toStdString().c_str()); _material = std::make_shared(); } diff --git a/src/Mod/Material/Gui/MaterialsEditor.h b/src/Mod/Material/Gui/MaterialsEditor.h index 0ad9e9e5b7..da523c850b 100644 --- a/src/Mod/Material/Gui/MaterialsEditor.h +++ b/src/Mod/Material/Gui/MaterialsEditor.h @@ -218,7 +218,7 @@ private: } void setIncludeEmptyLibraries(bool value) { - Base::Console().Log("setIncludeEmptyLibraries(%s)\n", (value ? "true" : "false")); + Base::Console().log("setIncludeEmptyLibraries(%s)\n", (value ? "true" : "false")); _filterOptions.setIncludeEmptyLibraries(value); } diff --git a/src/Mod/Material/Gui/ModelSelect.cpp b/src/Mod/Material/Gui/ModelSelect.cpp index 4f43325223..d2d7723824 100644 --- a/src/Mod/Material/Gui/ModelSelect.cpp +++ b/src/Mod/Material/Gui/ModelSelect.cpp @@ -240,8 +240,12 @@ void ModelSelect::addModels( for (auto& mod : *modelTree) { std::shared_ptr nodePtr = mod.second; if (nodePtr->getType() == Materials::ModelTreeNode::NodeType::DataNode) { + QString uuid = nodePtr->getUUID(); auto model = nodePtr->getData(); - QString uuid = model->getUUID(); + if (!model) { + model = Materials::ModelManager::getManager().getModel(uuid); + nodePtr->setData(model); + } auto card = new QStandardItem(icon, model->getName()); card->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDragEnabled diff --git a/src/Mod/Material/Gui/TextEdit.cpp b/src/Mod/Material/Gui/TextEdit.cpp index 95c1558855..aee64ea7b9 100644 --- a/src/Mod/Material/Gui/TextEdit.cpp +++ b/src/Mod/Material/Gui/TextEdit.cpp @@ -54,14 +54,14 @@ TextEdit::TextEdit(const QString& propertyName, _property = material->getAppearanceProperty(propertyName); } else { - Base::Console().Log("Property '%s' not found\n", propertyName.toStdString().c_str()); + Base::Console().log("Property '%s' not found\n", propertyName.toStdString().c_str()); _property = nullptr; } if (_property) { _value = _property->getString(); } else { - Base::Console().Log("No value loaded\n"); + Base::Console().log("No value loaded\n"); _value = QString(); } diff --git a/src/Mod/Material/materialtests/TestMaterialCreation.py b/src/Mod/Material/materialtests/TestMaterialCreation.py index 296f772f21..9febd43c94 100644 --- a/src/Mod/Material/materialtests/TestMaterialCreation.py +++ b/src/Mod/Material/materialtests/TestMaterialCreation.py @@ -130,6 +130,14 @@ class MaterialCreationTestCases(unittest.TestCase): self.assertTrue(material.hasPhysicalModel(self.uuids.Density)) # Quantity properties require units + with self.assertRaises(ValueError): + # Units of mass not density + material.setPhysicalValue("Density", "99.9 kg") + + material.setPhysicalValue("Density", "99.9") + self.assertEqual(material.getPhysicalValue("Density").Format["NumberFormat"], "g") + self.assertEqual(material.getPhysicalValue("Density").UserString, self.getQuantity("99.90 kg/m^3").UserString) + material.setPhysicalValue("Density", "99.9 kg/m^3") self.assertEqual(material.getPhysicalValue("Density").Format["NumberFormat"], "g") self.assertEqual(material.getPhysicalValue("Density").UserString, self.getQuantity("99.90 kg/m^3").UserString) diff --git a/src/Mod/Material/materialtests/TestMaterials.py b/src/Mod/Material/materialtests/TestMaterials.py index 66f6db0ed7..fb72bce1e6 100644 --- a/src/Mod/Material/materialtests/TestMaterials.py +++ b/src/Mod/Material/materialtests/TestMaterials.py @@ -27,6 +27,7 @@ Test module for FreeCAD material cards and APIs import unittest import FreeCAD import Materials +import sys parseQuantity = FreeCAD.Units.parseQuantity @@ -37,6 +38,15 @@ class MaterialTestCases(unittest.TestCase): def setUp(self): """ Setup function to initialize test data """ + # The test for ThermalExpansionCoefficient causes problems with some localizations + # due to the Unicode mu ('\u03bc') character in the units. This will happen with + # locales that don't support UTF8 such as zh_CN (It does support UTF-8) + try: + sys.stdout.reconfigure(errors='replace') + except: + # reconfigure appeared in 3.7, hope for the best... + pass + self.ModelManager = Materials.ModelManager() self.MaterialManager = Materials.MaterialManager() self.uuids = Materials.UUIDs() @@ -145,12 +155,6 @@ class MaterialTestCases(unittest.TestCase): self.assertIn("SpecularColor", properties) self.assertIn("Transparency", properties) - # - # The test for ThermalExpansionCoefficient causes problems with some localizations - # due to the Unicode mu character in the units. This will happen with - # locales that don't support UTF8 such as zh_CN (It does support UTF-8) - # - # When this is a problem simply comment the lines printing ThermalExpansionCoefficient print("Density " + properties["Density"]) # print("BulkModulus " + properties["BulkModulus"]) print("PoissonRatio " + properties["PoissonRatio"]) diff --git a/src/Mod/Measure/App/AppMeasure.cpp b/src/Mod/Measure/App/AppMeasure.cpp index b85061b240..881922f6c0 100644 --- a/src/Mod/Measure/App/AppMeasure.cpp +++ b/src/Mod/Measure/App/AppMeasure.cpp @@ -183,12 +183,12 @@ PyMOD_INIT_FUNC(Measure) } - Base::Console().Log("Loading Measure module... done\n"); + Base::Console().log("Loading Measure module... done\n"); PyMOD_Return(mod); } // debug print for sketchsolv void debugprint(const std::string& text) { - Base::Console().Log("%s", text.c_str()); + Base::Console().log("%s", text.c_str()); } diff --git a/src/Mod/Measure/App/AppMeasurePy.cpp b/src/Mod/Measure/App/AppMeasurePy.cpp index 292b5196dd..f960c40073 100644 --- a/src/Mod/Measure/App/AppMeasurePy.cpp +++ b/src/Mod/Measure/App/AppMeasurePy.cpp @@ -116,7 +116,7 @@ private: else { str += "No OCCT Exception Message"; } - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception& e) { @@ -124,7 +124,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception& e) { @@ -132,7 +132,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } diff --git a/src/Mod/Measure/App/MeasureBase.cpp b/src/Mod/Measure/App/MeasureBase.cpp index 3b6660ba62..10bfb64f55 100644 --- a/src/Mod/Measure/App/MeasureBase.cpp +++ b/src/Mod/Measure/App/MeasureBase.cpp @@ -81,7 +81,7 @@ std::vector MeasureBase::getSubject() const } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return {}; } @@ -116,7 +116,7 @@ void MeasureBase::parseSelection(const App::MeasureSelection& selection) } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } } @@ -136,7 +136,7 @@ std::vector MeasureBase::getInputProps() } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return {}; } Py::Sequence propsPy(ret); @@ -168,7 +168,7 @@ QString MeasureBase::getResultString() } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); return QString(); } return QString::fromStdString(ret.as_string()); diff --git a/src/Mod/Measure/App/MeasureBase.h b/src/Mod/Measure/App/MeasureBase.h index bcbdd122a7..c5e860b632 100644 --- a/src/Mod/Measure/App/MeasureBase.h +++ b/src/Mod/Measure/App/MeasureBase.h @@ -131,7 +131,7 @@ public: auto handler = getGeometryHandler(mod); if (!handler) { - Base::Console().Log("MeasureBaseExtendable::getMeasureInfo: No geometry handler " + Base::Console().log("MeasureBaseExtendable::getMeasureInfo: No geometry handler " "available for submitted element type"); return nullptr; } diff --git a/src/Mod/Measure/App/Measurement.cpp b/src/Mod/Measure/App/Measurement.cpp index 7965870851..661edd7ea0 100644 --- a/src/Mod/Measure/App/Measurement.cpp +++ b/src/Mod/Measure/App/Measurement.cpp @@ -292,10 +292,10 @@ double Measurement::length() const double result = 0.0; int numRefs = References3D.getSize(); if (numRefs == 0) { - Base::Console().Error("Measurement::length - No 3D references available\n"); + Base::Console().error("Measurement::length - No 3D references available\n"); } else if (measureType == MeasureType::Invalid) { - Base::Console().Error("Measurement::length - measureType is Invalid\n"); + Base::Console().error("Measurement::length - measureType is Invalid\n"); } else { const std::vector& objects = References3D.getValues(); @@ -406,7 +406,7 @@ double Measurement::lineLineDistance() const distance = perpendicularComponent.Magnitude(); } else { - Base::Console().Error("Measurement::length - TwoLines measureType requires two lines\n"); + Base::Console().error("Measurement::length - TwoLines measureType requires two lines\n"); } return distance; } @@ -528,7 +528,7 @@ double Measurement::radius() const int numRefs = References3D.getSize(); if (numRefs == 0) { - Base::Console().Error("Measurement::radius - No 3D references available\n"); + Base::Console().error("Measurement::radius - No 3D references available\n"); } else if (measureType == MeasureType::Circle) { TopoDS_Shape shape = getShape(objects.at(0), subElements.at(0).c_str()); @@ -555,7 +555,7 @@ double Measurement::radius() const return sf.Torus().MinorRadius(); } } - Base::Console().Error("Measurement::radius - Invalid References3D Provided\n"); + Base::Console().error("Measurement::radius - Invalid References3D Provided\n"); return 0.0; } @@ -564,10 +564,10 @@ Base::Vector3d Measurement::delta() const Base::Vector3d result; int numRefs = References3D.getSize(); if (numRefs == 0) { - Base::Console().Error("Measurement::delta - No 3D references available\n"); + Base::Console().error("Measurement::delta - No 3D references available\n"); } else if (measureType == MeasureType::Invalid) { - Base::Console().Error("Measurement::delta - measureType is Invalid\n"); + Base::Console().error("Measurement::delta - measureType is Invalid\n"); } else { const std::vector& objects = References3D.getValues(); @@ -646,7 +646,7 @@ Base::Vector3d Measurement::delta() const } } else { - Base::Console().Error("Measurement::delta - measureType is not recognized\n"); + Base::Console().error("Measurement::delta - measureType is not recognized\n"); } } return result; @@ -656,10 +656,10 @@ double Measurement::volume() const { double result = 0.0; if (References3D.getSize() == 0) { - Base::Console().Error("Measurement::volume - No 3D references available\n"); + Base::Console().error("Measurement::volume - No 3D references available\n"); } else if (measureType != MeasureType::Volumes) { - Base::Console().Error("Measurement::volume - measureType is not Volumes\n"); + Base::Console().error("Measurement::volume - measureType is not Volumes\n"); } else { const std::vector& objects = References3D.getValues(); @@ -678,7 +678,7 @@ double Measurement::area() const { double result = 0.0; if (References3D.getSize() == 0) { - Base::Console().Error("Measurement::area - No 3D references available\n"); + Base::Console().error("Measurement::area - No 3D references available\n"); } else if (measureType == MeasureType::Volumes || measureType == MeasureType::Surfaces || measureType == MeasureType::Cylinder || measureType == MeasureType::Cone @@ -695,7 +695,7 @@ double Measurement::area() const } } else { - Base::Console().Error("Measurement::area - measureType is not valid\n"); + Base::Console().error("Measurement::area - measureType is not valid\n"); } return result; } @@ -705,10 +705,10 @@ Base::Vector3d Measurement::massCenter() const Base::Vector3d result; int numRefs = References3D.getSize(); if (numRefs == 0) { - Base::Console().Error("Measurement::massCenter - No 3D references available\n"); + Base::Console().error("Measurement::massCenter - No 3D references available\n"); } else if (measureType == MeasureType::Invalid) { - Base::Console().Error("Measurement::massCenter - measureType is Invalid\n"); + Base::Console().error("Measurement::massCenter - measureType is Invalid\n"); } else { const std::vector& objects = References3D.getValues(); @@ -735,7 +735,7 @@ Base::Vector3d Measurement::massCenter() const return Base::Vector3d(cog.X(), cog.Y(), cog.Z()); } else { - Base::Console().Error("Measurement::massCenter - measureType is not recognized\n"); + Base::Console().error("Measurement::massCenter - measureType is not recognized\n"); } } return result; diff --git a/src/Mod/Measure/Gui/AppMeasureGui.cpp b/src/Mod/Measure/Gui/AppMeasureGui.cpp index af556fead8..2897c1591b 100644 --- a/src/Mod/Measure/Gui/AppMeasureGui.cpp +++ b/src/Mod/Measure/Gui/AppMeasureGui.cpp @@ -85,7 +85,7 @@ PyMOD_INIT_FUNC(MeasureGui) } PyObject* mod = MeasureGui::initModule(); - Base::Console().Log("Loading GUI of Measure module... done\n"); + Base::Console().log("Loading GUI of Measure module... done\n"); auto manip = std::make_shared(); Gui::WorkbenchManipulator::installManipulator(manip); diff --git a/src/Mod/Measure/Gui/QuickMeasure.cpp b/src/Mod/Measure/Gui/QuickMeasure.cpp index 21a918de14..6ad953db88 100644 --- a/src/Mod/Measure/Gui/QuickMeasure.cpp +++ b/src/Mod/Measure/Gui/QuickMeasure.cpp @@ -92,7 +92,7 @@ void QuickMeasure::processSelection() // sub-element e.g. when selecting a constraint in sketcher } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const Standard_Failure& e) { FC_ERR(e); diff --git a/src/Mod/Measure/Gui/TaskMeasure.cpp b/src/Mod/Measure/Gui/TaskMeasure.cpp index 9b2cc03b71..e9dccee5d4 100644 --- a/src/Mod/Measure/Gui/TaskMeasure.cpp +++ b/src/Mod/Measure/Gui/TaskMeasure.cpp @@ -255,7 +255,7 @@ void TaskMeasure::update() std::string mod = Base::Type::getModuleName(sub->getTypeId().getName()); if (!App::MeasureManager::hasMeasureHandler(mod.c_str())) { - Base::Console().Message("No measure handler available for geometry of module: %s\n", + Base::Console().message("No measure handler available for geometry of module: %s\n", mod); clearSelection(); return; diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp index 7609486af2..29d0e66b84 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp @@ -334,7 +334,7 @@ void ViewProviderMeasureAngle::redrawAnnotation() pcTransform->setMatrix(matrix); } catch (const Base::Exception& e) { - Base::Console().Error("Error in ViewProviderMeasureAngle::redrawAnnotation: %s\n", + Base::Console().error("Error in ViewProviderMeasureAngle::redrawAnnotation: %s\n", e.what()); return; } diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp index 4bc71cc99c..6b46ed20c6 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp @@ -380,7 +380,7 @@ void ViewProviderMeasureBase::updateData(const App::Property* prop) // TODO: should this be pure virtual? void ViewProviderMeasureBase::redrawAnnotation() { - // Base::Console().Message("VPMB::redrawAnnotation()\n"); + // Base::Console().message("VPMB::redrawAnnotation()\n"); } //! connect to the subject to receive visibility updates @@ -449,7 +449,7 @@ Base::Vector3d ViewProviderMeasureBase::getTextDirection(Base::Vector3d elementD view = dynamic_cast(this->getActiveView()); } catch (const Base::RuntimeError&) { - Base::Console().Log( + Base::Console().log( "ViewProviderMeasureBase::getTextDirection: Could not get active view\n"); } @@ -485,7 +485,7 @@ bool ViewProviderMeasureBase::isSubjectVisible() guiDoc = this->getDocument(); } catch (const Base::RuntimeError&) { - Base::Console().Log("ViewProviderMeasureBase::isSubjectVisible: Could not get document\n"); + Base::Console().log("ViewProviderMeasureBase::isSubjectVisible: Could not get document\n"); return false; } @@ -541,7 +541,7 @@ float ViewProviderMeasureBase::getViewScale() Gui::View3DInventor* view = dynamic_cast(this->getActiveView()); if (!view) { - Base::Console().Log("ViewProviderMeasureBase::getViewScale: Could not get active view\n"); + Base::Console().log("ViewProviderMeasureBase::getViewScale: Could not get active view\n"); return scale; } Gui::View3DInventorViewer* viewer = view->getViewer(); @@ -609,7 +609,7 @@ ViewProviderMeasure::ViewProviderMeasure() view = dynamic_cast(this->getActiveView()); } catch (const Base::RuntimeError&) { - Base::Console().Log( + Base::Console().log( "ViewProviderMeasure::ViewProviderMeasure: Could not get active view\n"); } @@ -641,7 +641,7 @@ void ViewProviderMeasure::positionAnno(const Measure::MeasureBase* measureObject view = dynamic_cast(this->getActiveView()); } catch (const Base::RuntimeError&) { - Base::Console().Log("ViewProviderMeasure::positionAnno: Could not get active view\n"); + Base::Console().log("ViewProviderMeasure::positionAnno: Could not get active view\n"); } if (!view) { @@ -697,7 +697,7 @@ Base::Vector3d ViewProviderMeasure::getTextPosition() Gui::View3DInventor* view = dynamic_cast(this->getActiveView()); if (!view) { - Base::Console().Log( + Base::Console().log( "ViewProviderMeasureBase::getTextPosition: Could not get active view\n"); return Base::Vector3d(); } diff --git a/src/Mod/Mesh/App/AppMesh.cpp b/src/Mod/Mesh/App/AppMesh.cpp index daca126ed5..795c3c2aab 100644 --- a/src/Mod/Mesh/App/AppMesh.cpp +++ b/src/Mod/Mesh/App/AppMesh.cpp @@ -54,7 +54,7 @@ extern PyObject* initModule(); PyMOD_INIT_FUNC(Mesh) { PyObject* meshModule = Mesh::initModule(); - Base::Console().Log("Loading Mesh module... done\n"); + Base::Console().log("Loading Mesh module... done\n"); // NOTE: To finish the initialization of our own type objects we must // call PyType_Ready, otherwise we run into a segmentation fault, later on. diff --git a/src/Mod/Mesh/App/Core/Algorithm.cpp b/src/Mod/Mesh/App/Core/Algorithm.cpp index 5ceb1d3e8b..57018986c1 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.cpp +++ b/src/Mod/Mesh/App/Core/Algorithm.cpp @@ -808,7 +808,7 @@ bool MeshAlgorithm::FillupHole(const std::vector& boundary, // in case the reference facet has not an open edge print a log message if (ref_side == max || tri_side == max) { - Base::Console().Log( + Base::Console().log( "MeshAlgorithm::FillupHole: Expected open edge for facet <%d, %d, %d>\n", rFace._aulPoints[0], rFace._aulPoints[1], diff --git a/src/Mod/Mesh/App/Core/Approximation.cpp b/src/Mod/Mesh/App/Core/Approximation.cpp index f0b8d2c25c..eb03190946 100644 --- a/src/Mod/Mesh/App/Core/Approximation.cpp +++ b/src/Mod/Mesh/App/Core/Approximation.cpp @@ -1186,7 +1186,7 @@ float CylinderFit::Fit() Base::Vector3d dir = cylFit.GetAxis(); #if defined(FC_DEBUG) - Base::Console().Log( + Base::Console().log( "MeshCoreFit::Cylinder Fit: Base: (%0.4f, %0.4f, %0.4f), Axis: (%0.6f, %0.6f, " "%0.6f), Radius: %0.4f, Std Dev: %0.4f, Iterations: %d\n", base.x, @@ -1238,7 +1238,7 @@ float CylinderFit::Fit() Eigen::LevenbergMarquardt lm(functor); int status = lm.minimize(x); - Base::Console().Log("Cylinder fit: %d, iterations: %d, gradient norm: %f\n", + Base::Console().log("Cylinder fit: %d, iterations: %d, gradient norm: %f\n", status, lm.iter, lm.gnorm); @@ -1421,7 +1421,7 @@ float SphereFit::Fit() _fLastResult = 0; #if defined(_DEBUG) - Base::Console().Message(" WildMagic Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " + Base::Console().message(" WildMagic Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " "%0.4f, Std Dev: %0.4f\n", _vCenter.x, _vCenter.y, @@ -1437,7 +1437,7 @@ float SphereFit::Fit() if (result < std::numeric_limits::max()) { Base::Vector3d center = sphereFit.GetCenter(); #if defined(_DEBUG) - Base::Console().Message("MeshCoreFit::Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " + Base::Console().message("MeshCoreFit::Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " "%0.4f, Std Dev: %0.4f, Iterations: %d\n", center.x, center.y, diff --git a/src/Mod/Mesh/App/Core/CylinderFit.cpp b/src/Mod/Mesh/App/Core/CylinderFit.cpp index 3cec8a71f5..9b940cb9dd 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.cpp +++ b/src/Mod/Mesh/App/Core/CylinderFit.cpp @@ -699,7 +699,7 @@ bool CylinderFit::computeResiduals(SolutionD solDir, } // rmsVv = sqrt(rmsVv / (double)nPtsUsed); - // Base::Console().Message("X: %0.3e %0.3e %0.3e %0.3e %0.3e , Max dV: %0.4f %0.4f %0.4f , RMS + // Base::Console().message("X: %0.3e %0.3e %0.3e %0.3e %0.3e , Max dV: %0.4f %0.4f %0.4f , RMS // Vv: %0.4f\n", x(0), x(1), x(2), x(3), x(4), maxdVx, maxdVy, maxdVz, rmsVv); return true; diff --git a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp index 6e0ed76831..e872ec73ee 100644 --- a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp +++ b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp @@ -83,7 +83,7 @@ bool WriterOBJ::Save(std::ostream& out) if (_material) { if (_material->binding == MeshIO::PER_FACE) { if (_material->diffuseColor.size() != rFacets.size()) { - Base::Console().Warning("Cannot export color information because there is a " + Base::Console().warning("Cannot export color information because there is a " "different number of faces and colors"); } else { @@ -92,7 +92,7 @@ bool WriterOBJ::Save(std::ostream& out) } else if (_material->binding == MeshIO::PER_VERTEX) { if (_material->diffuseColor.size() != rPoints.size()) { - Base::Console().Warning("Cannot export color information because there is a " + Base::Console().warning("Cannot export color information because there is a " "different number of points and colors"); } else { @@ -101,7 +101,7 @@ bool WriterOBJ::Save(std::ostream& out) } else if (_material->binding == MeshIO::OVERALL) { if (_material->diffuseColor.empty()) { - Base::Console().Warning( + Base::Console().warning( "Cannot export color information because there is no color defined"); } else { diff --git a/src/Mod/Mesh/App/Core/MeshIO.cpp b/src/Mod/Mesh/App/Core/MeshIO.cpp index 096ccc0f14..d1e5fdad74 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.cpp +++ b/src/Mod/Mesh/App/Core/MeshIO.cpp @@ -246,7 +246,7 @@ bool MeshInput::LoadAny(const char* FileName) else if (fi.hasExtension("iv")) { ok = LoadInventor(str); if (ok && _rclMesh.CountFacets() == 0) { - Base::Console().Warning("No usable mesh found in file '%s'", FileName); + Base::Console().warning("No usable mesh found in file '%s'", FileName); } } else if (fi.hasExtension({"nas", "bdf"})) { @@ -1151,14 +1151,14 @@ bool MeshInput::LoadNastran(std::istream& input) } if (badElementCounter > 0) { - Base::Console().Warning("Found bad elements while reading NASTRAN file.\n"); + Base::Console().warning("Found bad elements while reading NASTRAN file.\n"); } // Check the triangles to make sure the vertices they refer to actually exist: for (const auto& tri : mTria) { for (int i : tri.second.iV) { if (mNode.find(i) == mNode.end()) { - Base::Console().Error( + Base::Console().error( "CTRIA3 element refers to a node that does not exist, or could not be read.\n"); return false; } @@ -1169,7 +1169,7 @@ bool MeshInput::LoadNastran(std::istream& input) for (const auto& quad : mQuad) { for (int i : quad.second.iV) { if (mNode.find(i) == mNode.end()) { - Base::Console().Error( + Base::Console().error( "CQUAD4 element refers to a node that does not exist, or could not be read.\n"); return false; } @@ -1869,12 +1869,12 @@ bool MeshOutput::SaveOFF(std::ostream& out) const bool exportColor = false; if (_material) { if (_material->binding == MeshIO::PER_FACE) { - Base::Console().Warning( + Base::Console().warning( "Cannot export color information because it's defined per face"); } else if (_material->binding == MeshIO::PER_VERTEX) { if (_material->diffuseColor.size() != rPoints.size()) { - Base::Console().Warning("Cannot export color information because there is a " + Base::Console().warning("Cannot export color information because there is a " "different number of points and colors"); } else { @@ -1883,7 +1883,7 @@ bool MeshOutput::SaveOFF(std::ostream& out) const } else if (_material->binding == MeshIO::OVERALL) { if (_material->diffuseColor.empty()) { - Base::Console().Warning( + Base::Console().warning( "Cannot export color information because there is no color defined"); } else { diff --git a/src/Mod/Mesh/App/Core/SphereFit.cpp b/src/Mod/Mesh/App/Core/SphereFit.cpp index 91ae259706..02a42fd409 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.cpp +++ b/src/Mod/Mesh/App/Core/SphereFit.cpp @@ -440,7 +440,7 @@ bool SphereFit::computeResiduals(const Eigen::VectorXd& x, } // rmsVv = sqrt(rmsVv / (double)nPtsUsed); - // Base::Console().Message("X: %0.3e %0.3e %0.3e %0.3e , Max dV: %0.4f %0.4f %0.4f , RMS Vv: + // Base::Console().message("X: %0.3e %0.3e %0.3e %0.3e , Max dV: %0.4f %0.4f %0.4f , RMS Vv: // %0.4f\n", x(0), x(1), x(2), x(3), maxdVx, maxdVy, maxdVz, rmsVv); return true; diff --git a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp index 9d7960f847..3273fb9385 100644 --- a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp +++ b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp @@ -1729,7 +1729,7 @@ void MeshTopoAlgorithm::FillupHoles(int level, for (auto& newFacet : newFacets) { if (newFacet._aulPoints[0] >= ctPoints || newFacet._aulPoints[1] >= ctPoints || newFacet._aulPoints[2] >= ctPoints) { - Base::Console().Log("Ignore invalid face <%d, %d, %d> (%d vertices)\n", + Base::Console().log("Ignore invalid face <%d, %d, %d> (%d vertices)\n", newFacet._aulPoints[0], newFacet._aulPoints[1], newFacet._aulPoints[2], diff --git a/src/Mod/Mesh/App/Core/Triangulation.cpp b/src/Mod/Mesh/App/Core/Triangulation.cpp index 710f64df8f..98dbcc91d4 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.cpp +++ b/src/Mod/Mesh/App/Core/Triangulation.cpp @@ -237,7 +237,7 @@ bool AbstractPolygonTriangulator::TriangulatePolygon() { try { if (!this->_indices.empty() && this->_points.size() != this->_indices.size()) { - Base::Console().Log("Triangulation: %d points <> %d indices\n", + Base::Console().log("Triangulation: %d points <> %d indices\n", _points.size(), _indices.size()); return false; @@ -249,11 +249,11 @@ bool AbstractPolygonTriangulator::TriangulatePolygon() return ok; } catch (const Base::Exception& e) { - Base::Console().Log("Triangulation: %s\n", e.what()); + Base::Console().log("Triangulation: %s\n", e.what()); return false; } catch (const std::exception& e) { - Base::Console().Log("Triangulation: %s\n", e.what()); + Base::Console().log("Triangulation: %s\n", e.what()); return false; } catch (...) { diff --git a/src/Mod/Mesh/App/Mesh.cpp b/src/Mod/Mesh/App/Mesh.cpp index 42d551e589..125df12d97 100644 --- a/src/Mod/Mesh/App/Mesh.cpp +++ b/src/Mod/Mesh/App/Mesh.cpp @@ -526,19 +526,19 @@ void MeshObject::load(std::istream& in) try { MeshCore::MeshEvalNeighbourhood nb(_kernel); if (!nb.Evaluate()) { - Base::Console().Warning("Errors in neighbourhood of mesh found..."); + Base::Console().warning("Errors in neighbourhood of mesh found..."); _kernel.RebuildNeighbours(); - Base::Console().Warning("fixed\n"); + Base::Console().warning("fixed\n"); } MeshCore::MeshEvalTopology eval(_kernel); if (!eval.Evaluate()) { - Base::Console().Warning("The mesh data structure has some defects\n"); + Base::Console().warning("The mesh data structure has some defects\n"); } } catch (const Base::MemoryException&) { // ignore memory exceptions and continue - Base::Console().Log("Check for defects in mesh data structure failed\n"); + Base::Console().log("Check for defects in mesh data structure failed\n"); } #endif } diff --git a/src/Mod/Mesh/Gui/AppMeshGui.cpp b/src/Mod/Mesh/Gui/AppMeshGui.cpp index efdc2467a8..a5fb88d494 100644 --- a/src/Mod/Mesh/Gui/AppMeshGui.cpp +++ b/src/Mod/Mesh/Gui/AppMeshGui.cpp @@ -135,7 +135,7 @@ PyMOD_INIT_FUNC(MeshGui) PyMOD_Return(nullptr); } PyObject* mod = MeshGui::initModule(); - Base::Console().Log("Loading GUI of Mesh module... done\n"); + Base::Console().log("Loading GUI of Mesh module... done\n"); // instantiating the commands CreateMeshCommands(); @@ -149,7 +149,7 @@ PyMOD_INIT_FUNC(MeshGui) Base::Interpreter().runString("import MeshFlatteningCommand"); } catch (Base::PyException& err) { - err.ReportException(); + err.reportException(); } // register preferences pages diff --git a/src/Mod/Mesh/Gui/Command.cpp b/src/Mod/Mesh/Gui/Command.cpp index cfbc9d9842..6f6212780e 100644 --- a/src/Mod/Mesh/Gui/Command.cpp +++ b/src/Mod/Mesh/Gui/Command.cpp @@ -1447,7 +1447,7 @@ void CmdMeshBoundingBox::activated(int) const MeshCore::MeshKernel& rMesh = ((Mesh::Feature*)it)->Mesh.getValue().getKernel(); const Base::BoundBox3f& box = rMesh.GetBoundBox(); - Base::Console().Message("Boundings: Min=<%f,%f,%f>, Max=<%f,%f,%f>\n", + Base::Console().message("Boundings: Min=<%f,%f,%f>, Max=<%f,%f,%f>\n", box.MinX, box.MinY, box.MinZ, diff --git a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp index c26f66c7cd..6ed255f1aa 100644 --- a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp +++ b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp @@ -1017,7 +1017,7 @@ void DlgEvaluateMeshImp::onAnalyzeSelfIntersectionButtonClicked() eval.GetIntersections(intersection); } catch (const Base::AbortException&) { - Base::Console().Message("The self-intersection analysis was aborted by the user\n"); + Base::Console().message("The self-intersection analysis was aborted by the user\n"); } if (intersection.empty()) { diff --git a/src/Mod/Mesh/Gui/MeshSelection.cpp b/src/Mod/Mesh/Gui/MeshSelection.cpp index 728a3a978c..d63cf2f398 100644 --- a/src/Mod/Mesh/Gui/MeshSelection.cpp +++ b/src/Mod/Mesh/Gui/MeshSelection.cpp @@ -555,7 +555,7 @@ void MeshSelection::pickFaceCallback(void* ud, SoEventCallback* n) && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = n->getPickedPoint(); if (!point) { - Base::Console().Message("No facet picked.\n"); + Base::Console().message("No facet picked.\n"); return; } diff --git a/src/Mod/Mesh/Gui/RemeshGmsh.cpp b/src/Mod/Mesh/Gui/RemeshGmsh.cpp index f6aa7f480b..08a050a8f5 100644 --- a/src/Mod/Mesh/Gui/RemeshGmsh.cpp +++ b/src/Mod/Mesh/Gui/RemeshGmsh.cpp @@ -174,7 +174,7 @@ double GmshWidget::getMinSize() const void GmshWidget::accept() { if (d->gmsh.state() == QProcess::Running) { - Base::Console().Warning("Cannot start gmsh because it's already running\n"); + Base::Console().warning("Cannot start gmsh because it's already running\n"); return; } diff --git a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp index 3b413e0228..5bb5cea1e4 100644 --- a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp +++ b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp @@ -87,7 +87,7 @@ public: fit.SetInitialValues(base, axis); #if defined(FC_DEBUG) - Base::Console().Message("Initial axis: (%f, %f, %f)\n", axis.x, axis.y, axis.z); + Base::Console().message("Initial axis: (%f, %f, %f)\n", axis.x, axis.y, axis.z); #endif } diff --git a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp index 2304b30633..268e40fde5 100644 --- a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp +++ b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp @@ -1157,7 +1157,7 @@ void SoFCMeshObjectShape::generatePrimitives(SoAction* action) } } catch (const Base::MemoryException&) { - Base::Console().Log("Not enough memory to generate primitives\n"); + Base::Console().log("Not enough memory to generate primitives\n"); } endShape(); @@ -1582,7 +1582,7 @@ void SoFCMeshSegmentShape::generatePrimitives(SoAction* action) } } catch (const Base::MemoryException&) { - Base::Console().Log("Not enough memory to generate primitives\n"); + Base::Console().log("Not enough memory to generate primitives\n"); } endShape(); diff --git a/src/Mod/Mesh/Gui/ViewProvider.cpp b/src/Mod/Mesh/Gui/ViewProvider.cpp index 338b060dd4..c3e535c9c9 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.cpp +++ b/src/Mod/Mesh/Gui/ViewProvider.cpp @@ -1159,7 +1159,7 @@ void ViewProviderMesh::partMeshCallback(void* ud, SoEventCallback* cb) // create a tool shape from these points std::vector aFaces; if (!ViewProviderMesh::createToolMesh(clPoly, vol, cNormal, aFaces)) { - Base::Console().Message("The picked polygon seems to have self-overlappings. This could " + Base::Console().message("The picked polygon seems to have self-overlappings. This could " "lead to strange results."); } @@ -1232,7 +1232,7 @@ void ViewProviderMesh::segmMeshCallback(void* ud, SoEventCallback* cb) // create a tool shape from these points std::vector aFaces; if (!ViewProviderMesh::createToolMesh(clPoly, vol, cNormal, aFaces)) { - Base::Console().Message("The picked polygon seems to have self-overlappings. This could " + Base::Console().message("The picked polygon seems to have self-overlappings. This could " "lead to strange results."); } @@ -1366,7 +1366,7 @@ void ViewProviderMesh::getFacetsFromPolygon(const std::vector& picked, } if (!ok) { // note: the mouse grabbing needs to be released - Base::Console().Message("The picked polygon seems to have self-overlappings. This could " + Base::Console().message("The picked polygon seems to have self-overlappings. This could " "lead to strange results."); } } @@ -1701,7 +1701,7 @@ void ViewProviderMesh::faceInfoCallback(void* ud, SoEventCallback* cb) && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = cb->getPickedPoint(); if (!point) { - Base::Console().Message("No facet picked.\n"); + Base::Console().message("No facet picked.\n"); return; } @@ -1784,7 +1784,7 @@ void ViewProviderMesh::fillHoleCallback(void* ud, SoEventCallback* cb) && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = cb->getPickedPoint(); if (!point) { - Base::Console().Message("No facet picked.\n"); + Base::Console().message("No facet picked.\n"); return; } @@ -1859,7 +1859,7 @@ void ViewProviderMesh::markPartCallback(void* ud, SoEventCallback* cb) && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = cb->getPickedPoint(); if (!point) { - Base::Console().Message("No facet picked.\n"); + Base::Console().message("No facet picked.\n"); return; } @@ -1888,7 +1888,7 @@ void ViewProviderMesh::faceInfo(Mesh::FacetIndex uFacet) if (uFacet < facets.size()) { MeshCore::MeshFacet face = facets[uFacet]; MeshCore::MeshGeomFacet tria = rKernel.GetFacet(face); - Base::Console().Message( + Base::Console().message( "Mesh: %s Facet %lu: Points: <%lu, %lu, %lu>, Neighbours: <%lu, %lu, %lu>\n" "Triangle: <[%.6f, %.6f, %.6f], [%.6f, %.6f, %.6f], [%.6f, %.6f, %.6f]>\n", getObject()->getNameInDocument(), diff --git a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp index 04d6c59718..8067a19e1e 100644 --- a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp @@ -133,13 +133,13 @@ ViewProviderMeshCurvature::~ViewProviderMeshCurvature() deleteColorBar(); } catch (Base::Exception& e) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderMeshCurvature", "ViewProviderMeshCurvature::deleteColorBar() threw an exception: %s\n", e.what()); } catch (...) { - Base::Console().DestructorError( + Base::Console().destructorError( "ViewProviderInspection", "ViewProviderInspection destructor threw an unknown exception"); } @@ -554,7 +554,7 @@ void ViewProviderMeshCurvature::curvatureInfoCallback(void* ud, SoEventCallback* && mbe->getState() == SoButtonEvent::UP) { const SoPickedPoint* point = n->getPickedPoint(); if (!point) { - Base::Console().Message("No facet picked.\n"); + Base::Console().message("No facet picked.\n"); return; } diff --git a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp index 0f5feef8b2..c1d4b778ac 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp @@ -170,7 +170,7 @@ void ViewProviderMeshTransformDemolding::DragEndCallback() SbRotation rot = pcTrackballDragger->rotation.getValue(); calcMaterialIndex(rot); - Base::Console().Log("View: Finish dragging\n"); + Base::Console().log("View: Finish dragging\n"); } void ViewProviderMeshTransformDemolding::valueChangedCallback() diff --git a/src/Mod/MeshPart/App/AppMeshPart.cpp b/src/Mod/MeshPart/App/AppMeshPart.cpp index 3d3b79d306..4c1ea6598e 100644 --- a/src/Mod/MeshPart/App/AppMeshPart.cpp +++ b/src/Mod/MeshPart/App/AppMeshPart.cpp @@ -44,6 +44,6 @@ PyMOD_INIT_FUNC(MeshPart) PyMOD_Return(nullptr); } PyObject* mod = MeshPart::initModule(); - Base::Console().Log("Loading MeshPart module... done\n"); + Base::Console().log("Loading MeshPart module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/MeshPart/App/AppMeshPartPy.cpp b/src/Mod/MeshPart/App/AppMeshPartPy.cpp index 5b62b4216e..56a0bf897d 100644 --- a/src/Mod/MeshPart/App/AppMeshPartPy.cpp +++ b/src/Mod/MeshPart/App/AppMeshPartPy.cpp @@ -155,7 +155,7 @@ private: str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Base::PyExc_FC_GeneralError, str); } catch (const Base::Exception &e) { @@ -163,7 +163,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { @@ -171,7 +171,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } diff --git a/src/Mod/MeshPart/App/CurveProjector.cpp b/src/Mod/MeshPart/App/CurveProjector.cpp index 866d239a10..62c6acae4c 100644 --- a/src/Mod/MeshPart/App/CurveProjector.cpp +++ b/src/Mod/MeshPart/App/CurveProjector.cpp @@ -197,7 +197,7 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, } else if (Alg.NbPoints() > 1) { PointOnEdge[i] = Base::Vector3f(std::numeric_limits::max(), 0, 0); - Base::Console().Log("MeshAlgos::projectCurve(): More then one intersection in " + Base::Console().log("MeshAlgos::projectCurve(): More then one intersection in " "Facet %lu, Edge %d\n", uCurFacetIdx, i); @@ -218,7 +218,7 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, GoOn = true; } else { - Base::Console().Log("MeshAlgos::projectCurve(): Possible reentry in Facet %lu\n", + Base::Console().log("MeshAlgos::projectCurve(): Possible reentry in Facet %lu\n", uCurFacetIdx); } @@ -340,7 +340,7 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, FaceProjctMap[It.Position()].push_back(TempResultPoint); str << TempResultPoint.x << " " << TempResultPoint.y << " " << TempResultPoint.z << std::endl; - Base::Console().Log("IDX %d\n", It.Position()); + Base::Console().log("IDX %d\n", It.Position()); if (bFirst) { bFirst = false; @@ -352,7 +352,7 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, } str.close(); - Base::Console().Log("Projection map [%d facets with %d points]\n", + Base::Console().log("Projection map [%d facets with %d points]\n", FaceProjctMap.size(), PointCount); } @@ -460,7 +460,7 @@ void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, LineSegs.push_back(s); } - Base::Console().Log("Projection map [%d facets with %d points]\n", + Base::Console().log("Projection map [%d facets with %d points]\n", FaceProjctMap.size(), PointCount); @@ -989,7 +989,7 @@ void MeshProjection::projectEdgeToEdge(const TopoDS_Edge& aEdge, rParamSplitEdges[fSol] = splitEdge; } else if (nCntSol > 1) { - Base::Console().Log("More than one possible intersection points\n"); + Base::Console().log("More than one possible intersection points\n"); } } } diff --git a/src/Mod/MeshPart/App/Mesher.cpp b/src/Mod/MeshPart/App/Mesher.cpp index 0ba26fe51e..eb1603a299 100644 --- a/src/Mod/MeshPart/App/Mesher.cpp +++ b/src/Mod/MeshPart/App/Mesher.cpp @@ -112,7 +112,7 @@ int MeshingOutput::sync() else { sub = buffer; } - Base::Console().Error("%s", sub.c_str()); + Base::Console().error("%s", sub.c_str()); } buffer.clear(); } @@ -570,7 +570,7 @@ Mesh::MeshObject* Mesher::createFrom(SMESH_Mesh* mesh) const faces.push_back(f6); } else { - Base::Console().Warning("Face with %d nodes ignored\n", aFace->NbNodes()); + Base::Console().warning("Face with %d nodes ignored\n", aFace->NbNodes()); } } diff --git a/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp b/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp index f71dc60387..827ed1cec1 100644 --- a/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp +++ b/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp @@ -74,7 +74,7 @@ PyMOD_INIT_FUNC(MeshPartGui) } PyObject* mod = MeshPartGui::initModule(); - Base::Console().Log("Loading GUI of MeshPart module... done\n"); + Base::Console().log("Loading GUI of MeshPart module... done\n"); // clang-format off // instantiating the commands diff --git a/src/Mod/MeshPart/Gui/Tessellation.cpp b/src/Mod/MeshPart/Gui/Tessellation.cpp index 2031453a8d..675dd06f87 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.cpp +++ b/src/Mod/MeshPart/Gui/Tessellation.cpp @@ -347,7 +347,7 @@ void Tessellation::process(int method, } catch (const Base::Exception& e) { doc->abortTransaction(); - Base::Console().Error(e.what()); + Base::Console().error(e.what()); } } diff --git a/src/Mod/Part/App/AppPart.cpp b/src/Mod/Part/App/AppPart.cpp index 7668f6d9dd..b66e3c60ca 100644 --- a/src/Mod/Part/App/AppPart.cpp +++ b/src/Mod/Part/App/AppPart.cpp @@ -217,7 +217,7 @@ PyMOD_INIT_FUNC(Part) PyErr_SetString(PyExc_ImportError, e.what()); PyMOD_Return(nullptr); } - Base::Console().Log("Module: Part\n"); + Base::Console().log("Module: Part\n"); // This is highly experimental and we should keep an eye on it // if we have mysterious crashes @@ -229,7 +229,7 @@ PyMOD_INIT_FUNC(Part) #endif PyObject* partModule = Part::initModule(); - Base::Console().Log("Loading Part module... done\n"); + Base::Console().log("Loading Part module... done\n"); Py::Object module(partModule); module.setAttr("OCC_VERSION", Py::String(OCC_VERSION_STRING_EXT)); @@ -246,7 +246,7 @@ PyMOD_INIT_FUNC(Part) OCCError = PyErr_NewException("Part.OCCError", Base::PyExc_FC_GeneralError, nullptr); } else { - Base::Console().Error("Can not inherit Part.OCCError form BaseFreeCADError.\n"); + Base::Console().error("Can not inherit Part.OCCError form BaseFreeCADError.\n"); OCCError = PyErr_NewException("Part.OCCError", PyExc_RuntimeError, nullptr); } Py_INCREF(OCCError); @@ -575,7 +575,7 @@ PyMOD_INIT_FUNC(Part) Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean"); - + Part::FuzzyHelper::setBooleanFuzzy(hGrp->GetFloat("BooleanFuzzy",10.0)); Base::registerServiceImplementation(new AttacherSubObjectPlacement); diff --git a/src/Mod/Part/App/AppPartPy.cpp b/src/Mod/Part/App/AppPartPy.cpp index b6734ca17b..665c797c26 100644 --- a/src/Mod/Part/App/AppPartPy.cpp +++ b/src/Mod/Part/App/AppPartPy.cpp @@ -658,7 +658,7 @@ private: str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception &e) { @@ -666,7 +666,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { @@ -674,7 +674,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } @@ -691,7 +691,7 @@ private: str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception &e) { @@ -699,7 +699,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { @@ -707,7 +707,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } @@ -762,7 +762,7 @@ private: std::string EncodedName = std::string(Name); PyMem_Free(Name); - //Base::Console().Log("Insert in Part with %s",Name); + //Base::Console().log("Insert in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract ending @@ -821,7 +821,7 @@ private: builder.Add(comp, shape); } else { - Base::Console().Message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue()); + Base::Console().message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue()); } } } diff --git a/src/Mod/Part/App/AttachEnginePyImp.cpp b/src/Mod/Part/App/AttachEnginePyImp.cpp index 7955a5fbd6..761f3877ab 100644 --- a/src/Mod/Part/App/AttachEnginePyImp.cpp +++ b/src/Mod/Part/App/AttachEnginePyImp.cpp @@ -301,16 +301,16 @@ PyObject* AttachEnginePy::getModeInfo(PyObject* args) } catch (Py::Exception& e) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { // the GUI is not up. - Base::Console().Warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); + Base::Console().warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); e.clear(); } else { - Base::Console().Warning("AttachEngine.getModeInfo: error obtaining GUI strings\n"); + Base::Console().warning("AttachEngine.getModeInfo: error obtaining GUI strings\n"); e.clear(); } } catch (Base::Exception &e){ - Base::Console().Warning("AttachEngine.getModeInfo: error obtaining GUI strings:"); - Base::Console().Warning(e.what()); - Base::Console().Warning("\n"); + Base::Console().warning("AttachEngine.getModeInfo: error obtaining GUI strings:"); + Base::Console().warning(e.what()); + Base::Console().warning("\n"); } return Py::new_reference_to(ret); @@ -384,16 +384,16 @@ PyObject* AttachEnginePy::getRefTypeInfo(PyObject* args) } catch (Py::Exception& e) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { // the GUI is not up. - Base::Console().Warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); + Base::Console().warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); e.clear(); } else { - Base::Console().Warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings\n"); + Base::Console().warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings\n"); e.clear(); } } catch (Base::Exception &e){ - Base::Console().Warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings:"); - Base::Console().Warning(e.what()); - Base::Console().Warning("\n"); + Base::Console().warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings:"); + Base::Console().warning(e.what()); + Base::Console().warning("\n"); } return Py::new_reference_to(ret); diff --git a/src/Mod/Part/App/AttachExtension.cpp b/src/Mod/Part/App/AttachExtension.cpp index 493a3b13ea..e3ede2e495 100644 --- a/src/Mod/Part/App/AttachExtension.cpp +++ b/src/Mod/Part/App/AttachExtension.cpp @@ -414,12 +414,12 @@ void AttachExtension::extensionOnChanged(const App::Property* prop) } catch (Base::Exception &e) { getExtendedObject()->setStatus(App::Error, true); - Base::Console().Error("PositionBySupport: %s\n",e.what()); + Base::Console().error("PositionBySupport: %s\n",e.what()); //set error message - how? } catch (Standard_Failure &e){ getExtendedObject()->setStatus(App::Error, true); - Base::Console().Error("PositionBySupport: %s\n",e.GetMessageString()); + Base::Console().error("PositionBySupport: %s\n",e.GetMessageString()); } updateSinglePropertyStatus(bAttached); diff --git a/src/Mod/Part/App/Attacher.cpp b/src/Mod/Part/App/Attacher.cpp index 2107d02fed..31492009e5 100644 --- a/src/Mod/Part/App/Attacher.cpp +++ b/src/Mod/Part/App/Attacher.cpp @@ -1315,7 +1315,7 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector 1) { - Base::Console().Warning("AttachEngineLine::calculateAttachedPlacement: " + Base::Console().warning("AttachEngineLine::calculateAttachedPlacement: " "proximity calculation gave %i solutions, ambiguous.\n", int(distancer.NbSolution())); } @@ -2751,7 +2751,7 @@ gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& } if (points.size() > 1) - Base::Console().Warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %d solutions, ambiguous.\n", int(points.size())); + Base::Console().warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %d solutions, ambiguous.\n", int(points.size())); // if an intersection is found return the first hit // otherwise continue with BRepExtrema_DistShapeShape @@ -2767,7 +2767,7 @@ gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& if (!distancer.IsDone()) throw Base::ValueError("AttachEnginePoint::calculateAttachedPlacement: proximity calculation failed."); if (distancer.NbSolution() > 1) - Base::Console().Warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %i solutions, ambiguous.\n",int(distancer.NbSolution())); + Base::Console().warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %i solutions, ambiguous.\n",int(distancer.NbSolution())); gp_Pnt p1 = distancer.PointOnShape1(1); gp_Pnt p2 = distancer.PointOnShape2(1); diff --git a/src/Mod/Part/App/BSplineSurfacePyImp.cpp b/src/Mod/Part/App/BSplineSurfacePyImp.cpp index a7f24ec97e..12aa95d8dd 100644 --- a/src/Mod/Part/App/BSplineSurfacePyImp.cpp +++ b/src/Mod/Part/App/BSplineSurfacePyImp.cpp @@ -1183,7 +1183,7 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) Standard_Integer lv = col.size(); TColgp_Array2OfPnt interpolationPoints(1, lu, 1, lv); TColStd_Array2OfReal zPoints(1, lu, 1, lv); - //Base::Console().Message("lu=%d, lv=%d\n", lu, lv); + //Base::Console().message("lu=%d, lv=%d\n", lu, lv); Standard_Integer index1 = 0; Standard_Integer index2 = 0; diff --git a/src/Mod/Part/App/ExtrusionHelper.cpp b/src/Mod/Part/App/ExtrusionHelper.cpp index aabafa7141..d09a40c3da 100644 --- a/src/Mod/Part/App/ExtrusionHelper.cpp +++ b/src/Mod/Part/App/ExtrusionHelper.cpp @@ -382,7 +382,7 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D isInnerWire[0] = false; checklist[0] = false; --numCheckWires; - Base::Console().Warning("Extrusion: could not determine what structure is the outer one.\n\ + Base::Console().warning("Extrusion: could not determine what structure is the outer one.\n\ The first input one will now be taken as outer one.\n"); } @@ -399,7 +399,7 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D } ++i; } - Base::Console().Warning("Extrusion: too many self-intersection structures!\n\ + Base::Console().warning("Extrusion: too many self-intersection structures!\n\ Impossible to determine what structure is an inner one.\n\ All undeterminable structures will therefore be taken as outer ones.\n"); } @@ -450,10 +450,10 @@ void ExtrusionHelper::createTaperedPrismOffset(TopoDS_Wire sourceWire, } if (offsetShape.IsNull()) { if (isSecond) - Base::Console().Error("Extrusion: end face of tapered against extrusion is empty\n" \ + Base::Console().error("Extrusion: end face of tapered against extrusion is empty\n" \ "This means most probably that the against taper angle is too large or small.\n"); else - Base::Console().Error("Extrusion: end face of tapered along extrusion is empty\n" \ + Base::Console().error("Extrusion: end face of tapered along extrusion is empty\n" \ "This means most probably that the along taper angle is too large or small.\n"); Standard_Failure::Raise("Extrusion: end face of tapered extrusion is empty"); } @@ -472,10 +472,10 @@ void ExtrusionHelper::createTaperedPrismOffset(TopoDS_Wire sourceWire, // FIXME: Standard_Failure::Raise or App::DocumentObjectExecReturn don't output the message to the user result = TopoDS_Wire(); if (isSecond) - Base::Console().Error("Extrusion: type of against extrusion end face is not supported.\n" \ + Base::Console().error("Extrusion: type of against extrusion end face is not supported.\n" \ "This means most probably that the against taper angle is too large or small.\n"); else - Base::Console().Error("Extrusion: type of along extrusion is not supported.\n" \ + Base::Console().error("Extrusion: type of along extrusion is not supported.\n" \ "This means most probably that the along taper angle is too large or small.\n"); } diff --git a/src/Mod/Part/App/FT2FC.cpp b/src/Mod/Part/App/FT2FC.cpp index 76ca6959cf..54024bb5f0 100644 --- a/src/Mod/Part/App/FT2FC.cpp +++ b/src/Mod/Part/App/FT2FC.cpp @@ -190,7 +190,7 @@ PyObject* FT2FC(const Py_UCS4 *PyUString, } catch (Py::Exception& e) { e.clear(); - Base::Console().Log("FT2FC char '0x%04x'/'%d' has no Wires!\n", currchar, currchar); + Base::Console().log("FT2FC char '0x%04x'/'%d' has no Wires!\n", currchar, currchar); } PenPos += cadv; @@ -270,7 +270,7 @@ static int quad_cb(const FT_Vector* pt0, const FT_Vector* pt1, void* p) { ShapeConstruct_Curve scc; Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); if (spline.IsNull()) { - Base::Console().Message("Conversion to B-spline failed"); + Base::Console().message("Conversion to B-spline failed"); } TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); dc->Edges.push_back(edge); @@ -299,7 +299,7 @@ static int cubic_cb(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* ShapeConstruct_Curve scc; Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); if (spline.IsNull()) { - Base::Console().Message("Conversion to B-spline failed"); + Base::Console().message("Conversion to B-spline failed"); } TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); dc->Edges.push_back(edge); @@ -374,7 +374,7 @@ PyObject* getGlyphContours(FT_Face FTFace, FT_ULong currchar, double PenPos, dou (*iWire).Orientation(TopAbs_REVERSED); } else { //this is likely a poorly constructed font (ex a ttf with outer wires ACW ) - Base::Console().Message("FT2FC::getGlyphContours - indeterminate wire direction\n"); + Base::Console().message("FT2FC::getGlyphContours - indeterminate wire direction\n"); } BRepScale.Perform(*iWire,bCopy); @@ -416,7 +416,7 @@ TopoDS_Wire edgesToWire(std::vector Edges) { for (iEdge = Edges.begin(); iEdge != Edges.end(); ++iEdge){ mkWire.Add(*iEdge); if (!mkWire.IsDone()) { - Base::Console().Message("FT2FC Trace edgesToWire failed to add wire\n"); + Base::Console().message("FT2FC Trace edgesToWire failed to add wire\n"); } } occwire = mkWire.Wire(); diff --git a/src/Mod/Part/App/FeaturePartCurveNet.cpp b/src/Mod/Part/App/FeaturePartCurveNet.cpp index aafcf457ae..245ea2036b 100644 --- a/src/Mod/Part/App/FeaturePartCurveNet.cpp +++ b/src/Mod/Part/App/FeaturePartCurveNet.cpp @@ -47,7 +47,7 @@ App::DocumentObjectExecReturn *CurveNet::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().Log("CurveNet::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("CurveNet::execute() not able to open %s!\n",FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } diff --git a/src/Mod/Part/App/FeaturePartImportBrep.cpp b/src/Mod/Part/App/FeaturePartImportBrep.cpp index 81c09ef1c2..068761986b 100644 --- a/src/Mod/Part/App/FeaturePartImportBrep.cpp +++ b/src/Mod/Part/App/FeaturePartImportBrep.cpp @@ -52,7 +52,7 @@ App::DocumentObjectExecReturn *ImportBrep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().Log("ImportBrep::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportBrep::execute() not able to open %s!\n",FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } diff --git a/src/Mod/Part/App/FeaturePartImportIges.cpp b/src/Mod/Part/App/FeaturePartImportIges.cpp index cc28d598a8..2ffe9d400d 100644 --- a/src/Mod/Part/App/FeaturePartImportIges.cpp +++ b/src/Mod/Part/App/FeaturePartImportIges.cpp @@ -52,7 +52,7 @@ App::DocumentObjectExecReturn *ImportIges::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().Log("ImportIges::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportIges::execute() not able to open %s!\n",FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } diff --git a/src/Mod/Part/App/FeaturePartImportStep.cpp b/src/Mod/Part/App/FeaturePartImportStep.cpp index 435722b7cd..4cf53c3d70 100644 --- a/src/Mod/Part/App/FeaturePartImportStep.cpp +++ b/src/Mod/Part/App/FeaturePartImportStep.cpp @@ -52,7 +52,7 @@ App::DocumentObjectExecReturn *ImportStep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().Log("ImportStep::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportStep::execute() not able to open %s!\n",FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } diff --git a/src/Mod/Part/App/FeatureScale.cpp b/src/Mod/Part/App/FeatureScale.cpp index 8e30efc9a5..d2173a36dc 100644 --- a/src/Mod/Part/App/FeatureScale.cpp +++ b/src/Mod/Part/App/FeatureScale.cpp @@ -88,7 +88,7 @@ TopoShape Scale::scaleShape(const TopoShape& source, const Scale::ScaleParameter TopoShape Scale::uniformScale(const TopoShape& source, const double& factor) { -// Base::Console().Message("FS::uniformScale()\n"); +// Base::Console().message("FS::uniformScale()\n"); TopoDS_Shape transShape; TopoShape transTopo; try { @@ -107,7 +107,7 @@ TopoShape Scale::uniformScale(const TopoShape& source, const double& factor) TopoShape Scale::nonuniformScale(const TopoShape& source, const Scale::ScaleParameters& params) { -// Base::Console().Message("FS::nonuniformScale()\n"); +// Base::Console().message("FS::nonuniformScale()\n"); Base::Matrix4D matScale; matScale.scale(params.XScale, params.YScale, params.ZScale); @@ -136,7 +136,7 @@ TopoShape Scale::nonuniformScale(const TopoShape& source, const Scale::ScalePara transTopo.setShape(mkTrf.Shape()); } catch (...) { - Base::Console().Warning("FeatureScale failed on nonuniform scale\n"); + Base::Console().warning("FeatureScale failed on nonuniform scale\n"); return transTopo; } return transTopo; @@ -144,7 +144,7 @@ TopoShape Scale::nonuniformScale(const TopoShape& source, const Scale::ScalePara App::DocumentObjectExecReturn* Scale::execute() { -// Base::Console().Message("FS::execute()\n"); +// Base::Console().message("FS::execute()\n"); App::DocumentObject* link = Base.getValue(); if (!link) return new App::DocumentObjectExecReturn("No object linked"); diff --git a/src/Mod/Part/App/Geometry.cpp b/src/Mod/Part/App/Geometry.cpp index e88424e7f8..a77cf165a2 100644 --- a/src/Mod/Part/App/Geometry.cpp +++ b/src/Mod/Part/App/Geometry.cpp @@ -326,7 +326,7 @@ void Geometry::Restore(Base::XMLReader &reader) extensions.push_back(std::shared_ptr(newExtension)); } else { - Base::Console().Warning("Cannot restore geometry extension of type: %s\n", TypeName); + Base::Console().warning("Cannot restore geometry extension of type: %s\n", TypeName); } } @@ -6338,7 +6338,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the parameter of the first selected curve at the reference " "point.") @@ -6350,7 +6350,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the parameter of the second selected curve at the " "reference point.") @@ -6423,7 +6423,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWMT(Base::CADKernelError, QT_TRANSLATE_NOOP("Exceptions", "Unable to guess intersection of curves. Try adding " @@ -6449,7 +6449,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the parameter of the first selected curve at the " "intersection of the curves.") @@ -6461,7 +6461,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the parameter of the second selected curve at the " "intersection of the curves.") @@ -6549,7 +6549,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to find intersection between offset curves.") } @@ -6568,7 +6568,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the starting point of the arc.") } @@ -6578,7 +6578,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); THROWM(Base::CADKernelError, "Unable to determine the end point of the arc.") } diff --git a/src/Mod/Part/App/ImportStep.cpp b/src/Mod/Part/App/ImportStep.cpp index f040919d91..6790536171 100644 --- a/src/Mod/Part/App/ImportStep.cpp +++ b/src/Mod/Part/App/ImportStep.cpp @@ -84,7 +84,7 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) // Root transfers Standard_Integer nbr = aReader.NbRootsForTransfer(); for (Standard_Integer n = 1; n<= nbr; n++) { - Base::Console().Log("STEP: Transferring Root %d\n",n); + Base::Console().log("STEP: Transferring Root %d\n",n); aReader.TransferRoot(n); } @@ -98,7 +98,7 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) std::map hash_col; for (Standard_Integer i=1; i<=nbs; i++) { - Base::Console().Log("STEP: Transferring Shape %d\n",i); + Base::Console().log("STEP: Transferring Shape %d\n",i); aShape = aReader.Shape(i); // load each solid as an own object diff --git a/src/Mod/Part/App/MeasureClient.cpp b/src/Mod/Part/App/MeasureClient.cpp index 3e2e9ded86..35230ee242 100644 --- a/src/Mod/Part/App/MeasureClient.cpp +++ b/src/Mod/Part/App/MeasureClient.cpp @@ -100,7 +100,7 @@ TopoDS_Shape getLocatedShape(const App::SubObjectT& subject, Base::Matrix4D* mat Part::TopoShape shape = Part::Feature::getTopoShape(obj, subject.getElementName(), false, mat, nullptr, true); if (shape.isNull()) { - Base::Console().Log("Part::MeasureClient::getLocatedShape: Did not retrieve shape for %s, %s\n", obj->getNameInDocument(), subject.getElementName()); + Base::Console().log("Part::MeasureClient::getLocatedShape: Did not retrieve shape for %s, %s\n", obj->getNameInDocument(), subject.getElementName()); return {}; } @@ -124,7 +124,7 @@ App::MeasureElementType PartMeasureTypeCb(App::DocumentObject* ob, const char* s TopoDS_Shape shape = Part::Feature::getShape(ob, subName, true); if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("Part::PartMeasureTypeCb did not retrieve shape for %s, %s\n", ob->getNameInDocument(), subName); + Base::Console().message("Part::PartMeasureTypeCb did not retrieve shape for %s, %s\n", ob->getNameInDocument(), subName); return App::MeasureElementType(); } TopAbs_ShapeEnum shapeType = shape.ShapeType(); @@ -188,7 +188,7 @@ Part::VectorAdapter buildAdapter(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("Part::buildAdapter did not retrieve shape for %s, %s\n", + Base::Console().message("Part::buildAdapter did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return Part::VectorAdapter(); } @@ -240,7 +240,7 @@ MeasureLengthInfoPtr MeasureLengthHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("MeasureLengthHandler did not retrieve shape for %s, %s\n", + Base::Console().message("MeasureLengthHandler did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return std::make_shared(false, 0.0, Base::Matrix4D()); } @@ -301,7 +301,7 @@ MeasureAreaInfoPtr MeasureAreaHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("MeasureAreaHandler did not retrieve shape for %s, %s\n", + Base::Console().message("MeasureAreaHandler did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return std::make_shared(false, 0.0, Base::Matrix4D()); } @@ -328,7 +328,7 @@ MeasurePositionInfoPtr MeasurePositionHandler(const App::SubObjectT& subject) TopoDS_Shape shape = getLocatedShape(subject); if (shape.IsNull()) { - Base::Console().Message("MeasurePositionHandler did not retrieve shape for %s, %s\n", + Base::Console().message("MeasurePositionHandler did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return std::make_shared(false, Base::Vector3d()); } @@ -350,7 +350,7 @@ MeasureAngleInfoPtr MeasureAngleHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("MeasureAngleHandler did not retrieve shape for %s, %s\n", + Base::Console().message("MeasureAngleHandler did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return std::make_shared(); } @@ -389,7 +389,7 @@ MeasureDistanceInfoPtr MeasureDistanceHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().Message("MeasureDistanceHandler did not retrieve shape for %s, %s\n", + Base::Console().message("MeasureDistanceHandler did not retrieve shape for %s, %s\n", subject.getObjectName(), subject.getElementName()); return std::make_shared(); } diff --git a/src/Mod/Part/App/PartFeature.cpp b/src/Mod/Part/App/PartFeature.cpp index 82fa1e94fc..35150b3d02 100644 --- a/src/Mod/Part/App/PartFeature.cpp +++ b/src/Mod/Part/App/PartFeature.cpp @@ -877,7 +877,7 @@ void Feature::setMaterialAppearance(const App::Material& material) ShapeMaterial.setValue(material); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Mod/Part/App/PropertyGeometryList.cpp b/src/Mod/Part/App/PropertyGeometryList.cpp index 76515145e9..1fc142923c 100644 --- a/src/Mod/Part/App/PropertyGeometryList.cpp +++ b/src/Mod/Part/App/PropertyGeometryList.cpp @@ -197,7 +197,7 @@ void PropertyGeometryList::trySaveGeometry(Geometry * geom, Base::Writer &writer } } catch (const Base::NotImplementedError& e) { - Base::Console().Warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); + Base::Console().warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); } } @@ -219,7 +219,7 @@ void PropertyGeometryList::tryRestoreGeometry(Geometry * geom, Base::XMLReader & geom->Restore(reader); } catch (const Base::NotImplementedError& e) { - Base::Console().Warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); + Base::Console().warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); } } @@ -263,7 +263,7 @@ void PropertyGeometryList::Restore(Base::XMLReader &reader) tryRestoreGeometry(newG, reader); if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().Error("Geometry \"%s\" within a PropertyGeometryList was subject to a partial restore.\n",reader.localName()); + Base::Console().error("Geometry \"%s\" within a PropertyGeometryList was subject to a partial restore.\n",reader.localName()); if(isOrderRelevant()) { // Pushes the best try by the Geometry class values.push_back(newG); diff --git a/src/Mod/Part/App/PropertyTopoShape.cpp b/src/Mod/Part/App/PropertyTopoShape.cpp index cf7dc91951..ba4a0a7b68 100644 --- a/src/Mod/Part/App/PropertyTopoShape.cpp +++ b/src/Mod/Part/App/PropertyTopoShape.cpp @@ -481,11 +481,11 @@ void PropertyPartShape::saveToFile(Base::Writer &writer) const App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().Error("Shape of '%s' cannot be written to BRep file '%s'\n", + Base::Console().error("Shape of '%s' cannot be written to BRep file '%s'\n", obj->Label.getValue(),fi.filePath().c_str()); } else { - Base::Console().Error("Cannot save BRep file '%s'\n", fi.filePath().c_str()); + Base::Console().error("Cannot save BRep file '%s'\n", fi.filePath().c_str()); } std::stringstream ss; @@ -533,11 +533,11 @@ void PropertyPartShape::loadFromFile(Base::Reader &reader) App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().Error("BRep file '%s' with shape of '%s' seems to be empty\n", + Base::Console().error("BRep file '%s' with shape of '%s' seems to be empty\n", fi.filePath().c_str(),obj->Label.getValue()); } else { - Base::Console().Warning("Loaded BRep file '%s' seems to be empty\n", fi.filePath().c_str()); + Base::Console().warning("Loaded BRep file '%s' seems to be empty\n", fi.filePath().c_str()); } } } @@ -558,7 +558,7 @@ void PropertyPartShape::loadFromStream(Base::Reader &reader) } catch (const std::exception&) { if (!reader.eof()) - Base::Console().Warning("Failed to load BRep file %s\n", reader.getFileName().c_str()); + Base::Console().warning("Failed to load BRep file %s\n", reader.getFileName().c_str()); } } diff --git a/src/Mod/Part/App/TopoShape.cpp b/src/Mod/Part/App/TopoShape.cpp index 951b6086dc..67735d914c 100644 --- a/src/Mod/Part/App/TopoShape.cpp +++ b/src/Mod/Part/App/TopoShape.cpp @@ -2417,7 +2417,7 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, - W1-W2-W3-V1 ==> W1-W2-W3-V1-W1 invalid closed - W1-W2-W3 ==> W1-W2-W3-W1 valid closed*/ if (profiles.Last().ShapeType() == TopAbs_VERTEX) { - Base::Console().Message("TopoShape::makeLoft: can't close Loft with Vertex as last profile. 'Closed' ignored.\n"); + Base::Console().message("TopoShape::makeLoft: can't close Loft with Vertex as last profile. 'Closed' ignored.\n"); } else { // repeat Add logic above for first profile @@ -2444,7 +2444,7 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, if (!aGenerator.IsDone()) Standard_Failure::Raise("Failed to create loft face"); - //Base::Console().Message("DEBUG: TopoShape::makeLoft returns.\n"); + //Base::Console().message("DEBUG: TopoShape::makeLoft returns.\n"); return aGenerator.Shape(); } @@ -2487,7 +2487,7 @@ TopoDS_Shape TopoShape::revolve(const gp_Ax1& axis, double d, Standard_Boolean i } if (convertFailed) { - Base::Console().Message("TopoShape::revolve could not make Solid from Wire/Edge.\n");} + Base::Console().message("TopoShape::revolve could not make Solid from Wire/Edge.\n");} BRepPrimAPI_MakeRevol mkRevol(base, axis,d); return mkRevol.Shape(); @@ -4088,7 +4088,7 @@ bool TopoShape::_makeTransform(const TopoShape &shape, } } catch (const Standard_Failure& e) { - Base::Console().Warning("TopoShape::makeGTransform failed: %s\n", e.GetMessageString()); + Base::Console().warning("TopoShape::makeGTransform failed: %s\n", e.GetMessageString()); } } makeTransform(shape,convert(rclTrf),op,copy); diff --git a/src/Mod/Part/App/TopoShapeCache.cpp b/src/Mod/Part/App/TopoShapeCache.cpp index ec82c84c02..5db0698191 100644 --- a/src/Mod/Part/App/TopoShapeCache.cpp +++ b/src/Mod/Part/App/TopoShapeCache.cpp @@ -151,6 +151,10 @@ int TopoShapeCache::Ancestry::count() const return shapes.Extent(); } +bool TopoShapeCache::Ancestry::empty() const +{ + return shapes.IsEmpty(); +} TopoShapeCache::TopoShapeCache(const TopoDS_Shape& tds) : shape(tds.Located(TopLoc_Location())) diff --git a/src/Mod/Part/App/TopoShapeCache.h b/src/Mod/Part/App/TopoShapeCache.h index 190bfe3b28..4113c2eabd 100644 --- a/src/Mod/Part/App/TopoShapeCache.h +++ b/src/Mod/Part/App/TopoShapeCache.h @@ -114,6 +114,7 @@ public: int find(const TopoDS_Shape& parent, const TopoDS_Shape& subShape); TopoDS_Shape find(const TopoDS_Shape& parent, int index); int count() const; + bool empty() const; friend TopoShapeCache; }; diff --git a/src/Mod/Part/App/TopoShapeExpansion.cpp b/src/Mod/Part/App/TopoShapeExpansion.cpp index 11cdc6e3c7..ea9babd627 100644 --- a/src/Mod/Part/App/TopoShapeExpansion.cpp +++ b/src/Mod/Part/App/TopoShapeExpansion.cpp @@ -860,7 +860,7 @@ void TopoShape::mapSubElementForShape(const TopoShape& other, const char* op) for (auto type : types) { auto& shapeMap = _cache->getAncestry(type); auto& otherMap = other._cache->getAncestry(type); - if ((shapeMap.count() == 0) || (otherMap.count() == 0)) { + if ((shapeMap.empty()) || (otherMap.empty())) { continue; } @@ -1450,7 +1450,7 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, continue; } auto& otherMap = incomingShape._cache->getAncestry(info.type); - if (otherMap.count() == 0) { + if (otherMap.empty()) { continue; } for (int i = 1; i <= otherMap.count(); i++) { @@ -4206,7 +4206,7 @@ TopoShape& TopoShape::makeElementLoft(const std::vector& shapes, - W1-W2-W3-V1 ==> W1-W2-W3-V1-W1 invalid closed - W1-W2-W3 ==> W1-W2-W3-W1 valid closed*/ if (profiles.back().getShape().ShapeType() == TopAbs_VERTEX) { - Base::Console().Message("TopoShape::makeLoft: can't close Loft with Vertex as last " + Base::Console().message("TopoShape::makeLoft: can't close Loft with Vertex as last " "profile. 'Closed' ignored.\n"); } else { diff --git a/src/Mod/Part/App/TopoShapePyImp.cpp b/src/Mod/Part/App/TopoShapePyImp.cpp index f3513be0e0..32ed00a274 100644 --- a/src/Mod/Part/App/TopoShapePyImp.cpp +++ b/src/Mod/Part/App/TopoShapePyImp.cpp @@ -2215,7 +2215,7 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const } break; default: - Base::Console().Message("distToShape: supportType1 is unknown: %d \n", + Base::Console().message("distToShape: supportType1 is unknown: %d \n", static_cast(supportType1)); suppType1 = Py::String("Unknown"); suppIndex1 = -1; @@ -2250,7 +2250,7 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const } break; default: - Base::Console().Message("distToShape: supportType2 is unknown: %d \n", + Base::Console().message("distToShape: supportType2 is unknown: %d \n", static_cast(supportType2)); suppType2 = Py::String("Unknown"); suppIndex2 = -1; diff --git a/src/Mod/Part/App/modelRefine.cpp b/src/Mod/Part/App/modelRefine.cpp index 0c6338f979..0a71cef4c5 100644 --- a/src/Mod/Part/App/modelRefine.cpp +++ b/src/Mod/Part/App/modelRefine.cpp @@ -944,13 +944,13 @@ bool FaceTypedBSpline::isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &fa stream << "FaceTypedBSpline::isEqual: OCC Error: " << e.GetMessageString() << std::endl; else stream << "FaceTypedBSpline::isEqual: Unknown OCC Error" << std::endl; - Base::Console().Message(stream.str().c_str()); + Base::Console().message(stream.str().c_str()); } catch (...) { std::ostringstream stream; stream << "FaceTypedBSpline::isEqual: Unknown Error" << std::endl; - Base::Console().Message(stream.str().c_str()); + Base::Console().message(stream.str().c_str()); } return false; diff --git a/src/Mod/Part/Gui/AppPartGui.cpp b/src/Mod/Part/Gui/AppPartGui.cpp index dbf14a999a..297b8e4c43 100644 --- a/src/Mod/Part/Gui/AppPartGui.cpp +++ b/src/Mod/Part/Gui/AppPartGui.cpp @@ -133,7 +133,7 @@ PyMOD_INIT_FUNC(PartGui) PyObject* partGuiModule = PartGui::initModule(); - Base::Console().Log("Loading GUI of Part module... done\n"); + Base::Console().log("Loading GUI of Part module... done\n"); Gui::BitmapFactory().addPath(QStringLiteral(":/icons/booleans")); Gui::BitmapFactory().addPath(QStringLiteral(":/icons/create")); @@ -236,7 +236,7 @@ PyMOD_INIT_FUNC(PartGui) Py::Module(partGuiModule).setAttr(std::string("AttachmentEditor"), ae); } catch (Base::PyException& err) { - err.ReportException(); + err.reportException(); } // register preferences pages diff --git a/src/Mod/Part/Gui/AttacherTexts.cpp b/src/Mod/Part/Gui/AttacherTexts.cpp index 58f329f3ca..ec188e8a39 100644 --- a/src/Mod/Part/Gui/AttacherTexts.cpp +++ b/src/Mod/Part/Gui/AttacherTexts.cpp @@ -311,7 +311,7 @@ TextSet getUIStrings(Base::Type attacherType, eMapMode mmode) } } - Base::Console().Warning("No user-friendly string defined for this attachment mode and attacher type: %s %s \n",AttachEngine::getModeName(mmode).c_str(), attacherType.getName()); + Base::Console().warning("No user-friendly string defined for this attachment mode and attacher type: %s %s \n",AttachEngine::getModeName(mmode).c_str(), attacherType.getName()); return TwoStrings(QString::fromStdString(AttachEngine::getModeName(mmode)), QString()); } diff --git a/src/Mod/Part/Gui/Command.cpp b/src/Mod/Part/Gui/Command.cpp index cf1ad10396..b86d5343ee 100644 --- a/src/Mod/Part/Gui/Command.cpp +++ b/src/Mod/Part/Gui/Command.cpp @@ -1107,7 +1107,7 @@ void CmdPartMakeSolid::activated(int iMsg) TopAbs_ShapeEnum type = shape.ShapeType(); QString str; if (type == TopAbs_SOLID) { - Base::Console().Message("%s is ignored because it is already a solid.\n", + Base::Console().message("%s is ignored because it is already a solid.\n", it->Label.getValue()); } else if (type == TopAbs_COMPOUND || type == TopAbs_COMPSOLID) { @@ -1135,7 +1135,7 @@ void CmdPartMakeSolid::activated(int iMsg) QLatin1String(it->Label.getValue())); } else { - Base::Console().Message("%s is ignored because it is neither a shell nor a compound.\n", + Base::Console().message("%s is ignored because it is neither a shell nor a compound.\n", it->Label.getValue()); } @@ -1144,7 +1144,7 @@ void CmdPartMakeSolid::activated(int iMsg) runCommand(Doc, str.toLatin1()); } catch (const Base::Exception& e) { - Base::Console().Error("Cannot convert %s because %s.\n", + Base::Console().error("Cannot convert %s because %s.\n", it->Label.getValue(), e.what()); } } @@ -1203,7 +1203,7 @@ void CmdPartReverseShape::activated(int iMsg) copyVisual(name.c_str(), "PointColor", it->getNameInDocument()); } catch (const Base::Exception& e) { - Base::Console().Error("Cannot convert %s because %s.\n", + Base::Console().error("Cannot convert %s because %s.\n", it->Label.getValue(), e.what()); } } diff --git a/src/Mod/Part/Gui/CommandSimple.cpp b/src/Mod/Part/Gui/CommandSimple.cpp index 21d4f1f58a..4e3fb0b11d 100644 --- a/src/Mod/Part/Gui/CommandSimple.cpp +++ b/src/Mod/Part/Gui/CommandSimple.cpp @@ -196,7 +196,7 @@ void CmdPartPointsFromMesh::activated(int iMsg) } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } commitCommand(); @@ -382,7 +382,7 @@ void CmdPartRefineShape::activated(int iMsg) Gui::copyVisualT(newObj->getNameInDocument(), "PointColor", obj->getNameInDocument()); } catch (const Base::Exception& e) { - Base::Console().Warning("%s: %s\n", obj->Label.getValue(), e.what()); + Base::Console().warning("%s: %s\n", obj->Label.getValue(), e.what()); } }); commitCommand(); @@ -452,7 +452,7 @@ void CmdPartDefeaturing::activated(int iMsg) it->getFeatName()); } catch (const Base::Exception& e) { - Base::Console().Warning("%s: %s\n", it->getFeatName(), e.what()); + Base::Console().warning("%s: %s\n", it->getFeatName(), e.what()); } } commitCommand(); diff --git a/src/Mod/Part/Gui/DlgBooleanOperation.cpp b/src/Mod/Part/Gui/DlgBooleanOperation.cpp index 7482638045..95b9b7f000 100644 --- a/src/Mod/Part/Gui/DlgBooleanOperation.cpp +++ b/src/Mod/Part/Gui/DlgBooleanOperation.cpp @@ -461,7 +461,7 @@ void DlgBooleanOperation::accept() activeDoc->recompute(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } diff --git a/src/Mod/Part/Gui/DlgExtrusion.cpp b/src/Mod/Part/Gui/DlgExtrusion.cpp index 76cbea4787..c7f0bbb621 100644 --- a/src/Mod/Part/Gui/DlgExtrusion.cpp +++ b/src/Mod/Part/Gui/DlgExtrusion.cpp @@ -227,7 +227,7 @@ void DlgExtrusion::onSelectEdgeClicked() QByteArray code_2 = code.arg(features_to_hide).toLatin1(); Base::Interpreter().runString(code_2.constData()); } catch (Base::PyException &e){ - e.ReportException(); + e.reportException(); } } else { Gui::Selection().rmvSelectionGate(); @@ -238,7 +238,7 @@ void DlgExtrusion::onSelectEdgeClicked() try{ Base::Interpreter().runString("del(tv)"); } catch (Base::PyException &e){ - e.ReportException(); + e.reportException(); } } } diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp index 7267f49703..93f34e6f79 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp @@ -162,13 +162,13 @@ DlgProjectionOnSurface::DlgProjectionOnSurface(QWidget* parent) m_partDocument = App::GetApplication().getActiveDocument(); if (!m_partDocument) { - throw Base::ValueError(QString(tr("Have no active document!!!")).toUtf8()); + throw Base::ValueError(tr("Have no active document!!!").toStdString()); } this->attachDocument(m_partDocument); m_partDocument->openTransaction("Project on surface"); m_projectionObject = m_partDocument->addObject("Projection Object"); if (!m_projectionObject) { - throw Base::ValueError(QString(tr("Can not create a projection object!!!")).toUtf8()); + throw Base::ValueError(tr("Can not create a projection object!!!").toStdString()); } m_projectionObject->Label.setValue(std::string(m_projectionObjectName.toUtf8()).c_str()); onRadioButtonShowAllClicked(); @@ -183,7 +183,7 @@ DlgProjectionOnSurface::~DlgProjectionOnSurface() higlight_object(it.partFeature, it.partName, false, 0); } catch (Standard_NoSuchObject& e) { - Base::Console().Warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", + Base::Console().warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", e.GetMessageString()); } auto vp = dynamic_cast( @@ -198,7 +198,7 @@ DlgProjectionOnSurface::~DlgProjectionOnSurface() higlight_object(it.partFeature, it.partName, false, 0); } catch (Standard_NoSuchObject& e) { - Base::Console().Warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", + Base::Console().warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", e.GetMessageString()); } } diff --git a/src/Mod/Part/Gui/DlgScale.cpp b/src/Mod/Part/Gui/DlgScale.cpp index e3c87aa6ff..1b4515284c 100644 --- a/src/Mod/Part/Gui/DlgScale.cpp +++ b/src/Mod/Part/Gui/DlgScale.cpp @@ -92,7 +92,7 @@ void DlgScale::changeEvent(QEvent *e) void DlgScale::onUniformScaleToggled(bool state) { -// Base::Console().Message("DS::onUniformScaleToggled()\n"); +// Base::Console().message("DS::onUniformScaleToggled()\n"); if (state) { // this is uniform scaling, so hide the non-uniform input fields ui->dsbUniformScale->setEnabled(true); @@ -112,7 +112,7 @@ void DlgScale::onUniformScaleToggled(bool state) //! list widget void DlgScale::findShapes() { -// Base::Console().Message("DS::findShapes()\n"); +// Base::Console().message("DS::findShapes()\n"); App::Document* activeDoc = App::GetApplication().getActiveDocument(); if (!activeDoc) return; @@ -179,19 +179,19 @@ bool DlgScale::canScale(const TopoDS_Shape& shape) const void DlgScale::accept() { -// Base::Console().Message("DS::accept()\n"); +// Base::Console().message("DS::accept()\n"); try{ apply(); QDialog::accept(); } catch (Base::AbortException&){ - Base::Console().Message("DS::accept - apply failed!\n"); + Base::Console().message("DS::accept - apply failed!\n"); }; } // create a FeatureScale for each scalable object void DlgScale::apply() { -// Base::Console().Message("DS::apply()\n"); +// Base::Console().message("DS::apply()\n"); try{ if (!validate()) { QMessageBox::critical(this, windowTitle(), @@ -271,7 +271,7 @@ void DlgScale::reject() //! widget std::vector DlgScale::getShapesToScale() const { -// Base::Console().Message("DS::getShapesToScale()\n"); +// Base::Console().message("DS::getShapesToScale()\n"); QList items = ui->treeWidget->selectedItems(); App::Document* doc = App::GetApplication().getDocument(m_document.c_str()); if (!doc) @@ -309,7 +309,7 @@ bool DlgScale::validate() //! update a FeatureScale with the parameters from the UI void DlgScale::writeParametersToFeature(App::DocumentObject &feature, App::DocumentObject* base) const { -// Base::Console().Message("DS::writeParametersToFeature()\n"); +// Base::Console().message("DS::writeParametersToFeature()\n"); Gui::Command::doCommand(Gui::Command::Doc,"f = App.getDocument('%s').getObject('%s')", feature.getDocument()->getName(), feature.getNameInDocument()); if (!base) { diff --git a/src/Mod/Part/Gui/SectionCutting.cpp b/src/Mod/Part/Gui/SectionCutting.cpp index b5febc76eb..b6e517a9ac 100644 --- a/src/Mod/Part/Gui/SectionCutting.cpp +++ b/src/Mod/Part/Gui/SectionCutting.cpp @@ -549,7 +549,7 @@ void SectionCut::deleteCompound() // check for BooleanFragments pcCompoundDelBF = Gui::Application::Instance->getViewProvider(compoundObject); if (!pcCompoundDelBF) { - Base::Console().Error( + Base::Console().error( "SectionCut error: compound is incorrectly named, cannot proceed\n"); return; } @@ -625,7 +625,7 @@ Part::Box* SectionCut::tryCreateXBox(const Base::Vector3f& pos, const Base::Vect return createXBox(pos, size); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); return nullptr; } } @@ -699,7 +699,7 @@ Part::Box* SectionCut::tryCreateYBox(const Base::Vector3f& pos, const Base::Vect return createYBox(pos, size); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); return nullptr; } } @@ -743,7 +743,7 @@ Part::Box* SectionCut::tryCreateZBox(const Base::Vector3f& pos, const Base::Vect return createZBox(pos, size); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); return nullptr; } } @@ -798,7 +798,7 @@ Part::Cut* SectionCut::tryCreateCut(const char* name) return createCut(name); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); return nullptr; } } @@ -829,7 +829,7 @@ void SectionCut::startCutting(bool isInitial) startObjectCutting(isInitial); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -1567,7 +1567,7 @@ void SectionCut::onCutXvalueChanged(double val) } auto pcBox = dynamic_cast(CutBox); if (!pcBox) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(BoxXName) + Base::Console().error((std::string("SectionCut error: ") + std::string(BoxXName) + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); return; } @@ -1644,7 +1644,7 @@ void SectionCut::onCutXvalueChanged(double val) // recompute the cut auto pcCut = dynamic_cast(CutObject); if (!pcCut) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(CutZName) + Base::Console().error((std::string("SectionCut error: ") + std::string(CutZName) + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); return; } @@ -1688,7 +1688,7 @@ void SectionCut::onCutYvalueChanged(double val) } auto pcBox = dynamic_cast(CutBox); if (!pcBox) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(BoxYName) + Base::Console().error((std::string("SectionCut error: ") + std::string(BoxYName) + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); return; } @@ -1710,7 +1710,7 @@ void SectionCut::onCutYvalueChanged(double val) if (hasBoxZ) { auto CutFeatureZ = findObject(CutZName); if (!CutFeatureZ) { - Base::Console().Error((std::string("SectionCut error: there is no ") + Base::Console().error((std::string("SectionCut error: there is no ") + std::string(CutZName) + std::string("\n")).c_str()); return; } @@ -1746,7 +1746,7 @@ void SectionCut::onCutYvalueChanged(double val) // recompute the cut auto pcCut = dynamic_cast(CutObject); if (!pcCut) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(CutZName) + Base::Console().error((std::string("SectionCut error: ") + std::string(CutZName) + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); return; } @@ -1810,7 +1810,7 @@ void SectionCut::onCutZvalueChanged(double val) } auto pcBox = dynamic_cast(CutBox); if (!pcBox) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(BoxZName) + Base::Console().error((std::string("SectionCut error: ") + std::string(BoxZName) + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); return; } @@ -1827,7 +1827,7 @@ void SectionCut::onCutZvalueChanged(double val) } auto pcCut = dynamic_cast(CutObject); if (!pcCut) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(CutZName) + Base::Console().error((std::string("SectionCut error: ") + std::string(CutZName) + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); return; } @@ -1916,7 +1916,7 @@ void SectionCut::FlipClickedHelper(const char* BoxName) } auto pcBox = dynamic_cast(CutBox); if (!pcBox) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(BoxName) + Base::Console().error((std::string("SectionCut error: ") + std::string(BoxName) + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); return; } @@ -2025,7 +2025,7 @@ App::DocumentObject* SectionCut::findOrCreateObject(const char* objName) { auto object = findObject(objName); if (!object) { - Base::Console().Warning((std::string("SectionCut warning: there is no ") + Base::Console().warning((std::string("SectionCut warning: there is no ") + std::string(objName) + std::string(", trying to recreate it\n")).c_str()); startCutting(); return nullptr; @@ -2144,7 +2144,7 @@ void SectionCut::setBooleanFragmentsColor() compoundObject = doc->getObject(CompoundName); } else { - Base::Console().Error("SectionCut error: compound is incorrectly named, cannot proceed\n"); + Base::Console().error("SectionCut error: compound is incorrectly named, cannot proceed\n"); return; } // assure it is not a Part::Compound @@ -2153,7 +2153,7 @@ void SectionCut::setBooleanFragmentsColor() // check for valid BooleanFragments by accessing its ViewProvider auto CompoundBFVP = Gui::Application::Instance->getViewProvider(compoundObject); if (!CompoundBFVP) { - Base::Console().Error("SectionCut error: cannot access ViewProvider of cut compound\n"); + Base::Console().error("SectionCut error: cannot access ViewProvider of cut compound\n"); return; } auto CutCompoundBFGeom = dynamic_cast(CompoundBFVP); @@ -2174,7 +2174,7 @@ void SectionCut::onBFragTransparencyHSMoved(int val) auto setTransparency = [&](App::DocumentObject* cutObject) { Gui::ViewProvider* CutVP = Gui::Application::Instance->getViewProvider(cutObject); if (!CutVP) { - Base::Console().Error( + Base::Console().error( "SectionCut error: cannot access ViewProvider of cut object\n"); return; } @@ -2227,14 +2227,14 @@ void SectionCut::onRefreshCutPBclicked() // get document auto docGui = Gui::Application::Instance->activeDocument(); if (!docGui) { - Base::Console().Error("SectionCut error: there is no document\n"); + Base::Console().error("SectionCut error: there is no document\n"); return; } doc = docGui->getDocument(); // get all objects in the document std::vector ObjectsList = doc->getObjects(); if (ObjectsList.empty()) { - Base::Console().Error("SectionCut error: there are no objects in the document\n"); + Base::Console().error("SectionCut error: there are no objects in the document\n"); return; } // empty the ObjectsListVisible @@ -2281,12 +2281,12 @@ SbBox3f SectionCut::getViewBoundingBox() SbBox3f Box; auto docGui = Gui::Application::Instance->activeDocument(); if (!docGui) { - Base::Console().Error("SectionCut error: there is no active document\n"); + Base::Console().error("SectionCut error: there is no active document\n"); return Box; // return an empty box } auto view = dynamic_cast(docGui->getActiveView()); if (!view) { - Base::Console().Error("SectionCut error: could not get the active view\n"); + Base::Console().error("SectionCut error: could not get the active view\n"); return Box; // return an empty box } Gui::View3DInventorViewer* viewer = view->getViewer(); @@ -2376,7 +2376,7 @@ App::DocumentObject* SectionCut::CreateBooleanFragments(App::Document* doc) // check for success App::DocumentObject* object = doc->getObject(CompoundName); if (!object) { - Base::Console().Error((std::string("SectionCut error: ") + std::string(CompoundName) + Base::Console().error((std::string("SectionCut error: ") + std::string(CompoundName) + std::string(" could not be added\n")).c_str()); return nullptr; } diff --git a/src/Mod/Part/Gui/ShapeFromMesh.cpp b/src/Mod/Part/Gui/ShapeFromMesh.cpp index db63862799..14af6e82ef 100644 --- a/src/Mod/Part/Gui/ShapeFromMesh.cpp +++ b/src/Mod/Part/Gui/ShapeFromMesh.cpp @@ -97,7 +97,7 @@ void ShapeFromMesh::accept() perform(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } QDialog::accept(); diff --git a/src/Mod/Part/Gui/TaskAttacher.cpp b/src/Mod/Part/Gui/TaskAttacher.cpp index c40a719547..74e8f7e484 100644 --- a/src/Mod/Part/Gui/TaskAttacher.cpp +++ b/src/Mod/Part/Gui/TaskAttacher.cpp @@ -72,7 +72,7 @@ const QString makeRefString(const App::DocumentObject* obj, const std::string& s return QString::fromLatin1(obj->getNameInDocument()); } - // Hide the TNP string from the user. ie show "Body.Pad.Face6" and not : + // Hide the TNP string from the user. ie show "Body.Pad.Face6" and not : // "Body.Pad.;#a:1;:G0;XTR;:Hc94:8,F.Face6" App::ElementNamePair el; App::GeoFeature::resolveElement(obj, sub.c_str(), el, true); @@ -419,7 +419,7 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO for (size_t i = 0; i < names.size(); ++i) { App::DocumentObject* obj = doc->getObject(names[i].c_str()); if (!obj) { - Base::Console().TranslatedUserError("TaskAttacher", + Base::Console().translatedUserError("TaskAttacher", "Unsuitable selection: '%s' cannot be attached to '%s' from within it's group '%s'.\n", attachingObj->getFullLabel(), subObj->getFullLabel(), group->getFullLabel()); rootObj = nullptr; @@ -441,7 +441,7 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO } // In case the attaching object is in a link to a part. - // For instance : + // For instance : // - Part1 // - - LinkToPart2 // - - - Cube @@ -454,7 +454,7 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO } // if we reach this point it means that attaching object's group is outside of - // the scope of the attached object. For instance: + // the scope of the attached object. For instance: // - Part1 // - - Part2 // - - - Cube @@ -952,7 +952,7 @@ void TaskAttacher::updateListOfModes() //first up, remember currently selected mode. eMapMode curMode = mmDeactivated; auto sel = ui->listOfModes->selectedItems(); - if (sel.count() > 0) + if (!sel.isEmpty()) curMode = modesInList[ui->listOfModes->row(sel[0])]; //obtain list of available modes: @@ -1054,7 +1054,7 @@ void TaskAttacher::selectMapMode(eMapMode mmode) { Attacher::eMapMode TaskAttacher::getActiveMapMode() { auto sel = ui->listOfModes->selectedItems(); - if (sel.count() > 0) + if (!sel.isEmpty()) return modesInList[ui->listOfModes->row(sel[0])]; else { if (this->lastSuggestResult.message == SuggestResult::srOK) @@ -1200,11 +1200,11 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) visAutoFunc(opening_not_closing, ObjectName, ViewProvider, editObj, editSubName); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); } } else { @@ -1214,7 +1214,7 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) visAutoFunc(opening_not_closing, objName, nullptr, nullptr, std::string()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } } @@ -1224,7 +1224,7 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgAttacher::TaskDlgAttacher(Gui::ViewProviderDocumentObject* ViewProvider, bool createBox, +TaskDlgAttacher::TaskDlgAttacher(Gui::ViewProviderDocumentObject* ViewProvider, bool createBox, std::function onAccept, std::function onReject) : TaskDialog(), ViewProvider(ViewProvider), parameter(nullptr), onAccept(onAccept), onReject(onReject), accepted(false) { diff --git a/src/Mod/Part/Gui/TaskCheckGeometry.cpp b/src/Mod/Part/Gui/TaskCheckGeometry.cpp index bc8fc68b96..5ce8629a82 100644 --- a/src/Mod/Part/Gui/TaskCheckGeometry.cpp +++ b/src/Mod/Part/Gui/TaskCheckGeometry.cpp @@ -385,7 +385,7 @@ TaskCheckGeometryResults::~TaskCheckGeometryResults() } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -546,7 +546,7 @@ void TaskCheckGeometryResults::goCheck() void TaskCheckGeometryResults::generateReport() { QString reportString = reportViewStrings.join(QLatin1String("\n")); - Base::Console().Message(reportString.toStdString().c_str()); + Base::Console().message(reportString.toStdString().c_str()); } @@ -677,7 +677,7 @@ void TaskCheckGeometryResults::buildShapeContent(App::DocumentObject *pObject, c } catch (Py::Exception&) { Base::PyException e; - e.ReportException(); + e.reportException(); stream << baseName.toLatin1().data() << std::endl; BRepTools_ShapeSet set; set.Add(shape); diff --git a/src/Mod/Part/Gui/TaskShapeBuilder.cpp b/src/Mod/Part/Gui/TaskShapeBuilder.cpp index 295764cfba..7b87f880e1 100644 --- a/src/Mod/Part/Gui/TaskShapeBuilder.cpp +++ b/src/Mod/Part/Gui/TaskShapeBuilder.cpp @@ -198,7 +198,7 @@ void ShapeBuilderWidget::onCreateButtonClicked() Gui::Selection().clearSelection(); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } diff --git a/src/Mod/Part/Gui/ViewProvider.cpp b/src/Mod/Part/Gui/ViewProvider.cpp index f0e34d685f..d15bdf649e 100644 --- a/src/Mod/Part/Gui/ViewProvider.cpp +++ b/src/Mod/Part/Gui/ViewProvider.cpp @@ -54,7 +54,7 @@ bool ViewProviderPart::doubleClicked() return true; } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); return false; } } diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.cpp b/src/Mod/Part/Gui/ViewProvider2DObject.cpp index c555600f69..c6645c2ae9 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.cpp +++ b/src/Mod/Part/Gui/ViewProvider2DObject.cpp @@ -172,7 +172,7 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid() int lines = vlines + hlines; if (lines > maxNumberOfLines.getValue()) { - Base::Console().Warning("Grid Disabled: Requested number of lines %d is larger than the maximum configured of %d\n." + Base::Console().warning("Grid Disabled: Requested number of lines %d is larger than the maximum configured of %d\n." "Either increase the 'GridSize' property to a more reasonable value (recommended) or increase the 'maxNumberOfLines' property.\n", lines, maxNumberOfLines.getValue()); parent->addChild(vts); parent->addChild(grid); diff --git a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp index c549610827..976b89fbfc 100644 --- a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp +++ b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp @@ -112,7 +112,7 @@ void ViewProviderCurveNet::updateData(const App::Property* prop) computeVertices(VertexRoot,cShape); } catch (...){ - Base::Console().Error("ViewProviderPart::create() Cannot compute Inventor representation for the actual shape"); + Base::Console().error("ViewProviderPart::create() Cannot compute Inventor representation for the actual shape"); } } } @@ -183,7 +183,7 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve switch (button) { case SoMouseButtonEvent::BUTTON1: if (press) { - Base::Console().Log("ViewProviderCurveNet::handleEvent() press left\n"); + Base::Console().log("ViewProviderCurveNet::handleEvent() press left\n"); bool bIsNode = false; for (const auto & It : NodeList) @@ -207,7 +207,7 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve else if(Viewer.pickPoint(pos,point,norm)) { Node n; - Base::Console().Log("Picked(%f,%f,%f)\n",point[0],point[1],point[2]); + Base::Console().log("Picked(%f,%f,%f)\n",point[0],point[1],point[2]); SoSeparator *TransRoot = new SoSeparator(); n.pcTransform = new SoTransform(); diff --git a/src/Mod/Part/Gui/ViewProviderExt.cpp b/src/Mod/Part/Gui/ViewProviderExt.cpp index 4f616fef91..9850151fea 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.cpp +++ b/src/Mod/Part/Gui/ViewProviderExt.cpp @@ -1312,8 +1312,8 @@ void ViewProviderPartExt::updateVisual() # ifdef FC_DEBUG // printing some information - Base::Console().Log("ViewProvider update time: %f s\n",Base::TimeElapsed::diffTimeF(start_time,Base::TimeElapsed())); - Base::Console().Log("Shape tria info: Faces:%d Edges:%d Nodes:%d Triangles:%d IdxVec:%d\n",numFaces,numEdges,numNodes,numTriangles,numLines); + Base::Console().log("ViewProvider update time: %f s\n",Base::TimeElapsed::diffTimeF(start_time,Base::TimeElapsed())); + Base::Console().log("Shape tria info: Faces:%d Edges:%d Nodes:%d Triangles:%d IdxVec:%d\n",numFaces,numEdges,numNodes,numTriangles,numLines); # else (void)numEdges; # endif diff --git a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp index 986de17151..878267ac66 100644 --- a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp @@ -167,7 +167,7 @@ void GridExtensionP::getClosestGridPoint(double &x, double &y) const closestdim(x, computedGridValue); closestdim(y, computedGridValue); - //Base::Console().Log("gridvalue=%f, (x,y)=(%f,%f)", computedGridValue, x, y); + //Base::Console().log("gridvalue=%f, (x,y)=(%f,%f)", computedGridValue, x, y); } bool GridExtensionP::checkCameraZoomChange(const Gui::View3DInventorViewer* viewer) @@ -300,7 +300,7 @@ void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool div if (nlines > 2000) { if(!isTooManySegmentsNotified) { - Base::Console().Warning("The grid is too dense, so it is being disabled. Consider zooming in or changing the grid configuration\n"); + Base::Console().warning("The grid is too dense, so it is being disabled. Consider zooming in or changing the grid configuration\n"); isTooManySegmentsNotified = true; } diff --git a/src/Mod/PartDesign/App/AppPartDesign.cpp b/src/Mod/PartDesign/App/AppPartDesign.cpp index 92f28e9fdf..56df444367 100644 --- a/src/Mod/PartDesign/App/AppPartDesign.cpp +++ b/src/Mod/PartDesign/App/AppPartDesign.cpp @@ -78,7 +78,7 @@ PyMOD_INIT_FUNC(_PartDesign) } PyObject* mod = PartDesign::initModule(); - Base::Console().Log("Loading PartDesign module... done\n"); + Base::Console().log("Loading PartDesign module... done\n"); // NOTE: To finish the initialization of our own type objects we must diff --git a/src/Mod/PartDesign/App/Body.cpp b/src/Mod/PartDesign/App/Body.cpp index 7d3c6cf5aa..53c3e90f55 100644 --- a/src/Mod/PartDesign/App/Body.cpp +++ b/src/Mod/PartDesign/App/Body.cpp @@ -378,19 +378,19 @@ App::DocumentObjectExecReturn *Body::execute() { Part::BodyBase::execute(); /* - Base::Console().Error("Body '%s':\n", getNameInDocument()); + Base::Console().error("Body '%s':\n", getNameInDocument()); App::DocumentObject* tip = Tip.getValue(); - Base::Console().Error(" Tip: %s\n", (tip == NULL) ? "None" : tip->getNameInDocument()); + Base::Console().error(" Tip: %s\n", (tip == NULL) ? "None" : tip->getNameInDocument()); std::vector model = Group.getValues(); - Base::Console().Error(" Group:\n"); + Base::Console().error(" Group:\n"); for (std::vector::const_iterator m = model.begin(); m != model.end(); m++) { if (*m == NULL) continue; - Base::Console().Error(" %s", (*m)->getNameInDocument()); + Base::Console().error(" %s", (*m)->getNameInDocument()); if (Body::isSolidFeature(*m)) { App::DocumentObject* baseFeature = static_cast(*m)->BaseFeature.getValue(); - Base::Console().Error(", Base: %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); + Base::Console().error(", Base: %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); } else { - Base::Console().Error("\n"); + Base::Console().error("\n"); } } */ diff --git a/src/Mod/PartDesign/App/Feature.cpp b/src/Mod/PartDesign/App/Feature.cpp index b519137eda..62283ed5bd 100644 --- a/src/Mod/PartDesign/App/Feature.cpp +++ b/src/Mod/PartDesign/App/Feature.cpp @@ -94,7 +94,7 @@ App::DocumentObjectExecReturn* Feature::recompute() } catch (Base::Exception& e) { failed = true; - e.ReportException(); + e.reportException(); FC_ERR("Failed to recompute suppressed feature " << getFullName()); } diff --git a/src/Mod/PartDesign/App/FeatureDraft.cpp b/src/Mod/PartDesign/App/FeatureDraft.cpp index d317b77863..6c826ab963 100644 --- a/src/Mod/PartDesign/App/FeatureDraft.cpp +++ b/src/Mod/PartDesign/App/FeatureDraft.cpp @@ -301,7 +301,7 @@ App::DocumentObjectExecReturn *Draft::execute() // therefore unusable. See https://forum.freecad.org/viewtopic.php?f=10&t=3209&start=10#p25341 // The only solution is to discard mkDraft and start over without the current face // mkDraft.Remove(face); - Base::Console().Error("Adding face failed on %s. Omitted\n", it->c_str()); + Base::Console().error("Adding face failed on %s. Omitted\n", it->c_str()); success = false; SubVals.erase(it); break; diff --git a/src/Mod/PartDesign/App/FeatureHole.cpp b/src/Mod/PartDesign/App/FeatureHole.cpp index a68da0fec8..50dc45d5ea 100644 --- a/src/Mod/PartDesign/App/FeatureHole.cpp +++ b/src/Mod/PartDesign/App/FeatureHole.cpp @@ -1379,31 +1379,40 @@ double Hole::getThreadProfileAngle() void Hole::findClosestDesignation() { - // Intended for thread type changes - // finds the closest diameter of the new thread type int threadType = ThreadType.getValue(); - if (threadType == -1) { + const int numTypes = static_cast(std::size(threadDescription)); + + if (threadType < 0 || threadType >= numTypes) { throw Base::IndexError(QT_TRANSLATE_NOOP("Exception", "Thread type is invalid")); } - int closestSize = 0; - double diameter = ThreadDiameter.getValue(); - if (diameter == 0) - diameter = Diameter.getValue(); - double closestDifference = std::numeric_limits::infinity(); - double difference; - for (size_t i = 0; i < threadDescription[threadType].size(); i++) { - difference = threadDescription[threadType][i].diameter - diameter; - if (difference == 0) { - closestSize = i; - break; - } - if (std::abs(difference) < closestDifference) { - closestSize = i; - closestDifference = std::abs(difference); + double diameter = ThreadDiameter.getValue(); + if (diameter == 0.0) { + diameter = Diameter.getValue(); + } + + int oldSizeIndex = ThreadSize.getValue(); + const auto &options = threadDescription[threadType]; + double targetPitch = 0.0; + if (oldSizeIndex >= 0 && oldSizeIndex < static_cast(options.size())) { + targetPitch = options[oldSizeIndex].pitch; + } + + // Scan all entries to find the minimal (Δdiameter, Δpitch) Euclidean distance + size_t bestIndex = 0; + double bestMetric = std::numeric_limits::infinity(); + + for (size_t i = 0; i < options.size(); ++i) { + double dDiff = options[i].diameter - diameter; + double pDiff = options[i].pitch - targetPitch; + double metric = std::hypot(dDiff, pDiff); + if (metric < bestMetric) { + bestMetric = metric; + bestIndex = i; } } - ThreadSize.setValue(closestSize); + + ThreadSize.setValue(static_cast(bestIndex)); } void Hole::onChanged(const App::Property* prop) @@ -1818,8 +1827,8 @@ static gp_Pnt toPnt(gp_Vec dir) } App::DocumentObjectExecReturn* Hole::execute() -{ - TopoShape profileshape = getProfileShape(/*needSubElement*/ false); +{ + TopoShape profileshape = getProfileShape(); // Find the base shape TopoShape base; @@ -2089,7 +2098,7 @@ App::DocumentObjectExecReturn* Hole::execute() msg += std::to_string(i); return new App::DocumentObjectExecReturn(msg.c_str()); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); std::string msg(QT_TRANSLATE_NOOP("Exception", "Boolean operation failed on profile Edge")); msg += std::to_string(i); return new App::DocumentObjectExecReturn(msg.c_str()); @@ -2628,7 +2637,7 @@ int Hole::baseProfileOption_idxToBitmask(int index) if (index == 2) { return PartDesign::Hole::BaseProfileTypeOptions::OnPoints; } - Base::Console().Error("Unexpected hole base profile combobox index: %i", index); + Base::Console().error("Unexpected hole base profile combobox index: %i", index); return 0; } int Hole::baseProfileOption_bitmaskToIdx(int bitmask) @@ -2643,7 +2652,7 @@ int Hole::baseProfileOption_bitmaskToIdx(int bitmask) return 2; } - Base::Console().Error("Unexpected hole base profile bitmask: %i", bitmask); + Base::Console().error("Unexpected hole base profile bitmask: %i", bitmask); return -1; } diff --git a/src/Mod/PartDesign/App/FeaturePipe.cpp b/src/Mod/PartDesign/App/FeaturePipe.cpp index 7b60026224..08c4077948 100644 --- a/src/Mod/PartDesign/App/FeaturePipe.cpp +++ b/src/Mod/PartDesign/App/FeaturePipe.cpp @@ -494,9 +494,9 @@ void Pipe::getContinuousEdges(Part::TopoShape /*TopShape*/, std::vector shapes; for (auto& sub : subs) { shapes.push_back( - Part::Feature::getTopoShape(profile, sub.c_str(), needSubElement)); + Part::Feature::getTopoShape(profile, sub.c_str(), /* needSubElement */ true)); } shape = TopoShape(shape.Tag).makeElementCompound(shapes); } @@ -472,7 +472,7 @@ std::vector ProfileBased::getTopoShapeProfileWires() const // tessellations for some faces. Making an explicit copy of the linked // shape seems to fix it. The error mostly happens when re-computing the // shape but sometimes also for the first time - auto shape = getProfileShape(/*needSubElement*/ false).makeElementCopy(); + auto shape = getProfileShape().makeElementCopy(); if (shape.hasSubShape(TopAbs_WIRE)) { return shape.getSubTopoShapes(TopAbs_WIRE); diff --git a/src/Mod/PartDesign/App/FeatureSketchBased.h b/src/Mod/PartDesign/App/FeatureSketchBased.h index dc6cc81eed..08be8a10ef 100644 --- a/src/Mod/PartDesign/App/FeatureSketchBased.h +++ b/src/Mod/PartDesign/App/FeatureSketchBased.h @@ -131,7 +131,7 @@ public: virtual Base::Vector3d getProfileNormal() const; - TopoShape getProfileShape(bool needSubElement = false) const; + TopoShape getProfileShape() const; /// retrieves the number of axes in the linked sketch (defined as construction lines) int getSketchAxisCount() const; diff --git a/src/Mod/PartDesign/App/FeatureTransformed.cpp b/src/Mod/PartDesign/App/FeatureTransformed.cpp index 7e0dce819b..eefb46a72b 100644 --- a/src/Mod/PartDesign/App/FeatureTransformed.cpp +++ b/src/Mod/PartDesign/App/FeatureTransformed.cpp @@ -334,7 +334,7 @@ App::DocumentObjectExecReturn* Transformed::execute() supportShape = refineShapeIfActive((supportShape)); if (!isSingleSolidRuleSatisfied(supportShape.getShape())) { - Base::Console().Warning("Transformed: Result has multiple solids. Only keeping the first.\n"); + Base::Console().warning("Transformed: Result has multiple solids. Only keeping the first.\n"); } this->Shape.setValue(getSolid(supportShape)); // picking the first solid diff --git a/src/Mod/PartDesign/App/ShapeBinder.cpp b/src/Mod/PartDesign/App/ShapeBinder.cpp index cdbe83def8..399d4a0ead 100644 --- a/src/Mod/PartDesign/App/ShapeBinder.cpp +++ b/src/Mod/PartDesign/App/ShapeBinder.cpp @@ -389,7 +389,7 @@ SubShapeBinder::~SubShapeBinder() { clearCopiedObjects(); } catch (const Base::ValueError& e) { - e.ReportException(); + e.reportException(); } } @@ -452,7 +452,7 @@ void SubShapeBinder::setupCopyOnChange() { removeDynamicProperty(prop->getName()); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (...) { } @@ -678,7 +678,7 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR(getFullName() << " failed to obtain shape from " << obj->getFullName() << '.' << sub); if (errMsg.empty()) { @@ -817,7 +817,7 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { catch (...) { std::ostringstream msg; msg << Label.getValue() << ": failed to make 2D offset" << std::endl; - Base::Console().Error(msg.str().c_str()); + Base::Console().error(msg.str().c_str()); } } @@ -864,7 +864,7 @@ void SubShapeBinder::slotRecomputedObject(const App::DocumentObject& Obj) { update(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } } diff --git a/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp b/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp index 9ccb4a38e3..e9e8a33985 100644 --- a/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp +++ b/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp @@ -116,7 +116,7 @@ PyMOD_INIT_FUNC(PartDesignGui) } PyObject* mod = PartDesignGui::initModule(); - Base::Console().Log("Loading GUI of PartDesign module... done\n"); + Base::Console().log("Loading GUI of PartDesign module... done\n"); // instantiating the commands CreatePartDesignCommands(); diff --git a/src/Mod/PartDesign/Gui/Command.cpp b/src/Mod/PartDesign/Gui/Command.cpp index 328bc0a805..400fc4269e 100644 --- a/src/Mod/PartDesign/Gui/Command.cpp +++ b/src/Mod/PartDesign/Gui/Command.cpp @@ -405,7 +405,7 @@ void CmdPartDesignSubShapeBinder::activated(int iMsg) updateActive(); commitCommand(); } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(Gui::getMainWindow(), QObject::tr("Sub-Shape Binder"), QApplication::translate("Exception", e.what())); abortCommand(); @@ -609,13 +609,13 @@ unsigned validateSketches(std::vector& sketches, continue; } - //Base::Console().Error("Checking sketch %s\n", (*s)->getNameInDocument()); + //Base::Console().error("Checking sketch %s\n", (*s)->getNameInDocument()); // Check whether this sketch is already being used by another feature // Body features don't count... std::vector inList = (*s)->getInList(); std::vector::iterator o = inList.begin(); while (o != inList.end()) { - //Base::Console().Error("Inlist: %s\n", (*o)->getNameInDocument()); + //Base::Console().error("Inlist: %s\n", (*o)->getNameInDocument()); if ((*o)->isDerivedFrom()) o = inList.erase(o); //ignore bodies else if (!( (*o)->isDerivedFrom() )) @@ -1288,7 +1288,7 @@ void CmdPartDesignGroove::activated(int iMsg) FCMD_OBJ_CMD(Feat,"Reversed = 1"); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } finishProfileBased(cmd, sketch, Feat); diff --git a/src/Mod/PartDesign/Gui/CommandBody.cpp b/src/Mod/PartDesign/Gui/CommandBody.cpp index 0f2f85e804..db38c7915c 100644 --- a/src/Mod/PartDesign/Gui/CommandBody.cpp +++ b/src/Mod/PartDesign/Gui/CommandBody.cpp @@ -570,7 +570,7 @@ void CmdPartDesignMoveTip::activated(int iMsg) App::DocumentObject* oldTip = body->Tip.getValue(); if (oldTip == selFeature) { // it's not generally an error, so print only a console message - Base::Console().Message ("%s is already the tip of the body\n", selFeature->getNameInDocument () ); + Base::Console().message ("%s is already the tip of the body\n", selFeature->getNameInDocument () ); return; } diff --git a/src/Mod/PartDesign/Gui/SketchWorkflow.cpp b/src/Mod/PartDesign/Gui/SketchWorkflow.cpp index 7697239afc..acc06864be 100644 --- a/src/Mod/PartDesign/Gui/SketchWorkflow.cpp +++ b/src/Mod/PartDesign/Gui/SketchWorkflow.cpp @@ -380,7 +380,7 @@ public: tryFindBasePlanes(); } catch (const Base::Exception &ex) { - Base::Console().Error ("%s\n", ex.what() ); + Base::Console().error ("%s\n", ex.what() ); } } diff --git a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp index 3055a92e39..41bd6b0393 100644 --- a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp @@ -289,7 +289,7 @@ TaskChamferParameters::~TaskChamferParameters() } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -324,7 +324,7 @@ void TaskChamferParameters::apply() // Alert user if he created an empty feature if (ui->listWidgetReferences->count() == 0) { - Base::Console().Warning(tr("Empty chamfer created !\n").toStdString().c_str()); + Base::Console().warning(tr("Empty chamfer created !\n").toStdString().c_str()); } } diff --git a/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp b/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp index 15ab17d66e..0bd58df7c2 100644 --- a/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp @@ -268,7 +268,7 @@ TaskDraftParameters::~TaskDraftParameters() } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -284,7 +284,7 @@ void TaskDraftParameters::apply() { // Alert user if he created an empty feature if (ui->listWidgetReferences->count() == 0) { - Base::Console().Warning(tr("Empty draft created !\n").toStdString().c_str()); + Base::Console().warning(tr("Empty draft created !\n").toStdString().c_str()); } TaskDressUpParameters::apply(); diff --git a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp index 37adea59b8..4f8987f192 100644 --- a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp @@ -169,7 +169,7 @@ void TaskDressUpParameters::addAllEdges(QListWidget* widget) pcDressUp->Base.setValue(base, subValues); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -274,10 +274,10 @@ void TaskDressUpParameters::tryAddSelection(const std::string& doc, Gui::Selection().addSelection(doc.c_str(), obj.c_str(), sub.c_str(), 0, 0, 0); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const Standard_Failure& e) { - Base::Console().Error("OCC error: %s\n", e.GetMessageString()); + Base::Console().error("OCC error: %s\n", e.GetMessageString()); } } diff --git a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp index 1ebc00dce1..8cba881348 100644 --- a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp @@ -334,7 +334,7 @@ void TaskExtrudeParameters::tryRecomputeFeature() recomputeFeature(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -800,7 +800,7 @@ void TaskExtrudeParameters::onDirectionCBChanged(int num) else if (auto extrude = getObject()) { if (lnk.getValue()) { if (!extrude->getDocument()->isIn(lnk.getValue())) { - Base::Console().Error("Object was deleted\n"); + Base::Console().error("Object was deleted\n"); return; } propReferenceAxis->Paste(lnk); diff --git a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp index e639744216..ad00474162 100644 --- a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp +++ b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp @@ -325,16 +325,16 @@ std::vector TaskFeaturePick::buildFeatures() } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (Py::Exception& e) { // reported by code analyzers e.clear(); - Base::Console().Warning("Unexpected PyCXX exception\n"); + Base::Console().warning("Unexpected PyCXX exception\n"); } catch (const boost::exception&) { // reported by code analyzers - Base::Console().Warning("Unexpected boost exception\n"); + Base::Console().warning("Unexpected boost exception\n"); } return result; diff --git a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp index 4be4ae6adc..d1f9cd5cc4 100644 --- a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp @@ -172,7 +172,7 @@ TaskFilletParameters::~TaskFilletParameters() } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -191,7 +191,7 @@ void TaskFilletParameters::apply() // Alert user if he created an empty feature if (ui->listWidgetReferences->count() == 0) { std::string text = tr("Empty fillet created!").toStdString(); - Base::Console().Warning("%s\n", text.c_str()); + Base::Console().warning("%s\n", text.c_str()); } } diff --git a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp index 2421e6f564..980ec2ffaf 100644 --- a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp @@ -177,7 +177,7 @@ void TaskHelixParameters::showCoordinateAxes() vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } catch (const Base::Exception& ex) { - ex.ReportException(); + ex.reportException(); } } } @@ -239,7 +239,7 @@ void TaskHelixParameters::addPartAxes() addAxisToCombo(orig->getZ(), "", tr("Base Z axis")); } catch (const Base::Exception& ex) { - ex.ReportException(); + ex.reportException(); } } } @@ -496,7 +496,7 @@ void TaskHelixParameters::onAxisChanged(int num) } else { if (!helix->getDocument()->isIn(lnk.getValue())) { - Base::Console().Error("Object was deleted\n"); + Base::Console().error("Object was deleted\n"); return; } propReferenceAxis->Paste(lnk); @@ -528,7 +528,7 @@ void TaskHelixParameters::onAxisChanged(int num) updateStatus(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -589,7 +589,7 @@ TaskHelixParameters::~TaskHelixParameters() } } catch (const Base::Exception& ex) { - ex.ReportException(); + ex.reportException(); } } diff --git a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp index a29aea8ac1..6d3e5d2ced 100644 --- a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp @@ -277,7 +277,7 @@ void TaskHoleParameters::threadedChanged() ui->ThreadGroupBox->setVisible(isChecked); ui->ClearanceWidget->setHidden(isChecked); - // run modelThreadChanged + // run modelThreadChanged // it will handle the visibility of the model options modelThreadChanged(); recomputeFeature(); @@ -781,7 +781,7 @@ void TaskHoleParameters::changedObject(const App::Document&, const App::Property } bool ro = Prop.isReadOnly(); - Base::Console().Log("Parameter %s was updated\n", Prop.getName()); + Base::Console().log("Parameter %s was updated\n", Prop.getName()); auto updateCheckable = [&](QCheckBox* widget, bool value) { [[maybe_unused]] QSignalBlocker blocker(widget); @@ -1182,7 +1182,7 @@ void TaskHoleParameters::Observer::slotChangedObject(const App::DocumentObject& const App::Property& Prop) { if (&Obj == hole) { - Base::Console().Log("Parameter %s was updated with a new value\n", Prop.getName()); + Base::Console().log("Parameter %s was updated with a new value\n", Prop.getName()); if (Obj.getDocument()) { owner->changedObject(*Obj.getDocument(), Prop); } diff --git a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp index a546acf69f..5cff275990 100644 --- a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp @@ -114,7 +114,7 @@ void TaskLinearPatternParameters::setupParameterUI(QWidget* widget) vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } @@ -400,7 +400,7 @@ TaskLinearPatternParameters::~TaskLinearPatternParameters() } } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } diff --git a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp index e7912ff4d6..3e8fcc74ae 100644 --- a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp @@ -95,7 +95,7 @@ void TaskMirroredParameters::setupParameterUI(QWidget* widget) vpOrigin->setTemporaryVisibility(Gui::DatumElement::Planes); } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } @@ -231,7 +231,7 @@ TaskMirroredParameters::~TaskMirroredParameters() } } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } diff --git a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp index 77362510a5..6e79357ed2 100644 --- a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp @@ -542,7 +542,7 @@ TaskMultiTransformParameters::~TaskMultiTransformParameters() } catch (const Py::Exception&) { Base::PyException exc; // extract the Python error text - exc.ReportException(); + exc.reportException(); } } diff --git a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp index d3656020ef..258d58464c 100644 --- a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp @@ -165,11 +165,11 @@ TaskPipeParameters::~TaskPipeParameters() } catch (const Base::Exception& e) { // getDocument() may raise an exception - e.ReportException(); + e.reportException(); } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } diff --git a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp index 95df7a06fa..d69d610591 100644 --- a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp @@ -116,7 +116,7 @@ void TaskPolarPatternParameters::setupParameterUI(QWidget* widget) vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } @@ -394,7 +394,7 @@ TaskPolarPatternParameters::~TaskPolarPatternParameters() } } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } diff --git a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp index d7546695f3..ebb5d0d8f6 100644 --- a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp @@ -265,7 +265,7 @@ TaskBoxPrimitives::TaskBoxPrimitives(ViewProviderPrimitive* vp, QWidget* parent) vpOrigin = static_cast(Gui::Application::Instance->getViewProvider(origin)); vpOrigin->setTemporaryVisibility(Gui::DatumElement::Planes | Gui::DatumElement::Axes); } catch (const Base::Exception &ex) { - Base::Console().Error ("%s\n", ex.what () ); + Base::Console().error ("%s\n", ex.what () ); } } @@ -388,7 +388,7 @@ TaskBoxPrimitives::~TaskBoxPrimitives() } } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } diff --git a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp index 1aaecd72a0..734c6fffc6 100644 --- a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp @@ -104,7 +104,7 @@ TaskRevolutionParameters::TaskRevolutionParameters(PartDesignGui::ViewProvider* } } catch (const Base::Exception &ex) { - ex.ReportException(); + ex.reportException(); } } @@ -236,7 +236,7 @@ void TaskRevolutionParameters::fillAxisCombo(bool forceRefill) addAxisToCombo(orig->getY(), std::string(), tr("Base Y axis")); addAxisToCombo(orig->getZ(), std::string(), tr("Base Z axis")); } catch (const Base::Exception &ex) { - ex.ReportException(); + ex.reportException(); } } @@ -541,7 +541,7 @@ void TaskRevolutionParameters::onAxisChanged(int num) AllowSelection::CIRCLE); } else { if (!pcRevolution->getDocument()->isIn(lnk.getValue())){ - Base::Console().Error("Object was deleted\n"); + Base::Console().error("Object was deleted\n"); return; } propReferenceAxis->Paste(lnk); @@ -578,7 +578,7 @@ void TaskRevolutionParameters::onAxisChanged(int num) recomputeFeature(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -665,7 +665,7 @@ TaskRevolutionParameters::~TaskRevolutionParameters() } } catch (const Base::Exception &ex) { - ex.ReportException(); + ex.reportException(); } axesInList.clear(); diff --git a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp index 077623a02c..e9c8d55dfa 100644 --- a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp @@ -242,7 +242,7 @@ QString TaskSketchBasedParameters::make2DLabel(const App::DocumentObject* sectio return QString::fromUtf8(section->Label.getValue()); } else if (subValues.empty()) { - Base::Console().Error("No valid subelement linked in %s\n", section->Label.getValue()); + Base::Console().error("No valid subelement linked in %s\n", section->Label.getValue()); return {}; } else { diff --git a/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp b/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp index 081b2998e1..732d541c07 100644 --- a/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp @@ -241,7 +241,7 @@ TaskThicknessParameters::~TaskThicknessParameters() } catch (const Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); } } @@ -257,7 +257,7 @@ void TaskThicknessParameters::apply() { // Alert user if he created an empty feature if (ui->listWidgetReferences->count() == 0) { - Base::Console().Warning(tr("Empty thickness created !\n").toStdString().c_str()); + Base::Console().warning(tr("Empty thickness created !\n").toStdString().c_str()); } } diff --git a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp index 1b833991ae..b426bba314 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp @@ -374,7 +374,7 @@ void TaskTransformedParameters::onFeatureDeleted() std::vector originals = pcTransformed->Originals.getValues(); int currentRow = ui->listWidgetFeatures->currentRow(); if (currentRow < 0) { - Base::Console().Error("PartDesign Pattern: No feature selected for removing.\n"); + Base::Console().error("PartDesign Pattern: No feature selected for removing.\n"); return; // no current row selected } originals.erase(originals.begin() + currentRow); @@ -424,7 +424,7 @@ void TaskTransformedParameters::fillAxisCombo(ComboLinks& combolinks, Part::Part combolinks.addLink(orig->getZ(), "", tr("Base Z axis")); } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } @@ -460,7 +460,7 @@ void TaskTransformedParameters::fillPlanesCombo(ComboLinks& combolinks, Part::Pa combolinks.addLink(orig->getXZ(), "", tr("Base XZ plane")); } catch (const Base::Exception& ex) { - Base::Console().Error("%s\n", ex.what()); + Base::Console().error("%s\n", ex.what()); } } @@ -531,7 +531,7 @@ void TaskTransformedParameters::hideObject() FCMD_OBJ_HIDE(getTopTransformedObject()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -541,7 +541,7 @@ void TaskTransformedParameters::showObject() FCMD_OBJ_SHOW(getTopTransformedObject()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -551,7 +551,7 @@ void TaskTransformedParameters::hideBase() FCMD_OBJ_HIDE(getBaseObject()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -561,7 +561,7 @@ void TaskTransformedParameters::showBase() FCMD_OBJ_SHOW(getBaseObject()); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } @@ -574,7 +574,7 @@ void TaskTransformedParameters::exitSelectionMode() showObject(); } catch (Base::Exception& exc) { - exc.ReportException(); + exc.reportException(); } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderAddSub.cpp b/src/Mod/PartDesign/Gui/ViewProviderAddSub.cpp index 0cc2fdbefe..250771aa5a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderAddSub.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderAddSub.cpp @@ -222,7 +222,7 @@ void ViewProviderAddSub::updateAddSubShapeIndicator() { previewFaceSet ->partIndex .finishEditing(); } catch (...) { - Base::Console().Error("Cannot compute Inventor representation for the shape of %s.\n",pcObject->getNameInDocument()); + Base::Console().error("Cannot compute Inventor representation for the shape of %s.\n",pcObject->getNameInDocument()); } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp index 860af076b4..08a2d2a429 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp @@ -183,16 +183,16 @@ bool ViewProviderBody::doubleClicked() // if (ActiveGuiDoc == NULL) return; // // // Highlight active body and all its features -// //Base::Console().Error("ViewProviderBody::updateTree()\n"); +// //Base::Console().error("ViewProviderBody::updateTree()\n"); // PartDesign::Body* body = getObject(); // bool active = body->IsActive.getValue(); -// //Base::Console().Error("Body is %s\n", active ? "active" : "inactive"); +// //Base::Console().error("Body is %s\n", active ? "active" : "inactive"); // ActiveGuiDoc->signalHighlightObject(*this, Gui::Blue, active); // std::vector features = body->Group.getValues(); // bool highlight = true; // App::DocumentObject* tip = body->Tip.getValue(); // for (std::vector::const_iterator f = features.begin(); f != features.end(); f++) { -// //Base::Console().Error("Highlighting %s: %s\n", (*f)->getNameInDocument(), highlight ? "true" : "false"); +// //Base::Console().error("Highlighting %s: %s\n", (*f)->getNameInDocument(), highlight ? "true" : "false"); // Gui::ViewProviderDocumentObject* vp = dynamic_cast(Gui::Application::Instance->getViewProvider(*f)); // if (vp != NULL) // ActiveGuiDoc->signalHighlightObject(*vp, Gui::LightBlue, active ? highlight : false); @@ -257,7 +257,7 @@ void ViewProviderBody::onChanged(const App::Property* prop) { if(getOverrideMode() == "As Is") setDisplayMaskMode(DisplayMode.getValueAsString()); else { - Base::Console().Message("Set override mode: %s\n", getOverrideMode().c_str()); + Base::Console().message("Set override mode: %s\n", getOverrideMode().c_str()); setDisplayMaskMode(getOverrideMode().c_str()); } } @@ -403,7 +403,7 @@ void ViewProviderBody::dropObject(App::DocumentObject* obj) body->addObjects(move); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } } else if (!body->BaseFeature.getValue()) { diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp index 5da2b897ec..58b27f7177 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp @@ -384,7 +384,7 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { self->update(PartDesign::SubShapeBinder::UpdateForced); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } return; } @@ -398,7 +398,7 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { return; } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (Standard_Failure& e) { std::ostringstream str; diff --git a/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp b/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp index 9b46447312..73c4aa1225 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp @@ -330,7 +330,7 @@ void ViewProviderTransformed::showRejectedShape(TopoDS_Shape shape) } } catch (...) { - Base::Console().Error("Cannot compute Inventor representation for the rejected transformations of shape of %s.\n", + Base::Console().error("Cannot compute Inventor representation for the rejected transformations of shape of %s.\n", getObject()->getNameInDocument()); } } diff --git a/src/Mod/Points/App/AppPoints.cpp b/src/Mod/Points/App/AppPoints.cpp index fbdc5c8a57..b367009ac0 100644 --- a/src/Mod/Points/App/AppPoints.cpp +++ b/src/Mod/Points/App/AppPoints.cpp @@ -42,7 +42,7 @@ PyMOD_INIT_FUNC(Points) { // clang-format off PyObject* pointsModule = Points::initModule(); - Base::Console().Log("Loading Points module... done\n"); + Base::Console().log("Loading Points module... done\n"); // add python types Base::Interpreter().addType(&Points::PointsPy::Type, pointsModule, "Points"); diff --git a/src/Mod/Points/App/AppPointsPy.cpp b/src/Mod/Points/App/AppPointsPy.cpp index fb6aa8cbde..c0e7cf9ba6 100644 --- a/src/Mod/Points/App/AppPointsPy.cpp +++ b/src/Mod/Points/App/AppPointsPy.cpp @@ -83,7 +83,7 @@ private: PyMem_Free(Name); try { - Base::Console().Log("Open in Points with %s", EncodedName.c_str()); + Base::Console().log("Open in Points with %s", EncodedName.c_str()); Base::FileInfo file(EncodedName.c_str()); // extract ending @@ -205,7 +205,7 @@ private: PyMem_Free(Name); try { - Base::Console().Log("Import in Points with %s", EncodedName.c_str()); + Base::Console().log("Import in Points with %s", EncodedName.c_str()); Base::FileInfo file(EncodedName.c_str()); // extract ending @@ -390,7 +390,7 @@ private: break; } else { - Base::Console().Message("'%s' is not a point object, export will be ignored.\n", + Base::Console().message("'%s' is not a point object, export will be ignored.\n", obj->Label.getValue()); } } diff --git a/src/Mod/Points/Gui/AppPointsGui.cpp b/src/Mod/Points/Gui/AppPointsGui.cpp index 0da1eb3f5f..303ec357c9 100644 --- a/src/Mod/Points/Gui/AppPointsGui.cpp +++ b/src/Mod/Points/Gui/AppPointsGui.cpp @@ -81,7 +81,7 @@ PyMOD_INIT_FUNC(PointsGui) PyMOD_Return(nullptr); } - Base::Console().Log("Loading GUI of Points module... done\n"); + Base::Console().log("Loading GUI of Points module... done\n"); PyObject* mod = PointsGui::initModule(); // instantiating the commands diff --git a/src/Mod/Points/Gui/Command.cpp b/src/Mod/Points/Gui/Command.cpp index b0f76cb089..3250fb6e35 100644 --- a/src/Mod/Points/Gui/Command.cpp +++ b/src/Mod/Points/Gui/Command.cpp @@ -309,7 +309,7 @@ void CmdPointsConvert::activated(int iMsg) catch (const Py::Exception&) { abortCommand(); Base::PyException e; - e.ReportException(); + e.reportException(); } } diff --git a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp index 311cf73e8b..ca4848c8e5 100644 --- a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp +++ b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp @@ -999,7 +999,7 @@ PyMOD_INIT_FUNC(ReverseEngineering) } PyObject* mod = Reen::initModule(); - Base::Console().Log("Loading ReverseEngineering module... done\n"); + Base::Console().log("Loading ReverseEngineering module... done\n"); PyMOD_Return(mod); } // clang-format on diff --git a/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp b/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp index f89ba6ee71..ef9ec5e51d 100644 --- a/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp +++ b/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp @@ -82,7 +82,7 @@ PyMOD_INIT_FUNC(ReverseEngineeringGui) } PyObject* mod = ReverseEngineeringGui::initModule(); - Base::Console().Log("Loading GUI of ReverseEngineering module... done\n"); + Base::Console().log("Loading GUI of ReverseEngineering module... done\n"); // instantiating the commands CreateReverseEngineeringCommands(); diff --git a/src/Mod/ReverseEngineering/Gui/Command.cpp b/src/Mod/ReverseEngineering/Gui/Command.cpp index 8ac65d98d6..09b72958e6 100644 --- a/src/Mod/ReverseEngineering/Gui/Command.cpp +++ b/src/Mod/ReverseEngineering/Gui/Command.cpp @@ -208,11 +208,11 @@ void CmdApproxPlane::activated(int) double q0, q1, q2, q3; pm.getRotation().getValue(q0, q1, q2, q3); - Base::Console().Log("RMS value for plane fit with %lu points: %.4f\n", + Base::Console().log("RMS value for plane fit with %lu points: %.4f\n", aData.size(), sigma); - Base::Console().Log(" Plane base(%.4f, %.4f, %.4f)\n", base.x, base.y, base.z); - Base::Console().Log(" Plane normal(%.4f, %.4f, %.4f)\n", norm.x, norm.y, norm.z); + Base::Console().log(" Plane base(%.4f, %.4f, %.4f)\n", base.x, base.y, base.z); + Base::Console().log(" Plane normal(%.4f, %.4f, %.4f)\n", norm.x, norm.y, norm.z); std::stringstream str; str << "from FreeCAD import Base" << std::endl; diff --git a/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp b/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp index 73f3baec44..153b8ee421 100644 --- a/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp +++ b/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp @@ -149,7 +149,7 @@ void FitBSplineCurveWidget::tryCommand(const QString& cmd) } catch (const Base::Exception& e) { Gui::Command::abortCommand(); - e.ReportException(); + e.reportException(); } } diff --git a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp index 6a47a77e86..1f9a119952 100644 --- a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp +++ b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp @@ -211,13 +211,13 @@ void Segmentation::accept() } else { failures.push_back(feaSegm); - Base::Console().Warning("Failed to create face from %s\n", + Base::Console().warning("Failed to create face from %s\n", feaSegm->Label.getValue()); } } catch (Standard_Failure&) { failures.push_back(feaSegm); - Base::Console().Error("Fatal failure to create face from %s\n", + Base::Console().error("Fatal failure to create face from %s\n", feaSegm->Label.getValue()); } } diff --git a/src/Mod/Robot/App/AppRobot.cpp b/src/Mod/Robot/App/AppRobot.cpp index d0b7051ef7..03f15bb67a 100644 --- a/src/Mod/Robot/App/AppRobot.cpp +++ b/src/Mod/Robot/App/AppRobot.cpp @@ -109,7 +109,7 @@ PyMOD_INIT_FUNC(Robot) } PyObject* robotModule = Robot::initModule(); - Base::Console().Log("Loading Robot module... done\n"); + Base::Console().log("Loading Robot module... done\n"); // Add Types to module Base::Interpreter().addType(&Robot::Robot6AxisPy ::Type,robotModule,"Robot6Axis"); diff --git a/src/Mod/Robot/Gui/AppRobotGui.cpp b/src/Mod/Robot/Gui/AppRobotGui.cpp index 334b2500e3..b7609b0fd3 100644 --- a/src/Mod/Robot/Gui/AppRobotGui.cpp +++ b/src/Mod/Robot/Gui/AppRobotGui.cpp @@ -100,7 +100,7 @@ PyMOD_INIT_FUNC(RobotGui) PyMOD_Return(nullptr); } PyObject* mod = RobotGui::initModule(); - Base::Console().Log("Loading GUI of Robot module... done\n"); + Base::Console().log("Loading GUI of Robot module... done\n"); // instantiating the commands CreateRobotCommands(); diff --git a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp index c5d43531af..c6ee2e283a 100644 --- a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp +++ b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp @@ -83,7 +83,7 @@ void TaskDlgEdge2Trac::clicked(int button) } } catch (const Base::Exception& e) { - Base::Console().Warning("TaskDlgEdge2Trac::clicked(): %s\n", e.what()); + Base::Console().warning("TaskDlgEdge2Trac::clicked(): %s\n", e.what()); } } @@ -104,7 +104,7 @@ bool TaskDlgEdge2Trac::accept() } } catch (const Base::Exception& e) { - Base::Console().Warning("TaskDlgEdge2Trac::accept(): %s\n", e.what()); + Base::Console().warning("TaskDlgEdge2Trac::accept(): %s\n", e.what()); } return false; diff --git a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp index 8373c795eb..22792ea55c 100644 --- a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp +++ b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp @@ -445,7 +445,7 @@ void ViewProviderRobotObject::DraggerMotionCallback(SoDragger* dragger) SbVec3f center(Tcp.getPosition().x, Tcp.getPosition().y, Tcp.getPosition().z); M.getTransform(translation, rotation, scaleFactor, scaleOrientation); rotation.getValue(q0, q1, q2, q3); - // Base::Console().Message("M %f %f %f\n", M[3][0], M[3][1], M[3][2]); + // Base::Console().message("M %f %f %f\n", M[3][0], M[3][1], M[3][2]); Base::Rotation rot(q0, q1, q2, q3); Base::Vector3d pos(translation[0], translation[1], translation[2]); robObj->Tcp.setValue(Base::Placement(pos, rot)); diff --git a/src/Mod/Sandbox/App/AppSandbox.cpp b/src/Mod/Sandbox/App/AppSandbox.cpp index 4618589aa8..5a6adf4c7a 100644 --- a/src/Mod/Sandbox/App/AppSandbox.cpp +++ b/src/Mod/Sandbox/App/AppSandbox.cpp @@ -209,12 +209,12 @@ public: &Module::new_DocumentObjectProtector, "DocumentObjectProtector(DocumentObject)"); initialize("This module is the Sandbox module"); // register with Python - + Py::Dict d( moduleDictionary() ); Py::Object x( Sandbox::PythonBaseClass::type() ); d["PythonBaseClass"] = x; } - + virtual ~Module() {} private: @@ -253,6 +253,6 @@ PyMOD_INIT_FUNC(Sandbox) // the following constructor call registers our extension module // with the Python runtime system PyObject* mod = Sandbox::initModule(); - Base::Console().Log("Loading Sandbox module... done\n"); + Base::Console().log("Loading Sandbox module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Sandbox/App/DocumentThread.cpp b/src/Mod/Sandbox/App/DocumentThread.cpp index bd11674f01..b8df4ce511 100644 --- a/src/Mod/Sandbox/App/DocumentThread.cpp +++ b/src/Mod/Sandbox/App/DocumentThread.cpp @@ -133,7 +133,7 @@ void PythonThread::run() #endif } catch (const Base::PyException& e) { - Base::Console().Error(e.what()); + Base::Console().error(e.what()); } } @@ -181,26 +181,26 @@ short SandboxObject::mustExecute(void) const App::DocumentObjectExecReturn *SandboxObject::execute(void) { - Base::Console().Message("SandboxObject::execute()\n"); + Base::Console().message("SandboxObject::execute()\n"); return 0; } void SandboxObject::onChanged(const App::Property* prop) { if (prop == &Integer) - Base::Console().Message("SandboxObject::onChanged(%d)\n", Integer.getValue()); + Base::Console().message("SandboxObject::onChanged(%d)\n", Integer.getValue()); App::DocumentObject::onChanged(prop); } void SandboxObject::setIntValue(int v) { - Base::Console().Message("SandboxObject::setIntValue(%d)\n", v); + Base::Console().message("SandboxObject::setIntValue(%d)\n", v); Integer.setValue(v); } void SandboxObject::resetValue() { - Base::Console().Message("SandboxObject::resetValue()\n"); + Base::Console().message("SandboxObject::resetValue()\n"); Integer.setValue(4711); } @@ -215,7 +215,7 @@ DocumentTestThread::~DocumentTestThread() void DocumentTestThread::run() { - Base::Console().Message("DocumentTestThread::run()\n"); + Base::Console().message("DocumentTestThread::run()\n"); App::Document* doc = App::GetApplication().getActiveDocument(); DocumentProtector dp(doc); SandboxObject* obj = dp.addObject(); diff --git a/src/Mod/Sandbox/Gui/AppSandboxGui.cpp b/src/Mod/Sandbox/Gui/AppSandboxGui.cpp index 6bc88ea0c0..34cc678910 100644 --- a/src/Mod/Sandbox/Gui/AppSandboxGui.cpp +++ b/src/Mod/Sandbox/Gui/AppSandboxGui.cpp @@ -107,17 +107,17 @@ private: coords->point.set1Value(1, (float)m2.x,(float)m2.y,(float)m2.z); coords->point.set1Value(2, (float)s2.x,(float)s2.y,(float)s2.z); - Base::Console().Message("M1=<%.4f,%.4f>\n", m1.x,m1.y); - Base::Console().Message("M2=<%.4f,%.4f>\n", m2.x,m2.y); - Base::Console().Message("S1=<%.4f,%.4f>\n", s1.x,s1.y); - Base::Console().Message("S2=<%.4f,%.4f>\n", s2.x,s2.y); - Base::Console().Message("P=<%.4f,%.4f>\n", a3.x,a3.y); - Base::Console().Message("Q=<%.4f,%.4f>\n", l2.x,l2.y); - Base::Console().Message("\n"); + Base::Console().message("M1=<%.4f,%.4f>\n", m1.x,m1.y); + Base::Console().message("M2=<%.4f,%.4f>\n", m2.x,m2.y); + Base::Console().message("S1=<%.4f,%.4f>\n", s1.x,s1.y); + Base::Console().message("S2=<%.4f,%.4f>\n", s2.x,s2.y); + Base::Console().message("P=<%.4f,%.4f>\n", a3.x,a3.y); + Base::Console().message("Q=<%.4f,%.4f>\n", l2.x,l2.y); + Base::Console().message("\n"); } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } #else @@ -144,7 +144,7 @@ public: "Read XML"); initialize("This module is the SandboxGui module"); // register with Python } - + virtual ~Module() {} private: @@ -215,6 +215,6 @@ PyMOD_INIT_FUNC(SandboxGui) // the following constructor call registers our extension module // with the Python runtime system PyObject* mod = SandboxGui::initModule(); - Base::Console().Log("Loading GUI of Sandbox module... done\n"); + Base::Console().log("Loading GUI of Sandbox module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Sandbox/Gui/Command.cpp b/src/Mod/Sandbox/Gui/Command.cpp index 4df0634e81..38b7040df4 100644 --- a/src/Mod/Sandbox/Gui/Command.cpp +++ b/src/Mod/Sandbox/Gui/Command.cpp @@ -533,7 +533,7 @@ void CmdSandboxEventLoop::activated(int) timer.start(5000); // 5s timeout loop.exec(); - Base::Console().Message("CmdSandboxEventLoop: timeout\n"); + Base::Console().message("CmdSandboxEventLoop: timeout\n"); } bool CmdSandboxEventLoop::isActive(void) @@ -758,7 +758,7 @@ public: kernel = myMesh->getKernel(); for (std::vector::iterator it = meshes.begin(); it != meshes.end(); ++it) { if (*it != myMesh) { - Base::Console().Message("MeshTestJob::run() in thread: %p\n", QThread::currentThreadId()); + Base::Console().message("MeshTestJob::run() in thread: %p\n", QThread::currentThreadId()); } } @@ -822,7 +822,7 @@ void CmdSandboxMeshTestJob::activated(int) } // run the actual multi-threaded mesh test - Base::Console().Message("Mesh test (step %d)...\n",iteration++); + Base::Console().message("Mesh test (step %d)...\n",iteration++); MeshTestJob meshJob; QFuture mesh_future = QtConcurrent::mapped (mesh_groups, boost::bind(&MeshTestJob::run, &meshJob, bp::_1)); @@ -840,7 +840,7 @@ void CmdSandboxMeshTestJob::activated(int) } if (meshes.empty()) { - Base::Console().Error("The mesh test failed to create a valid mesh.\n"); + Base::Console().error("The mesh test failed to create a valid mesh.\n"); return; } } @@ -905,9 +905,9 @@ void CmdSandboxMeshTestRef::activated(int) Mesh::MeshObject* ptr = (Mesh::MeshObject*)mesh; if (!ptr) - Base::Console().Error("Object deleted\n"); + Base::Console().error("Object deleted\n"); if (num != mesh.getRefCount()) - Base::Console().Error("Reference count is %d\n",mesh.getRefCount()); + Base::Console().error("Reference count is %d\n",mesh.getRefCount()); } bool CmdSandboxMeshTestRef::isActive(void) diff --git a/src/Mod/Sketcher/App/AppSketcher.cpp b/src/Mod/Sketcher/App/AppSketcher.cpp index eba2a200e6..97766496eb 100644 --- a/src/Mod/Sketcher/App/AppSketcher.cpp +++ b/src/Mod/Sketcher/App/AppSketcher.cpp @@ -99,7 +99,7 @@ PyMOD_INIT_FUNC(Sketcher) Sketcher::Measure ::initialize(); - Base::Console().Log("Loading Sketcher module... done\n"); + Base::Console().log("Loading Sketcher module... done\n"); PyMOD_Return(sketcherModule); } diff --git a/src/Mod/Sketcher/App/AppSketcherPy.cpp b/src/Mod/Sketcher/App/AppSketcherPy.cpp index 590cc013be..c324233c57 100644 --- a/src/Mod/Sketcher/App/AppSketcherPy.cpp +++ b/src/Mod/Sketcher/App/AppSketcherPy.cpp @@ -58,7 +58,7 @@ private: std::string EncodedName = std::string(Name); PyMem_Free(Name); - // Base::Console().Log("Open in Part with %s",Name); + // Base::Console().log("Open in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract extension @@ -81,7 +81,7 @@ private: PyMem_Free(Name); try { - // Base::Console().Log("Insert in Part with %s",Name); + // Base::Console().log("Insert in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract extension diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp index 6a4d249ba2..899bcc5100 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp @@ -94,7 +94,7 @@ void ExternalGeometryFacade::initExtensions() // The following warning was commented out as part of the Toponaming problem mitigation, and // left for potential usefulness to future developers making a custom build for debugging. - // Base::Console().Warning("Sketcher External Geometry without Geometry Extension: %s + // Base::Console().warning("Sketcher External Geometry without Geometry Extension: %s // \n", // boost::uuids::to_string(Geo->getTag()).c_str()); } @@ -106,7 +106,7 @@ void ExternalGeometryFacade::initExtensions() // The following warning was commented out as part of the Toponaming problem mitigation, and // left for potential usefulness to future developers making a custom build for debugging. - // Base::Console().Warning( + // Base::Console().warning( // "Sketcher External Geometry without ExternalGeometryExtension: %s \n", // boost::uuids::to_string(Geo->getTag()).c_str()); } diff --git a/src/Mod/Sketcher/App/GeometryFacade.cpp b/src/Mod/Sketcher/App/GeometryFacade.cpp index 4b4d89b70f..6746cae859 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.cpp +++ b/src/Mod/Sketcher/App/GeometryFacade.cpp @@ -86,7 +86,7 @@ void GeometryFacade::initExtension() getGeo()->setExtension(std::make_unique()); // Create getExtension - // Base::Console().Warning("%s\nSketcher Geometry without Extension: %s \n", + // Base::Console().warning("%s\nSketcher Geometry without Extension: %s \n", // boost::uuids::to_string(Geo->getTag()).c_str()); } diff --git a/src/Mod/Sketcher/App/PythonConverter.cpp b/src/Mod/Sketcher/App/PythonConverter.cpp index 7c7dbdae19..f5795615fe 100644 --- a/src/Mod/Sketcher/App/PythonConverter.cpp +++ b/src/Mod/Sketcher/App/PythonConverter.cpp @@ -195,6 +195,29 @@ std::string PythonConverter::convert(const std::string& doc, return constraintlist; } +template +std::string makeSplineInfoArrayString(const std::vector& rInfoVec) +{ + std::stringstream stream; + if constexpr (std::is_same_v) { + for (const auto& rInfo : rInfoVec) { + stream << "App.Vector(" << rInfo.x << ", " << rInfo.y << "), "; + } + } + else { + for (const auto& rInfo : rInfoVec) { + stream << rInfo << ", "; + } + } + + std::string res = stream.str(); + // remove last comma and add brackets + int index = res.rfind(','); + res.resize(index); + return fmt::format("[{}]", res); + ; +} + PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* geo) { static std::map> @@ -307,23 +330,17 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g [](const Part::Geometry* geo) { auto bSpline = static_cast(geo); - std::stringstream stream; - std::vector poles = bSpline->getPoles(); - for (auto& pole : poles) { - stream << "App.Vector(" << pole.x << "," << pole.y << "),"; - } - std::string controlpoints = stream.str(); - // remove last comma and add brackets - int index = controlpoints.rfind(','); - controlpoints.resize(index); - controlpoints.insert(0, 1, '['); - controlpoints.append(1, ']'); + std::string controlpoints = makeSplineInfoArrayString(bSpline->getPoles()); + std::string mults = makeSplineInfoArrayString(bSpline->getMultiplicities()); + std::string knots = makeSplineInfoArrayString(bSpline->getKnots()); + std::string weights = makeSplineInfoArrayString(bSpline->getWeights()); SingleGeometry sg; - sg.creation = boost::str( - boost::format("Part.BSplineCurve (%s, None, None, %s, %d, None, False)") - % controlpoints.c_str() % (bSpline->isPeriodic() ? "True" : "False") - % bSpline->getDegree()); + sg.creation = + boost::str(boost::format("Part.BSplineCurve(%s, %s, %s, %s, %d, %s, False)") + % controlpoints.c_str() % mults.c_str() % knots.c_str() + % (bSpline->isPeriodic() ? "True" : "False") % bSpline->getDegree() + % weights.c_str()); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, diff --git a/src/Mod/Sketcher/App/Sketch.cpp b/src/Mod/Sketcher/App/Sketch.cpp index 24d350825d..dcc117664a 100644 --- a/src/Mod/Sketcher/App/Sketch.cpp +++ b/src/Mod/Sketcher/App/Sketch.cpp @@ -227,31 +227,31 @@ int Sketch::setUpSketch(const std::vector& GeoList, #ifdef DEBUG_BLOCK_CONSTRAINT if (doesBlockAffectOtherConstraints) { - Base::Console().Log("\n Block interferes with other constraints: Post-analysis required"); + Base::Console().log("\n Block interferes with other constraints: Post-analysis required"); } - Base::Console().Log("\nOnlyBlocked GeoIds:"); + Base::Console().log("\nOnlyBlocked GeoIds:"); size_t i = 0; bool found = false; for (; i < onlyBlockedGeometry.size(); i++) { if (onlyBlockedGeometry[i]) { - Base::Console().Log("\n GeoId=%d", i); + Base::Console().log("\n GeoId=%d", i); found = true; } } if (found) { - Base::Console().Log("\n None"); + Base::Console().log("\n None"); } - Base::Console().Log("\nNotOnlyBlocked GeoIds:"); + Base::Console().log("\nNotOnlyBlocked GeoIds:"); i = 0; for (; i < blockedGeoIds.size(); i++) { - Base::Console().Log("\n GeoId=%d", blockedGeoIds[i]); + Base::Console().log("\n GeoId=%d", blockedGeoIds[i]); } if (i == 0) { - Base::Console().Log("\n None"); + Base::Console().log("\n None"); } - Base::Console().Log("\n"); + Base::Console().log("\n"); #endif // DEBUG_BLOCK_CONSTRAINT buildInternalAlignmentGeometryMap(ConstraintList); @@ -301,7 +301,7 @@ int Sketch::setUpSketch(const std::vector& GeoList, analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); if (debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n", + Base::Console().log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n", index); } index++; @@ -317,9 +317,9 @@ int Sketch::setUpSketch(const std::vector& GeoList, // Debug code block for (size_t i = 0; i < groups.size(); i++) { - Base::Console().Log("\nDepParams: Group %d:", i); + Base::Console().log("\nDepParams: Group %d:", i); for (size_t j = 0; j < groups[i].size(); j++) { - Base::Console().Log( + Base::Console().log( "\n Param=%x ,GeoId=%d, GeoPos=%d", param2geoelement.find(*std::next(groups[i].begin(), j))->first, param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, @@ -341,7 +341,7 @@ int Sketch::setUpSketch(const std::vector& GeoList, if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { Base::TimeElapsed end_time; - Base::Console().Log("Sketcher::setUpSketch()-T:%s\n", + Base::Console().log("Sketcher::setUpSketch()-T:%s\n", Base::TimeElapsed::diffTime(start_time, end_time).c_str()); } @@ -401,9 +401,9 @@ bool Sketch::analyseBlockedConstraintDependentParameters( #ifdef DEBUG_BLOCK_CONSTRAINT for (size_t i = 0; i < groups.size(); i++) { - Base::Console().Log("\nDepParams: Group %d:", i); + Base::Console().log("\nDepParams: Group %d:", i); for (size_t j = 0; j < groups[i].size(); j++) { - Base::Console().Log( + Base::Console().log( "\n Param=%x ,GeoId=%d, GeoPos=%d", param2geoelement.find(*std::next(groups[i].begin(), j))->first, param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, @@ -442,7 +442,7 @@ bool Sketch::analyseBlockedConstraintDependentParameters( params_to_block.push_back(thisparam); prop_groups[i].blocking_param_in_group = thisparam; #ifdef DEBUG_BLOCK_CONSTRAINT - Base::Console().Log("\nTentatively blocking group %d, with param=%x", i, thisparam); + Base::Console().log("\nTentatively blocking group %d, with param=%x", i, thisparam); #endif // DEBUG_BLOCK_CONSTRAINT break; } @@ -2388,7 +2388,7 @@ int Sketch::addConstraints(const std::vector& ConstraintList) if (rtn == -1) { int humanconstraintid = cid + 1; - Base::Console().Error("Sketcher constraint number %d is malformed!\n", + Base::Console().error("Sketcher constraint number %d is malformed!\n", humanconstraintid); MalformedConstraints.push_back(humanconstraintid); } @@ -2411,7 +2411,7 @@ int Sketch::addConstraints(const std::vector& ConstraintList, if (rtn == -1) { int humanconstraintid = cid + 1; - Base::Console().Error("Sketcher constraint number %d is malformed!\n", + Base::Console().error("Sketcher constraint number %d is malformed!\n", humanconstraintid); MalformedConstraints.push_back(humanconstraintid); } @@ -2803,7 +2803,7 @@ int Sketch::addPerpendicularConstraint(int geoId1, int geoId2) } } - Base::Console().Warning("Perpendicular constraints between %s and %s are not supported.\n", + Base::Console().warning("Perpendicular constraints between %s and %s are not supported.\n", nameByType(Geoms[geoId1].type), nameByType(Geoms[geoId2].type)); return -1; @@ -2863,7 +2863,7 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().Error("Direct tangency constraint between line and B-spline is not " + Base::Console().error("Direct tangency constraint between line and B-spline is not " "supported. Use tangent-via-point instead."); return -1; } @@ -2877,7 +2877,7 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().Error("Direct tangency constraint between circle and ellipse is not " + Base::Console().error("Direct tangency constraint between circle and ellipse is not " "supported. Use tangent-via-point instead."); return -1; } @@ -2888,24 +2888,24 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().Error("Direct tangency constraint between circle and B-spline is not " + Base::Console().error("Direct tangency constraint between circle and B-spline is not " "supported. Use tangent-via-point instead."); return -1; } } else if (Geoms[geoId1].type == Ellipse) { if (Geoms[geoId2].type == Circle) { - Base::Console().Error("Direct tangency constraint between circle and ellipse is not " + Base::Console().error("Direct tangency constraint between circle and ellipse is not " "supported. Use tangent-via-point instead."); return -1; } else if (Geoms[geoId2].type == Arc) { - Base::Console().Error("Direct tangency constraint between arc and ellipse is not " + Base::Console().error("Direct tangency constraint between arc and ellipse is not " "supported. Use tangent-via-point instead."); return -1; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().Error("Direct tangency constraint between ellipse and B-spline is not " + Base::Console().error("Direct tangency constraint between ellipse and B-spline is not " "supported. Use tangent-via-point instead."); return -1; } @@ -2919,7 +2919,7 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().Error("Direct tangency constraint between arc and ellipse is not " + Base::Console().error("Direct tangency constraint between arc and ellipse is not " "supported. Use tangent-via-point instead."); return -1; } @@ -2930,13 +2930,13 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().Error("Direct tangency constraint between arc and B-spline is not " + Base::Console().error("Direct tangency constraint between arc and B-spline is not " "supported. Use tangent-via-point instead."); return -1; } } else if (Geoms[geoId1].type == BSpline) { - Base::Console().Error("Direct tangency constraint including B-splines is not " + Base::Console().error("Direct tangency constraint including B-splines is not " "supported. Use tangent-via-point instead."); return -1; } @@ -2958,13 +2958,13 @@ int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, knotindex = std::distance(b.knotpointGeoids.begin(), knotIt); if (knotindex >= b.knots.size()) { - Base::Console().Error("addConstraint: Knot index out-of-range!\n"); + Base::Console().error("addConstraint: Knot index out-of-range!\n"); return -1; } if (b.mult[knotindex] >= b.degree) { if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { - Base::Console().Error("addTangentLineAtBSplineKnotConstraint: cannot set constraint " + Base::Console().error("addTangentLineAtBSplineKnotConstraint: cannot set constraint " "when B-spline slope is discontinuous at knot!\n"); return -1; } @@ -2977,7 +2977,7 @@ int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, // nullptr, Tangent, true); // For now we just throw an error. - Base::Console().Error( + Base::Console().error( "addTangentLineAtBSplineKnotConstraint: This method cannot set tangent constraint " "at end knots of a B-spline. Please constrain the start/end points instead.\n"); return -1; @@ -3011,13 +3011,13 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, knotindex = std::distance(b.knotpointGeoids.begin(), knotIt); if (knotindex >= b.knots.size()) { - Base::Console().Error("addConstraint: Knot index out-of-range!\n"); + Base::Console().error("addConstraint: Knot index out-of-range!\n"); return -1; } if (b.mult[knotindex] >= b.degree) { if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { - Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: cannot set " + Base::Console().error("addTangentLineEndpointAtBSplineKnotConstraint: cannot set " "constraint when B-spline slope is discontinuous at knot!\n"); return -1; } @@ -3030,7 +3030,7 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, // nullptr, Tangent, true); // For now we just throw an error. - Base::Console().Error("addTangentLineEndpointAtBSplineKnotConstraint: This method " + Base::Console().error("addTangentLineEndpointAtBSplineKnotConstraint: This method " "cannot set tangent constraint at end knots of a B-spline. " "Please constrain the start/end points instead.\n"); return -1; @@ -3082,14 +3082,14 @@ int Sketch::addAngleAtPointConstraint(int geoId1, } if (Geoms[geoId1].type == Point || Geoms[geoId2].type == Point) { - Base::Console().Error("addAngleAtPointConstraint: one of the curves is a point!\n"); + Base::Console().error("addAngleAtPointConstraint: one of the curves is a point!\n"); return -1; } GCS::Curve* crv1 = getGCSCurveByGeoId(geoId1); GCS::Curve* crv2 = getGCSCurveByGeoId(geoId2); if (!crv1 || !crv2) { - Base::Console().Error("addAngleAtPointConstraint: getGCSCurveByGeoId returned NULL!\n"); + Base::Console().error("addAngleAtPointConstraint: getGCSCurveByGeoId returned NULL!\n"); return -1; } @@ -3102,7 +3102,7 @@ int Sketch::addAngleAtPointConstraint(int geoId1, } if (pointId < 0 || pointId >= int(Points.size())) { - Base::Console().Error("addAngleAtPointConstraint: point index out of range.\n"); + Base::Console().error("addAngleAtPointConstraint: point index out of range.\n"); return -1; } GCS::Point& p = Points[pointId]; @@ -3110,7 +3110,7 @@ int Sketch::addAngleAtPointConstraint(int geoId1, if (e2e) { // we need second point int pointId = getPointId(geoId2, pos2); if (pointId < 0 || pointId >= int(Points.size())) { - Base::Console().Error("addAngleAtPointConstraint: point index out of range.\n"); + Base::Console().error("addAngleAtPointConstraint: point index out of range.\n"); return -1; } p2 = &(Points[pointId]); @@ -3638,7 +3638,7 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) } } - Base::Console().Warning("Equality constraints between %s and %s are not supported.\n", + Base::Console().warning("Equality constraints between %s and %s are not supported.\n", nameByType(Geoms[geoId1].type), nameByType(Geoms[geoId2].type)); return -1; @@ -3798,7 +3798,7 @@ int Sketch::addSnellsLawConstraint(int geoIdRay1, geoIdBnd = checkGeoId(geoIdBnd); if (Geoms[geoIdRay1].type == Point || Geoms[geoIdRay2].type == Point) { - Base::Console().Error("addSnellsLawConstraint: point is not a curve. Not applicable!\n"); + Base::Console().error("addSnellsLawConstraint: point is not a curve. Not applicable!\n"); return -1; } @@ -3806,7 +3806,7 @@ int Sketch::addSnellsLawConstraint(int geoIdRay1, GCS::Curve* ray2 = getGCSCurveByGeoId(geoIdRay2); GCS::Curve* boundary = getGCSCurveByGeoId(geoIdBnd); if (!ray1 || !ray2 || !boundary) { - Base::Console().Error("addSnellsLawConstraint: getGCSCurveByGeoId returned NULL!\n"); + Base::Console().error("addSnellsLawConstraint: getGCSCurveByGeoId returned NULL!\n"); return -1; } @@ -3814,7 +3814,7 @@ int Sketch::addSnellsLawConstraint(int geoIdRay1, int pointId2 = getPointId(geoIdRay2, posRay2); if (pointId1 < 0 || pointId1 >= int(Points.size()) || pointId2 < 0 || pointId2 >= int(Points.size())) { - Base::Console().Error("addSnellsLawConstraint: point index out of range.\n"); + Base::Console().error("addSnellsLawConstraint: point index out of range.\n"); return -1; } GCS::Point& p1 = Points[pointId1]; @@ -4316,7 +4316,7 @@ bool Sketch::updateGeometry() ++i; } catch (Base::Exception& e) { - Base::Console().Error("Updating geometry: Error build geometry(%d): %s\n", i, e.what()); + Base::Console().error("Updating geometry: Error build geometry(%d): %s\n", i, e.what()); return false; } } @@ -4594,7 +4594,7 @@ int Sketch::solve() if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s-T:%s\n", + Base::Console().log("Sketcher::Solve()-%s-T:%s\n", solvername.c_str(), Base::TimeElapsed::diffTime(start_time, end_time).c_str()); } @@ -4646,7 +4646,7 @@ int Sketch::internalSolve(std::string& solvername, int level) if (!valid_solution) { GCSsys.undoSolution(); updateGeometry(); - Base::Console().Warning("Invalid solution from %s solver.\n", solvername.c_str()); + Base::Console().warning("Invalid solution from %s solver.\n", solvername.c_str()); } else { updateNonDrivingConstraints(); @@ -4656,7 +4656,7 @@ int Sketch::internalSolve(std::string& solvername, int level) valid_solution = false; if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n", + Base::Console().log("Sketcher::Solve()-%s- Failed!! Falling back...\n", solvername.c_str()); } } @@ -4706,7 +4706,7 @@ int Sketch::internalSolve(std::string& solvername, int level) if (!valid_solution) { GCSsys.undoSolution(); updateGeometry(); - Base::Console().Warning("Invalid solution from %s solver.\n", + Base::Console().warning("Invalid solution from %s solver.\n", solvername.c_str()); ret = GCS::SuccessfulSolutionInvalid; } @@ -4718,7 +4718,7 @@ int Sketch::internalSolve(std::string& solvername, int level) valid_solution = false; if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().Log("Sketcher::Solve()-%s- Failed!! Falling back...\n", + Base::Console().log("Sketcher::Solve()-%s- Failed!! Falling back...\n", solvername.c_str()); } } @@ -4729,19 +4729,19 @@ int Sketch::internalSolve(std::string& solvername, int level) if (valid_solution) { if (soltype == 1) { - Base::Console().Log("Important: the LevenbergMarquardt solver succeeded where " + Base::Console().log("Important: the LevenbergMarquardt solver succeeded where " "the DogLeg solver had failed.\n"); } else if (soltype == 2) { - Base::Console().Log("Important: the BFGS solver succeeded where the DogLeg and " + Base::Console().log("Important: the BFGS solver succeeded where the DogLeg and " "LevenbergMarquardt solvers have failed.\n"); } else if (soltype == 3) { - Base::Console().Log("Important: the SQP solver succeeded where all single " + Base::Console().log("Important: the SQP solver succeeded where all single " "subsystem solvers have failed.\n"); } else if (soltype > 0) { - Base::Console().Log("All solvers failed.\n"); + Base::Console().log("All solvers failed.\n"); } break; diff --git a/src/Mod/Sketcher/App/SketchAnalysis.cpp b/src/Mod/Sketcher/App/SketchAnalysis.cpp index 81d20781ef..a0275bdd5d 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.cpp +++ b/src/Mod/Sketcher/App/SketchAnalysis.cpp @@ -596,7 +596,7 @@ void SketchAnalysis::analyseMissingPointOnPointCoincident(double angleprecision) } } catch (Base::Exception&) { - Base::Console().Warning("Point-On-Point Coincidence analysis: unable to obtain " + Base::Console().warning("Point-On-Point Coincidence analysis: unable to obtain " "derivative. Detection ignored.\n"); continue; } @@ -930,7 +930,7 @@ int SketchAnalysis::autoconstraint(double precision, // STAGE 3: Equality constraint detection int ne = detectMissingEqualityConstraints(precision); - Base::Console().Log("Constraints: Vertical/Horizontal: %d found. " + Base::Console().log("Constraints: Vertical/Horizontal: %d found. " "Point-on-point: %d. Equality: %d\n", nhv, nc, diff --git a/src/Mod/Sketcher/App/SketchObject.cpp b/src/Mod/Sketcher/App/SketchObject.cpp index eb95bdfab4..0cec70f7ff 100644 --- a/src/Mod/Sketcher/App/SketchObject.cpp +++ b/src/Mod/Sketcher/App/SketchObject.cpp @@ -278,7 +278,7 @@ App::DocumentObjectExecReturn* SketchObject::execute() catch (const Base::Exception&) { // 9/16/24: We used to clear the constraints here, but we no longer want to do that // as missing reference geometry is not considered an error while we sort out sketcher UI. - // Base::Console().Error("%s\nClear constraints to external geometry\n", e.what()); + // Base::Console().error("%s\nClear constraints to external geometry\n", e.what()); // we cannot trust the constraints of external geometries, so remove them // delConstraintsToExternal(); } @@ -426,7 +426,7 @@ const std::map SketchObject::getInternalElementMap() co if (!internalElementMap.empty() || !MakeInternals.getValue()) return internalElementMap; - auto internalShape = InternalShape.getShape(); + const auto& internalShape = InternalShape.getShape(); auto shape = Shape.getShape().located(TopLoc_Location()); if (!internalShape.isNull() && !shape.isNull()) { std::vector names; @@ -577,13 +577,13 @@ int SketchObject::solve(bool updateGeoAfterSolving /*=true*/) } if (lastHasMalformedConstraints) { - Base::Console().Error( + Base::Console().error( this->getFullLabel(), QT_TRANSLATE_NOOP("Notifications", "The Sketch has malformed constraints!") "\n"); } if (lastHasPartialRedundancies) { - Base::Console().Warning( + Base::Console().warning( this->getFullLabel(), QT_TRANSLATE_NOOP("Notifications", "The Sketch has partially redundant constraints!") "\n"); @@ -1142,7 +1142,7 @@ void SketchObject::reverseAngleConstraintToSupplementary(Constraint* constr, int // Edit the expression if any, else modify constraint value directly if (constraintHasExpression(constNum)) { std::string expression = getConstraintExpression(constNum); - setConstraintExpression(constNum, reverseAngleConstraintExpression(expression)); + setConstraintExpression(constNum, std::move(reverseAngleConstraintExpression(expression))); } else { double actAngle = constr->getValue(); @@ -1185,10 +1185,10 @@ void SketchObject::setConstraintExpression(int constNum, const std::string& newE if (info.expression) { try { std::shared_ptr expr(App::Expression::parse(this, newExpression)); - setExpression(path, expr); + setExpression(path, std::move(expr)); } catch (const Base::Exception&) { - Base::Console().Error("Failed to set constraint expression."); + Base::Console().error("Failed to set constraint expression."); } } } @@ -1353,7 +1353,7 @@ int SketchObject::diagnoseAdditionalConstraints( return lastDoF; } -int SketchObject::moveGeometries(std::vector geoEltIds, const Base::Vector3d& toPoint, bool relative, +int SketchObject::moveGeometries(const std::vector& geoEltIds, const Base::Vector3d& toPoint, bool relative, bool updateGeoBeforeMoving) { @@ -1935,7 +1935,7 @@ int SketchObject::delGeometriesExclusiveList(const std::vector& GeoIds) void SketchObject::replaceGeometries(std::vector oldGeoIds, std::vector& newGeos) { - auto vals = getInternalGeometry(); + auto& vals = getInternalGeometry(); auto newVals(vals); if (std::any_of(oldGeoIds.begin(), oldGeoIds.end(), [](auto geoId) { @@ -2493,7 +2493,7 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge } } } - delConstraints(deleteme, false); + delConstraints(std::move(deleteme), false); return; } @@ -3047,7 +3047,7 @@ bool getIntersectionParameter(const Part::Geometry* geo, curve->closestParameter(point, pointParam); } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); return false; } @@ -3449,7 +3449,7 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) addConstraint(std::move(newConstr)); }; - delConstraints(idsOfOldConstraints, false); + delConstraints(std::move(idsOfOldConstraints), false); if (!isOriginalCurvePeriodic) { transferConstraints(GeoId, PointPos::start, newIds.front(), PointPos::start, true); @@ -3808,7 +3808,7 @@ int SketchObject::split(int GeoId, const Base::Vector3d& point) solve(); } - delConstraints(idsOfOldConstraints); + delConstraints(std::move(idsOfOldConstraints)); addConstraints(newConstraints); for (auto& cons : newConstraints) { @@ -4000,7 +4000,7 @@ bool SketchObject::isExternalAllowed(App::Document* pDoc, App::DocumentObject* p } } catch (Base::Exception& e) { - Base::Console().Warning( + Base::Console().warning( "Probably, there is a circular reference in the document. Error: %s\n", e.what()); return true;// prohibiting this reference won't remove the problem anyway... } @@ -4072,7 +4072,7 @@ bool SketchObject::isCarbonCopyAllowed(App::Document* pDoc, App::DocumentObject* } } catch (Base::Exception& e) { - Base::Console().Warning( + Base::Console().warning( "Probably, there is a circular reference in the document. Error: %s\n", e.what()); return true;// prohibiting this reference won't remove the problem anyway... } @@ -4603,7 +4603,7 @@ std::vector SketchObject::getSymmetric(const std::vector& isStartEndInverted.insert(std::make_pair(geoId, false)); } else { - Base::Console().Error("Unsupported Geometry!! Just copying it.\n"); + Base::Console().error("Unsupported Geometry!! Just copying it.\n"); isStartEndInverted.insert(std::make_pair(geoId, false)); } @@ -4624,7 +4624,7 @@ std::vector SketchObject::getSymmetric(const std::vector& } else { if (refPosId == Sketcher::PointPos::none) { - Base::Console().Error("Wrong PointPosId.\n"); + Base::Console().error("Wrong PointPosId.\n"); return {}; } refpoint = getPoint(georef, refPosId); @@ -4762,7 +4762,7 @@ std::vector SketchObject::getSymmetric(const std::vector& isStartEndInverted.insert(std::make_pair(geoId, false)); } else { - Base::Console().Error("Unsupported Geometry!! Just copying it.\n"); + Base::Console().error("Unsupported Geometry!! Just copying it.\n"); isStartEndInverted.insert(std::make_pair(geoId, false)); } @@ -5023,7 +5023,7 @@ int SketchObject::addCopy(const std::vector& geoIdList, const Base::Vector3 iterfirstpoint = scp; } else { - Base::Console().Error("Unsupported Geometry!! Just skipping it.\n"); + Base::Console().error("Unsupported Geometry!! Just skipping it.\n"); continue; } @@ -6413,7 +6413,7 @@ bool SketchObject::convertToNURBS(int GeoId) } } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); // revert to original values return false; } @@ -6499,7 +6499,7 @@ bool SketchObject::increaseBSplineDegree(int GeoId, int degreeincrement /*= 1*/) bspline->increaseDegree(cdegree + degreeincrement); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); return false; } @@ -6545,7 +6545,7 @@ bool SketchObject::decreaseBSplineDegree(int GeoId, int degreedecrement /*= 1*/) bspline->approximate(Precision::Confusion(), 20, maxdegree, GeomAbs_C0); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); return false; } @@ -6644,7 +6644,7 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m } } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); return false; } @@ -6789,7 +6789,7 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) bspline->insertKnot(param, multiplicity); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); return false; } @@ -6972,7 +6972,7 @@ int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) if (Objects.size() != SubElements.size() || sObjects.size() != sSubElements.size()) { assert(0 /*counts of objects and subelements in external geometry links do not match*/); - Base::Console().Error("Internal error: counts of objects and subelements in external " + Base::Console().error("Internal error: counts of objects and subelements in external " "geometry links do not match\n"); return -1; } @@ -6982,7 +6982,7 @@ int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) int i = 0; for (auto& obj : Objects) { if (obj == sobj && SubElements[i] == sSubElements[si]) { - Base::Console().Error( + Base::Console().error( "Link to %s already exists in this sketch. Delete the link and try again\n", sSubElements[si].c_str()); return -1; @@ -7003,7 +7003,7 @@ int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) rebuildExternalGeometry(); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); // revert to original values ExternalGeometry.setValues(originalObjects, originalSubElements); return -1; @@ -7083,7 +7083,7 @@ int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) * * if (expr_info.expression)*/ // App::Expression * expr = parse(this, const std::string& buffer); - setExpression(Constraints.createPath(nextcid), expr); + setExpression(Constraints.createPath(nextcid), std::move(expr)); } } } @@ -7173,7 +7173,7 @@ int SketchObject::addExternal(App::DocumentObject *Obj, const char* SubName, boo if (Objects.size() != SubElements.size()) { assert(0 /*counts of objects and subelements in external geometry links do not match*/); - Base::Console().Error("Internal error: counts of objects and subelements in external " + Base::Console().error("Internal error: counts of objects and subelements in external " "geometry links do not match\n"); return -1; } @@ -7184,7 +7184,7 @@ int SketchObject::addExternal(App::DocumentObject *Obj, const char* SubName, boo if (Types[i] == (int)ExtType::Both || (Types[i] == (int)ExtType::Projection && !intersection) || (Types[i] == (int)ExtType::Intersection && intersection)) { - Base::Console().Error("Link to %s already exists in this sketch.\n", SubName); + Base::Console().error("Link to %s already exists in this sketch.\n", SubName); return -1; } // Case where projections are already there when adding intersections. @@ -7209,7 +7209,7 @@ int SketchObject::addExternal(App::DocumentObject *Obj, const char* SubName, boo rebuildExternalGeometry(ext); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); // revert to original values ExternalGeometry.setValues(originalObjects, originalSubElements); return -1; @@ -7401,7 +7401,7 @@ int SketchObject::delAllExternal() rebuildExternalGeometry(); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); // revert to original values ExternalGeometry.setValues(originalObjects, originalSubElements); for (Constraint* it : newConstraints) @@ -7779,12 +7779,12 @@ void SketchObject::validateExternalLinks() } catch (Base::IndexError& indexError) { removeBadLink = true; - Base::Console().Warning( + Base::Console().warning( this->getFullLabel(), (indexError.getMessage() + "\n").c_str()); } catch (Base::ValueError& valueError) { removeBadLink = true; - Base::Console().Warning( + Base::Console().warning( this->getFullLabel(), (valueError.getMessage() + "\n").c_str()); } catch (Standard_Failure&) { @@ -8540,7 +8540,7 @@ std::vector projectShape(const TopoDS_Shape& inShape, const gp_Ax3 brep_hlr->Hide(); } catch (const Standard_Failure& e) { - Base::Console().Error("GO::projectShape - OCC error - %s - while projecting shape\n", + Base::Console().error("GO::projectShape - OCC error - %s - while projecting shape\n", e.GetMessageString()); throw Base::RuntimeError("SketchObject::projectShape - OCC error"); } @@ -9262,7 +9262,7 @@ const std::vector> SketchObject::getCoincidenc std::map tmp; tmp.insert(std::pair(constr->First, constr->FirstPos)); tmp.insert(std::pair(constr->Second, constr->SecondPos)); - coincidenttree.push_back(tmp); + coincidenttree.push_back(std::move(tmp)); } else if (firstpresentin != -1) { // add to existing group @@ -9955,7 +9955,7 @@ void SketchObject::onChanged(const App::Property* prop) acceptGeometry(); } else { - Base::Console().Error( + Base::Console().error( this->getFullLabel() + " SketchObject::onChanged ", QT_TRANSLATE_NOOP("Notifications", "Unmanaged change of Geometry Property " "results in invalid constraint indices") "\n"); @@ -9986,7 +9986,7 @@ void SketchObject::onChanged(const App::Property* prop) } } else { - Base::Console().Error( + Base::Console().error( this->getFullLabel() + " SketchObject::onChanged ", QT_TRANSLATE_NOOP("Notifications", "Unmanaged change of Constraint " "Property results in invalid constraint indices") "\n"); @@ -10116,7 +10116,7 @@ void SketchObject::onChanged(const App::Property* prop) delete res; } } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to recompute " << ExpressionEngine.getFullName() << ": " << e.what()); // NOLINT } @@ -10368,7 +10368,7 @@ bool SketchObject::getBlockedState(const Constraint* cstr, bool& blockedstate) c void SketchObject::onDocumentRestored() { try { - restoreFinished(); + onSketchRestore(); Part::Part2DObject::onDocumentRestored(); } catch (...) { @@ -10376,6 +10376,12 @@ void SketchObject::onDocumentRestored() } void SketchObject::restoreFinished() +{ + App::DocumentObject::restoreFinished(); + onSketchRestore(); +} + +void SketchObject::onSketchRestore() { try { migrateSketch(); @@ -10426,7 +10432,7 @@ void SketchObject::restoreFinished() } } } catch (Base::Exception &e) { - e.ReportException(); + e.reportException(); FC_ERR("Error while restoring " << getFullName()); } catch (...) { } @@ -10614,7 +10620,7 @@ void SketchObject::migrateSketch() Constraints.setValues(std::move(newconstraints)); - Base::Console().Critical( + Base::Console().critical( this->getFullName(), QT_TRANSLATE_NOOP("Notifications", "Parabolas were migrated. Migrated files won't open in previous " @@ -10675,13 +10681,13 @@ int SketchObject::changeConstraintsLocking(bool bLock) cntSuccess++; newVals[i] = constNew; - Base::Console().Log("Constraint%i will be affected\n", i + 1); + Base::Console().log("Constraint%i will be affected\n", i + 1); } } this->Constraints.setValues(std::move(newVals)); - Base::Console().Log("ChangeConstraintsLocking: affected %i of %i tangent/perp constraints\n", + Base::Console().log("ChangeConstraintsLocking: affected %i of %i tangent/perp constraints\n", cntSuccess, cntToBeAffected); @@ -10768,13 +10774,13 @@ int SketchObject::port_reversedExternalArcs(bool justAnalyze) if (affected) { cntToBeAffected++; newVals[ic] = constNew; - Base::Console().Log("Constraint%i will be affected\n", ic + 1); + Base::Console().log("Constraint%i will be affected\n", ic + 1); }; } if (!justAnalyze) { this->Constraints.setValues(std::move(newVals)); - Base::Console().Log("Swapped start/end of reversed external arcs in %i constraints\n", + Base::Console().log("Swapped start/end of reversed external arcs in %i constraints\n", cntToBeAffected); } @@ -10880,7 +10886,7 @@ bool SketchObject::AutoLockTangencyAndPerpty(Constraint* cstr, bool bForce, bool } catch (Base::Exception& e) { // failure to determine tangency type is not a big deal, so a warning. - Base::Console().Warning("Error in AutoLockTangency. %s \n", e.what()); + Base::Console().warning("Error in AutoLockTangency. %s \n", e.what()); return false; } return true; @@ -11072,7 +11078,7 @@ std::vector SketchObject::getElementTypes(bool all) const void SketchObject::setExpression(const App::ObjectIdentifier& path, std::shared_ptr expr) { - DocumentObject::setExpression(path, expr); + DocumentObject::setExpression(path, std::move(expr)); if (noRecomputes) { // if we do not have a recompute, the sketch must be solved to update the DoF of the solver, @@ -11086,7 +11092,7 @@ void SketchObject::setExpression(const App::ObjectIdentifier& path, } } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to recompute " << ExpressionEngine.getFullName() << ": " << e.what()); } solve(); @@ -11589,7 +11595,7 @@ int SketchObject::renameConstraint(int GeoId, std::string name) Base::StateLocker lock(managedoperation, true); Constraint* copy = item->clone(); - copy->Name = name; + copy->Name = std::move(name); Constraints.set1Value(GeoId, copy); delete copy; diff --git a/src/Mod/Sketcher/App/SketchObject.h b/src/Mod/Sketcher/App/SketchObject.h index 4d17218403..7e70270427 100644 --- a/src/Mod/Sketcher/App/SketchObject.h +++ b/src/Mod/Sketcher/App/SketchObject.h @@ -354,7 +354,7 @@ public: /// toggle the driving status of this constraint int toggleVirtualSpace(int ConstrId); /// move this point to a new location and solve - int moveGeometries(std::vector geoEltIds, + int moveGeometries(const std::vector& geoEltIds, const Base::Vector3d& toPoint, bool relative = false, bool updateGeoBeforeMoving = false); @@ -917,6 +917,7 @@ protected: void onDocumentRestored() override; void restoreFinished() override; + void onSketchRestore(); std::string validateExpression(const App::ObjectIdentifier& path, std::shared_ptr expr); diff --git a/src/Mod/Sketcher/App/SketchObjectSF.cpp b/src/Mod/Sketcher/App/SketchObjectSF.cpp index 87da13e326..52a7adc063 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSF.cpp @@ -50,7 +50,7 @@ short SketchObjectSF::mustExecute() const App::DocumentObjectExecReturn* SketchObjectSF::execute() { - Base::Console().Warning( + Base::Console().warning( "%s: This feature is deprecated and won't be longer supported in future FreeCAD versions\n", this->getNameInDocument()); // do nothing diff --git a/src/Mod/Sketcher/App/planegcs/GCS.cpp b/src/Mod/Sketcher/App/planegcs/GCS.cpp index bc63d84608..a5b02b86bc 100644 --- a/src/Mod/Sketcher/App/planegcs/GCS.cpp +++ b/src/Mod/Sketcher/App/planegcs/GCS.cpp @@ -302,7 +302,7 @@ SolverReportingManager& SolverReportingManager::Manager() void SolverReportingManager::LogToConsole(const std::string& str) { - Base::Console().Log(str.c_str()); + Base::Console().log(str.c_str()); } void SolverReportingManager::LogToFile(const std::string& str) @@ -2086,7 +2086,7 @@ int System::solve_BFGS(SubSystem* subsys, bool /*isFine*/, bool isRedundantsolvi << ", maxIter: " << maxIterNumber << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } double divergingLim = 1e6 * err + 1e12; @@ -2101,7 +2101,7 @@ int System::solve_BFGS(SubSystem* subsys, bool /*isFine*/, bool isRedundantsolvi << ", err: " << err << ", h_norm: " << h_norm << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } break; } @@ -2113,7 +2113,7 @@ int System::solve_BFGS(SubSystem* subsys, bool /*isFine*/, bool isRedundantsolvi << ", err: " << err << ", divergingLim: " << divergingLim << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } break; } @@ -2150,7 +2150,7 @@ int System::solve_BFGS(SubSystem* subsys, bool /*isFine*/, bool isRedundantsolvi << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } } @@ -2213,7 +2213,7 @@ int System::solve_LM(SubSystem* subsys, bool isRedundantsolving) << ", xsize: " << xsize << ", maxIter: " << maxIterNumber << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } double nu = 2, mu = 0; @@ -2332,7 +2332,7 @@ int System::solve_LM(SubSystem* subsys, bool isRedundantsolving) << ", g_inf(eps1): " << g_inf << ", h_norm: " << h_norm << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } } @@ -2385,7 +2385,7 @@ int System::solve_DL(SubSystem* subsys, bool isRedundantsolving) << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } Eigen::VectorXd x(xsize), x_new(xsize); @@ -2542,7 +2542,7 @@ int System::solve_DL(SubSystem* subsys, bool isRedundantsolving) << ", err(divergingLim): " << err << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } // count this iteration and start again @@ -2556,7 +2556,7 @@ int System::solve_DL(SubSystem* subsys, bool isRedundantsolving) stream << "DL: stopcode: " << stop << ((stop == 1) ? ", Success" : ", Failed") << "\n"; const std::string tmp = stream.str(); - Base::Console().Log(tmp.c_str()); + Base::Console().log(tmp.c_str()); } return (stop == 1) ? Success : Failed; @@ -4975,7 +4975,7 @@ int System::diagnose(Algorithm alg) #ifndef EIGEN_SPARSEQR_COMPATIBLE if (qrAlgorithm == EigenSparseQR) { - Base::Console().Warning("SparseQR not supported by you current version of Eigen. It " + Base::Console().warning("SparseQR not supported by you current version of Eigen. It " "requires Eigen 3.2.2 or higher. Falling back to Dense QR\n"); qrAlgorithm = EigenDenseQR; } @@ -5053,7 +5053,7 @@ int System::diagnose(Algorithm alg) auto SolveTime = Base::TimeElapsed::diffTimeF(DenseQR_start_time, DenseQR_end_time); - Base::Console().Log("\nDenseQR - Lapsed Time: %f seconds\n", SolveTime); + Base::Console().log("\nDenseQR - Lapsed Time: %f seconds\n", SolveTime); #endif } @@ -5128,7 +5128,7 @@ int System::diagnose(Algorithm alg) auto SolveTime = Base::TimeElapsed::diffTimeF(SparseQR_start_time, SparseQR_end_time); - Base::Console().Log("\nSparseQR - Lapsed Time: %f seconds\n", SolveTime); + Base::Console().log("\nSparseQR - Lapsed Time: %f seconds\n", SolveTime); #endif } #endif @@ -5658,7 +5658,7 @@ void System::identifyConflictingRedundantConstraints( break; } - Base::Console().Log("Sketcher::RedundantSolving-%s-\n", solvername.c_str()); + Base::Console().log("Sketcher::RedundantSolving-%s-\n", solvername.c_str()); } if (res == Success) { @@ -5673,7 +5673,7 @@ void System::identifyConflictingRedundantConstraints( resetToReference(); if (debugMode == Minimal || debugMode == IterationLevel) { - Base::Console().Log("Sketcher Redundant solving: %d redundants\n", redundant.size()); + Base::Console().log("Sketcher Redundant solving: %d redundants\n", redundant.size()); } // TODO: Figure out why we need to iterate in reverse order and add explanation here. @@ -5692,7 +5692,7 @@ void System::identifyConflictingRedundantConstraints( } if (debugMode == IterationLevel) { - Base::Console().Log("(Partially) Redundant, Group %d, index %d, Tag: %d\n", + Base::Console().log("(Partially) Redundant, Group %d, index %d, Tag: %d\n", i, iterRedundantEntry - conflictGroupsOrig[i].begin(), (*iterRedundantEntry)->getTag()); diff --git a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp index b7cedd992f..2fdb7597d0 100644 --- a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp +++ b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp @@ -99,7 +99,7 @@ PyMOD_INIT_FUNC(SketcherGui) } PyObject* sketcherGuiModule = SketcherGui::initModule(); - Base::Console().Log("Loading GUI of Sketcher module... done\n"); + Base::Console().log("Loading GUI of Sketcher module... done\n"); Gui::BitmapFactory().addPath(QStringLiteral(":/icons/constraints")); Gui::BitmapFactory().addPath(QStringLiteral(":/icons/elements")); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp index ee3f9b5381..81da9dd727 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp @@ -414,7 +414,7 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) // particularly B-spline GeoID might have changed. } catch (const Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); if (e.getTranslatable()) { Gui::TranslatedUserError(Obj, QObject::tr("CAD Kernel Error"), @@ -423,7 +423,7 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) getSelection().clearSelection(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); if (e.getTranslatable()) { Gui::TranslatedUserError(Obj, QObject::tr("Input Error"), @@ -789,7 +789,7 @@ public: // particularly B-spline GeoID might have changed. } catch (const Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); if (e.getTranslatable()) { Gui::TranslatedUserError(Obj, QObject::tr("CAD Kernel Error"), @@ -797,7 +797,7 @@ public: } } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); if (e.getTranslatable()) { Gui::TranslatedUserError(Obj, QObject::tr("Input Error"), diff --git a/src/Mod/Sketcher/Gui/DrawSketchController.h b/src/Mod/Sketcher/Gui/DrawSketchController.h index 9a098826c3..9c53f56f5a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchController.h +++ b/src/Mod/Sketcher/Gui/DrawSketchController.h @@ -358,10 +358,10 @@ public: tryViewValueChanged(onviewparameterindex, value); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); } catch (const std::exception& e) { - Base::Console().Error("C++ exception in onViewValueChanged: %s\n", e.what()); + Base::Console().error("C++ exception in onViewValueChanged: %s\n", e.what()); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h b/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h index f80f62f4f2..177bc6ed5a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h @@ -502,7 +502,7 @@ protected: // RuntimeError exceptions inside of the block above must provide a translatable // message. It is reported both to developer (report view) and user (notifications // area). - Base::Console().Error(e.what()); + Base::Console().error(e.what()); } // Keep the recompute separate so that everything is drawn even if execution fails @@ -514,7 +514,7 @@ protected: // RuntimeError exceptions inside of the block above must provide a translatable // message. It is reported both to developer (report view) and user (notifications // area). - Base::Console().Error(e.what()); + Base::Console().error(e.what()); } return handleContinuousMode(); } @@ -940,7 +940,7 @@ protected: sketchobject->diagnoseAdditionalConstraints(autoConstraints); if (sketchobject->getLastHasRedundancies()) { - Base::Console().Warning( + Base::Console().warning( QT_TRANSLATE_NOOP("Notifications", "Autoconstraints cause redundancy. Removing them") "\n"); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp index c4d0deeb78..7c66b4ac9a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp @@ -173,7 +173,7 @@ CurveConverter::CurveConverter() } catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, // the exception is not propagated - Base::Console().DeveloperError("CurveConverter", + Base::Console().developerError("CurveConverter", "Malformed parameter string: %s\n", e.what()); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h index d2b0f8d516..ac79f17a90 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h @@ -784,7 +784,7 @@ private: // Since it happens very frequently that the interpolation fails // it's sufficient to report this as log message to avoid to pollute // the output window - Base::Console().Log(std::string("drawBSplineToPosition"), "interpolation failed\n"); + Base::Console().log(std::string("drawBSplineToPosition"), "interpolation failed\n"); } } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h index 5137966a49..e4151f601f 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h @@ -142,7 +142,7 @@ private: AutoConstraint::CURVE); } catch (Base::ValueError& e) { - e.ReportException(); + e.reportException(); } } break; default: diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h index c60285d2db..81a13412d3 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h @@ -513,7 +513,7 @@ private: stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } @@ -1070,11 +1070,11 @@ private: /*void printCCeVec() { for (size_t j = 0; j < vCC.size(); j++) { - Base::Console().Warning("curve %d{", j); + Base::Console().warning("curve %d{", j); for (size_t k = 0; k < vCC[j].size(); k++) { - Base::Console().Warning("%d, ", vCC[j][k]); + Base::Console().warning("%d, ", vCC[j][k]); } - Base::Console().Warning("}\n"); + Base::Console().warning("}\n"); } }*/ }; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h index 03be54ee61..118c4c7d2e 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h @@ -129,7 +129,7 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); Gui::NotifyError(sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), QT_TRANSLATE_NOOP("Notifications", "Failed to rotate")); @@ -225,7 +225,7 @@ private: stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h index de54ae32a8..de9d80901f 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h @@ -125,7 +125,7 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); Gui::NotifyError(sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), QT_TRANSLATE_NOOP("Notifications", "Failed to scale")); @@ -219,7 +219,7 @@ private: stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h index dd20bcfb82..bda7afdfbf 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h @@ -145,7 +145,7 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); Gui::NotifyError(sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), QT_TRANSLATE_NOOP("Notifications", "Failed to create symmetry")); @@ -228,7 +228,7 @@ private: stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h index 635a1192ad..403269c5a9 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h @@ -126,7 +126,7 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); Gui::NotifyError(sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), QT_TRANSLATE_NOOP("Notifications", "Failed to translate")); @@ -240,7 +240,7 @@ private: stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().Error("%s\n", e.what()); + Base::Console().error("%s\n", e.what()); } } diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp index d083f133a4..e4bde67259 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp @@ -371,51 +371,40 @@ void EditModeCoinManager::ParameterObserver::updateElementSizeParameters( double viewScalingFactor = hGrp->GetFloat("ViewScalingFactor", 1.0); viewScalingFactor = Base::clamp(viewScalingFactor, 0.5, 5.0); - int markersize = hGrp->GetInt("MarkerSize", 7); + int markerSize = hGrp->GetInt("MarkerSize", 7); int defaultFontSizePixels = Client.defaultApplicationFontSizePixels(); // returns height in pixels, not points int sketcherfontSize = hGrp->GetInt("EditSketcherFontSize", defaultFontSizePixels); - int dpi = Client.getApplicationLogicalDPIX(); + double dpi = Client.getApplicationLogicalDPIX(); + double devicePixelRatio = Client.getDevicePixelRatio(); // simple scaling factor for hardcoded pixel values in the Sketcher - Client.drawingParameters.pixelScalingFactor = viewScalingFactor * dpi - / 96; // 96 ppi is the standard pixel density for which pixel quantities were calculated + Client.drawingParameters.pixelScalingFactor = devicePixelRatio; // About sizes: // SoDatumLabel takes the size in points, not in pixels. This is because it uses QFont // internally. Coin, at least our coin at this time, takes pixels, not points. - // - // DPI considerations: - // With hdpi monitors, the coin font labels do not respect the size passed in pixels: - // https://forum.freecad.org/viewtopic.php?f=3&t=54347&p=467610#p467610 - // https://forum.freecad.org/viewtopic.php?f=10&t=49972&start=40#p467471 - // - // Because I (abdullah) have 96 dpi logical, 82 dpi physical, and I see a 35px font setting for - // a "1" in a datum label as 34px, and I see kilsore and Elyas screenshots showing 41px and 61px - // in higher resolution monitors for the same configuration, I think that coin pixel size has to - // be corrected by the logical dpi of the monitor. The rationale is that: a) it obviously needs - // dpi correction, b) with physical dpi, the ratio of representation between kilsore and me is - // too far away. - // - // This means that the following correction does not have a documented basis, but appears - // necessary so that the Sketcher is usable in HDPI monitors. Client.drawingParameters.coinFontSize = - std::lround(sketcherfontSize * 96.0f / dpi); // this is in pixels - Client.drawingParameters.labelFontSize = std::lround( - sketcherfontSize * 72.0f / dpi); // this is in points, as SoDatumLabel uses points - Client.drawingParameters.constraintIconSize = std::lround(0.8 * sketcherfontSize); + std::lround(sketcherfontSize * devicePixelRatio); // this is in pixels + Client.drawingParameters.labelFontSize = + std::lround(sketcherfontSize * devicePixelRatio * 72.0f + / dpi); // this is in points, as SoDatumLabel uses points + Client.drawingParameters.constraintIconSize = + std::lround(0.8 * sketcherfontSize * devicePixelRatio); - // For marker size the global default is used. - // - // Rationale: - // -> Other WBs use the default value as is - // -> If a user has a HDPI, he will eventually change the value for the other WBs - // -> If we correct the value here in addition, we would get two times a resize - Client.drawingParameters.markerSize = markersize; + + auto supportedsizes = Gui::Inventor::MarkerBitmaps::getSupportedSizes("CIRCLE_LINE"); + auto scaledMarkerSize = std::lround(markerSize * devicePixelRatio); + auto const it = + std::lower_bound(supportedsizes.begin(), supportedsizes.end(), scaledMarkerSize); + if (it != supportedsizes.end()) { + scaledMarkerSize = *it; + } + Client.drawingParameters.markerSize = scaledMarkerSize; Client.updateInventorNodeSizes(); } @@ -486,7 +475,7 @@ void EditModeCoinManager::ParameterObserver::subscribeToParameters() } catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, // the exception is not propagated - Base::Console().DeveloperError("EditModeCoinManager", + Base::Console().developerError("EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); } @@ -514,7 +503,7 @@ void EditModeCoinManager::ParameterObserver::unsubscribeToParameters() catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, the program is not // terminated when calling the noexcept destructor. - Base::Console().DeveloperError("EditModeCoinManager", + Base::Console().developerError("EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); } @@ -726,7 +715,7 @@ EditModeCoinManager::detectPreselection(SoPickedPoint* Point, const SbVec2s& cur return result; } - // Base::Console().Log("Point pick\n"); + // Base::Console().log("Point pick\n"); SoPath* path = Point->getPath(); SoNode* tail = path->getTail(); // Tail is directly the node containing points and curves @@ -1083,6 +1072,11 @@ int EditModeCoinManager::defaultApplicationFontSizePixels() const return ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(viewProvider); } +double EditModeCoinManager::getDevicePixelRatio() const +{ + return ViewProviderSketchCoinAttorney::getDevicePixelRatio(viewProvider); +} + int EditModeCoinManager::getApplicationLogicalDPIX() const { return ViewProviderSketchCoinAttorney::getApplicationLogicalDPIX(viewProvider); diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.h b/src/Mod/Sketcher/Gui/EditModeCoinManager.h index 2d06a995a6..baa7a4801f 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.h @@ -280,6 +280,8 @@ private: int defaultApplicationFontSizePixels() const; + double getDevicePixelRatio() const; + int getApplicationLogicalDPIX() const; void updateInventorNodeSizes(); diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp index 398c2534ab..4d66b3ee9b 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp @@ -1617,13 +1617,13 @@ Restart: } } catch (Base::Exception& e) { - Base::Console().DeveloperError("EditModeConstraintCoinManager", + Base::Console().developerError("EditModeConstraintCoinManager", "Exception during draw: %s\n", e.what()); - e.ReportException(); + e.reportException(); } catch (...) { - Base::Console().DeveloperError("EditModeConstraintCoinManager", + Base::Console().developerError("EditModeConstraintCoinManager", "Exception during draw: unknown\n"); } } @@ -2049,7 +2049,7 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes( const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId((*it)->First); const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId((*it)->Second); if (!geo1 || !geo2) { - Base::Console().DeveloperWarning( + Base::Console().developerWarning( "EditModeConstraintCoinManager", "Tangent constraint references non-existing geometry\n"); } @@ -2100,100 +2100,77 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes( QString EditModeConstraintCoinManager::getPresentationString(const Constraint* constraint) { - std::string nameStr; // name parameter string - QString valueStr; // dimensional value string - std::string unitStr; // the actual unit string - std::string baseUnitStr; // the expected base unit string - double factor; // unit scaling factor, currently not used - Base::UnitSystem unitSys; // current unit system - if (!constraint->isActive) { return QStringLiteral(" "); } - // Get the current name parameter string of the constraint - nameStr = constraint->Name; + /** + * Hide units if + * - user has requested it, + * - is being displayed in the base units, -and- + * - the schema being used has a clear base unit in the first place. + * + * Remove unit string if expected unit string matches actual unit string + * Example code from: Mod/TechDraw/App/DrawViewDimension.cpp:372 + * + * Hide the default length unit + */ + auto fixValueStr = [&](const QString& valueStr, const auto& unitStr) -> std::optional { + if (!constraintParameters.bHideUnits || constraint->Type == Sketcher::Angle) { + return std::nullopt; + } + + const auto baseUnitStr {Base::UnitsApi::getBasicLengthUnit()}; + if (baseUnitStr.empty() || baseUnitStr != unitStr) { + return std::nullopt; + } + + // trailing space or non-dig + const QRegularExpression rxUnits {QString::fromUtf8(" \\D*$")}; + auto vStr = valueStr; + vStr.remove(rxUnits); + return {vStr}; + }; // Get the current value string including units - valueStr = - QString::fromStdString(constraint->getPresentationValue().getUserString(factor, unitStr)); + double factor {}; + std::string unitStr; // the actual unit string + const auto constrPresValue {constraint->getPresentationValue().getUserString(factor, unitStr)}; + auto valueStr = QString::fromStdString(constrPresValue); - // Hide units if user has requested it, is being displayed in the base - // units, and the schema being used has a clear base unit in the first - // place. Otherwise, display units. - if (constraintParameters.bHideUnits && constraint->Type != Sketcher::Angle) { - // Only hide the default length unit. Right now there is not an easy way - // to get that from the Unit system so we have to manually add it here. - // Hopefully this can be added in the future so this code won't have to - // be updated if a new units schema is added. - unitSys = Base::UnitsApi::getSchema(); - - // If this is a supported unit system then define what the base unit is. - switch (unitSys) { - case Base::UnitSystem::SI1: - case Base::UnitSystem::MmMin: - baseUnitStr = "mm"; - break; - - case Base::UnitSystem::SI2: - baseUnitStr = "m"; - break; - - case Base::UnitSystem::ImperialDecimal: - baseUnitStr = "in"; - break; - - case Base::UnitSystem::Centimeters: - baseUnitStr = "cm"; - break; - - default: - // Nothing to do - break; - } - - if (!baseUnitStr.empty()) { - // expected unit string matches actual unit string. remove. - if (baseUnitStr.compare(unitStr) == 0) { - // Example code from: Mod/TechDraw/App/DrawViewDimension.cpp:372 - QRegularExpression rxUnits( - QStringLiteral(" \\D*$")); // space + any non digits at end of string - valueStr.remove(rxUnits); // getUserString(defaultDecimals) without units - } - } + auto fixedValueStr = fixValueStr(valueStr, unitStr).value_or(valueStr); + switch (constraint->Type) { + case Sketcher::Diameter: + fixedValueStr.prepend(QChar(0x2300)); + break; + case Sketcher::Radius: + fixedValueStr.prepend(QLatin1Char('R')); + break; + default: + break; } - if (constraint->Type == Sketcher::Diameter) { - valueStr.prepend(QChar(216)); // Diameter sign - } - else if (constraint->Type == Sketcher::Radius) { - valueStr.prepend(QChar(82)); // Capital letter R + if (!constraintParameters.bShowDimensionalName || constraint->Name.empty()) { + return fixedValueStr; } /** - Create the representation string from the user defined format string - Format options are: - %N - the constraint name parameter - %V - the value of the dimensional constraint, including any unit characters - */ - if (constraintParameters.bShowDimensionalName && !nameStr.empty()) { - QString presentationStr; - if (constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%V")) - || constraintParameters.sDimensionalStringFormat.contains(QLatin1String("%N"))) { - presentationStr = constraintParameters.sDimensionalStringFormat; - presentationStr.replace(QLatin1String("%N"), QString::fromStdString(nameStr)); - presentationStr.replace(QLatin1String("%V"), valueStr); - } - else { - // user defined format string does not contain any valid parameter, using default format - // "%N = %V" - presentationStr = QString::fromStdString(nameStr) + QStringLiteral(" = ") + valueStr; - } + * Create the representation string from the user defined format string + * Format options are: + * %N - the constraint name parameter + * %V - the value of the dimensional constraint, including any unit characters + */ + auto sDimFmt {constraintParameters.sDimensionalStringFormat}; + if (!sDimFmt.contains(QLatin1String("%V")) + && !sDimFmt.contains(QLatin1String("%N"))) { // using default format "%N = %V" - return presentationStr; + return QString::fromStdString(constraint->Name) + QString::fromLatin1(" = ") + valueStr; } - return valueStr; + sDimFmt.replace(QLatin1String("%N"), QString::fromStdString(constraint->Name)); + sDimFmt.replace(QLatin1String("%V"), fixedValueStr); + + return sDimFmt; } std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPickedPoint* Point, @@ -2277,7 +2254,7 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi if (tail != sep->getChild( static_cast(ConstraintNodePosition::FirstIconIndex))) { - Base::Console().Log("SecondIcon\n"); + Base::Console().log("SecondIcon\n"); auto translation2 = static_cast( static_cast(tailFather) @@ -2318,7 +2295,7 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi // Useful code to debug coordinates and bounding boxes that does // not need to be compiled in for any debug operations. - /*Base::Console().Log("Abs(%f,%f),Trans(%f,%f),Coords(%d,%d),iCoords(%f,%f),icon(%d,%d),isize(%d,%d),boundingbox([%d,%d],[%d,%d])\n", + /*Base::Console().log("Abs(%f,%f),Trans(%f,%f),Coords(%d,%d),iCoords(%f,%f),icon(%d,%d),isize(%d,%d),boundingbox([%d,%d],[%d,%d])\n", * absPos[0],absPos[1],trans[0], trans[1], cursorPos[0], * cursorPos[1], iconCoords[0], iconCoords[1], iconX, iconY, * iconSize[0], iconSize[1], @@ -2440,7 +2417,7 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geo // Double-check that we can safely access the Inventor nodes if (constrId >= editModeScenegraphNodes.constrGroup->getNumChildren()) { - Base::Console().DeveloperWarning( + Base::Console().developerWarning( "EditModeConstraintManager", "Can't update constraint icons because view is not in sync with sketch\n"); break; diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp index 2babbd66e0..d1d827a362 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp @@ -431,8 +431,8 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade* geom // it is "just" a visualisation matter OCC could not calculate the curvature // terminating here would mean that the other shapes would not be drawn. // Solution: Report the issue and set dummy curvature to 0 - e.ReportException(); - Base::Console().DeveloperError( + e.reportException(); + Base::Console().developerError( "EditModeGeometryCoinConverter", "Curvature graph for B-spline with GeoId=%d could not be calculated.\n", geoid); // TODO: Fix identification of curve. diff --git a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp index 309f2b6ef4..29f17b61ad 100644 --- a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp @@ -214,8 +214,8 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge // it is "just" a visualisation matter OCC could not calculate the curvature // terminating here would mean that the other shapes would not be drawn. // Solution: Report the issue and set dummy curvature to 0 - e.ReportException(); - Base::Console().DeveloperError( + e.reportException(); + Base::Console().developerError( "EditModeInformationOverlayCoinConverter", "Curvature graph for B-spline with GeoId=%d could not be calculated.\n", geoid); diff --git a/src/Mod/Sketcher/Gui/SketcherSettings.cpp b/src/Mod/Sketcher/Gui/SketcherSettings.cpp index 82ef50a389..17c84fbcc8 100644 --- a/src/Mod/Sketcher/Gui/SketcherSettings.cpp +++ b/src/Mod/Sketcher/Gui/SketcherSettings.cpp @@ -491,8 +491,8 @@ void SketcherSettingsDisplay::onBtnTVApplyClicked(bool) this->ui->checkBoxTVSectionView->isChecked() ? "True" : "False"); } catch (Base::PyException& e) { - Base::Console().DeveloperError("SketcherSettings", "error in onBtnTVApplyClicked:\n"); - e.ReportException(); + Base::Console().developerError("SketcherSettings", "error in onBtnTVApplyClicked:\n"); + e.reportException(); errMsg = QString::fromLatin1(e.what()); } catch (...) { diff --git a/src/Mod/Sketcher/Gui/SnapManager.cpp b/src/Mod/Sketcher/Gui/SnapManager.cpp index 574102257d..ad435cbe91 100644 --- a/src/Mod/Sketcher/Gui/SnapManager.cpp +++ b/src/Mod/Sketcher/Gui/SnapManager.cpp @@ -135,7 +135,7 @@ void SnapManager::ParameterObserver::subscribeToParameters() } catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, // the exception is not propagated - Base::Console().DeveloperError("SnapManager", "Malformed parameter string: %s\n", e.what()); + Base::Console().developerError("SnapManager", "Malformed parameter string: %s\n", e.what()); } } @@ -148,7 +148,7 @@ void SnapManager::ParameterObserver::unsubscribeToParameters() catch (const Base::ValueError& e) { // ensure that if parameter strings are not well-formed, the program is not // terminated when calling the noexcept destructor. - Base::Console().DeveloperError("SnapManager", "Malformed parameter string: %s\n", e.what()); + Base::Console().developerError("SnapManager", "Malformed parameter string: %s\n", e.what()); } } @@ -280,7 +280,7 @@ bool SnapManager::snapToObject(double& x, double& y) pointToOverride = curve->pointAtParameter(pointParam); } catch (Base::CADKernelError& e) { - e.ReportException(); + e.reportException(); return false; } diff --git a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp index 0c7222e8d2..6e9ee2caa5 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp @@ -1105,7 +1105,7 @@ void TaskSketcherConstraints::changeFilteredVisibility(bool show, ActionTarget t processItem = !item->isHidden(); } else if (target == ActionTarget::Selected) { - if (std::ranges::find(selecteditems, item) != selecteditems.end()) + if (selecteditems.contains(item)) processItem = true; } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp index 2a5f3f8ea1..353cc55d7d 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp @@ -217,7 +217,7 @@ void ViewProviderSketch::ParameterObserver::subscribeToParameters() } catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the // exception is not propagated - Base::Console().DeveloperError( + Base::Console().developerError( "ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); } } @@ -239,7 +239,7 @@ void ViewProviderSketch::ParameterObserver::unsubscribeToParameters() } catch (const Base::ValueError& e) {// ensure that if parameter strings are not well-formed, the // exception is not propagated - Base::Console().DeveloperError( + Base::Console().developerError( "ViewProviderSketch", "Malformed parameter string: %s\n", e.what()); } } @@ -917,22 +917,22 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe case STATUS_NONE: { bool done = false; if (preselection.isPreselectPointValid()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; done = true; } else if (preselection.isPreselectCurveValid()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; done = true; } else if (preselection.isCrossPreselected()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; done = true; } else if (!preselection.PreselectConstraintSet.empty()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; done = true; } @@ -978,7 +978,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe switch (Mode) { case STATUS_SELECT_Point: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); // Do selection std::stringstream ss; ss << "Vertex" << preselection.getPreselectionVertexIndex(); @@ -989,7 +989,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Edge: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (preselection.isEdge()) ss << "Edge" << preselection.getPreselectionEdgeIndex(); @@ -1002,7 +1002,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Cross: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); std::stringstream ss; switch (preselection.PreselectCross) { case Preselection::Axes::RootPoint: @@ -1102,19 +1102,19 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe switch (Mode) { case STATUS_NONE: { if (preselection.isPreselectPointValid()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Point; } else if (preselection.isPreselectCurveValid()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Edge; } else if (preselection.isCrossPreselected()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Cross; } else if (!preselection.PreselectConstraintSet.empty()) { - // Base::Console().Log("start dragging, point:%d\n",this->DragPoint); + // Base::Console().log("start dragging, point:%d\n",this->DragPoint); Mode = STATUS_SELECT_Constraint; } } @@ -1133,7 +1133,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Point: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); // Do selection std::stringstream ss; ss << "Vertex" << preselection.getPreselectionVertexIndex(); @@ -1145,7 +1145,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Edge: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); std::stringstream ss; if (preselection.isEdge()) { ss << "Edge" << preselection.getPreselectionEdgeIndex(); @@ -1161,7 +1161,7 @@ bool ViewProviderSketch::mouseButtonPressed(int Button, bool pressed, const SbVe return true; case STATUS_SELECT_Cross: if (pp) { - // Base::Console().Log("Select Point:%d\n",this->DragPoint); + // Base::Console().log("Select Point:%d\n",this->DragPoint); std::stringstream ss; switch (preselection.PreselectCross) { case Preselection::Axes::RootPoint: @@ -1226,7 +1226,7 @@ bool ViewProviderSketch::mouseWheelEvent(int delta, const SbVec2s& cursorPos, void ViewProviderSketch::editDoubleClicked() { if (preselection.isPreselectPointValid()) { - Base::Console().Log("double click point:%d\n", preselection.PreselectPoint); + Base::Console().log("double click point:%d\n", preselection.PreselectPoint); } else if (preselection.isPreselectCurveValid()) { // We cannot do toggleWireSelelection directly here because the released event with @@ -1234,7 +1234,7 @@ void ViewProviderSketch::editDoubleClicked() Mode = STATUS_SELECT_Wire; } else if (preselection.isCrossPreselected()) { - Base::Console().Log("double click cross:%d\n", + Base::Console().log("double click cross:%d\n", static_cast(preselection.PreselectCross)); } else if (!preselection.PreselectConstraintSet.empty()) { @@ -1737,7 +1737,7 @@ void ViewProviderSketch::commitDragMove(double x, double y) } catch (const Base::Exception& e) { getDocument()->abortCommand(); - Base::Console().DeveloperError("ViewProviderSketch", "Drag: %s\n", e.what()); + Base::Console().developerError("ViewProviderSketch", "Drag: %s\n", e.what()); } getDocument()->commitCommand(); @@ -2583,7 +2583,7 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s& startPos, const SbVec2s& } } else { - Base::Console().DeveloperError("ViewProviderSketch::doBoxSelection", + Base::Console().developerError("ViewProviderSketch::doBoxSelection", "Geometry type is unsupported. Selection may be unsynchronised and fail."); } } @@ -3076,13 +3076,13 @@ bool ViewProviderSketch::setEdit(int ModNum) Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException& e) { - Base::Console().DeveloperError( + Base::Console().developerError( "ViewProviderSketch", "setEdit: visibility automation failed with an error: \n"); - e.ReportException(); + e.reportException(); } } catch (Base::PyException&) { - Base::Console().DeveloperWarning( + Base::Console().developerWarning( "ViewProviderSketch", "setEdit: could not import Show module. Visibility automation will not work.\n"); } @@ -3338,7 +3338,7 @@ void ViewProviderSketch::unsetEdit(int ModNum) Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException& e) { - Base::Console().DeveloperError( + Base::Console().developerError( "ViewProviderSketch", "unsetEdit: visibility automation failed with an error: %s \n", e.what()); @@ -3366,7 +3366,7 @@ void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int Mo Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); } catch (Base::PyException& e) { - Base::Console().DeveloperError( + Base::Console().developerError( "ViewProviderSketch", "setEdit: visibility automation failed with an error: %s \n", e.what()); @@ -3473,7 +3473,7 @@ void ViewProviderSketch::camSensCB(void* data, SoSensor*) auto cam = proxyVPrdr->renderMgr->getCamera(); if (cam == nullptr) - Base::Console().DeveloperWarning("ViewProviderSketch", "Camera is nullptr!\n"); + Base::Console().developerWarning("ViewProviderSketch", "Camera is nullptr!\n"); else vp->onCameraChanged(cam); } @@ -3493,7 +3493,7 @@ void ViewProviderSketch::onCameraChanged(SoCamera* cam) auto tmpFactor = orientation.z < 0 ? -1 : 1; if (tmpFactor != viewOrientationFactor) {// redraw only if viewing side changed - Base::Console().Log("Switching side, now %s, redrawing\n", + Base::Console().log("Switching side, now %s, redrawing\n", tmpFactor < 0 ? "back" : "front"); viewOrientationFactor = tmpFactor; draw(); @@ -3556,7 +3556,7 @@ void ViewProviderSketch::deleteSelected() // only one sketch with its subelements are allowed to be selected if (selection.size() != 1) { - Base::Console().DeveloperWarning( + Base::Console().developerWarning( "ViewProviderSketch", "Delete: Selection not restricted to one sketch and its subelements\n"); return; @@ -3633,7 +3633,7 @@ bool ViewProviderSketch::onDelete(const std::vector& subList) Gui::cmdAppObjectArgs(getObject(), "delConstraint(%d)", *rit); } catch (const Base::Exception& e) { - Base::Console().DeveloperError("ViewProviderSketch", "%s\n", e.what()); + Base::Console().developerError("ViewProviderSketch", "%s\n", e.what()); } } @@ -3661,7 +3661,7 @@ bool ViewProviderSketch::onDelete(const std::vector& subList) getObject(), "delConstraintOnPoint(%d,%d)", GeoId, (int)PosId); } catch (const Base::Exception& e) { - Base::Console().DeveloperError("ViewProviderSketch", "%s\n", e.what()); + Base::Console().developerError("ViewProviderSketch", "%s\n", e.what()); } break; } @@ -3685,7 +3685,7 @@ bool ViewProviderSketch::onDelete(const std::vector& subList) Gui::cmdAppObjectArgs(getObject(), "delGeometries([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { - Base::Console().DeveloperError("ViewProviderSketch", "%s\n", e.what()); + Base::Console().developerError("ViewProviderSketch", "%s\n", e.what()); } stream.str(std::string()); @@ -3696,7 +3696,7 @@ bool ViewProviderSketch::onDelete(const std::vector& subList) Gui::cmdAppObjectArgs(getObject(), "delExternal(%d)", *rit); } catch (const Base::Exception& e) { - Base::Console().DeveloperError("ViewProviderSketch", "%s\n", e.what()); + Base::Console().developerError("ViewProviderSketch", "%s\n", e.what()); } } @@ -3969,6 +3969,16 @@ int ViewProviderSketch::defaultFontSizePixels() const return static_cast(metrics.height()); } +qreal ViewProviderSketch::getDevicePixelRatio() const +{ + if (auto activeView = qobject_cast(this->getActiveView())) { + auto glWidget = activeView->getViewer()->getGLWidget(); + return glWidget->devicePixelRatio(); + } + + return QApplication::primaryScreen()->devicePixelRatio(); +} + int ViewProviderSketch::getApplicationLogicalDPIX() const { return int(QApplication::primaryScreen()->logicalDotsPerInchX()); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.h b/src/Mod/Sketcher/Gui/ViewProviderSketch.h index 0cf380a4ad..f78e7ffb00 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.h @@ -857,6 +857,8 @@ private: int defaultFontSizePixels() const; + qreal getDevicePixelRatio() const; + int getApplicationLogicalDPIX() const; double getRotation(SbVec3f pos0, SbVec3f pos1) const; diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h index 9e2296b562..30f8b77bc7 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h @@ -97,6 +97,7 @@ private: static inline QFont getApplicationFont(const ViewProviderSketch& vp); static inline double getRotation(const ViewProviderSketch& vp, SbVec3f pos0, SbVec3f pos1); static inline int defaultApplicationFontSizePixels(const ViewProviderSketch& vp); + static inline double getDevicePixelRatio(const ViewProviderSketch& vp); static inline int getApplicationLogicalDPIX(const ViewProviderSketch& vp); static inline int getViewOrientationFactor(const ViewProviderSketch& vp); @@ -195,6 +196,11 @@ ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(const ViewProvi return vp.defaultFontSizePixels(); } +inline double ViewProviderSketchCoinAttorney::getDevicePixelRatio(const ViewProviderSketch& vp) +{ + return vp.getDevicePixelRatio(); +} + inline int ViewProviderSketchCoinAttorney::getApplicationLogicalDPIX(const ViewProviderSketch& vp) { return vp.getApplicationLogicalDPIX(); diff --git a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp index d6a58b01cd..db92e460c9 100644 --- a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp @@ -62,6 +62,6 @@ PyMOD_INIT_FUNC(Spreadsheet) Spreadsheet::SheetPython::init(); PyObject* mod = Spreadsheet::initModule(); - Base::Console().Log("Loading Spreadsheet module... done\n"); + Base::Console().log("Loading Spreadsheet module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Spreadsheet/App/Cell.cpp b/src/Mod/Spreadsheet/App/Cell.cpp index d5f573af89..a877ee3bf4 100644 --- a/src/Mod/Spreadsheet/App/Cell.cpp +++ b/src/Mod/Spreadsheet/App/Cell.cpp @@ -201,7 +201,7 @@ void Cell::setExpression(App::ExpressionPtr&& expr) restore(reader, true); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_ERR("Failed to restore style of cell " << owner->sheet()->getFullName() << '.' << address.toString() << ": " << e.what()); diff --git a/src/Mod/Spreadsheet/App/Sheet.cpp b/src/Mod/Spreadsheet/App/Sheet.cpp index 52fb12fd1b..cacbe011fa 100644 --- a/src/Mod/Spreadsheet/App/Sheet.cpp +++ b/src/Mod/Spreadsheet/App/Sheet.cpp @@ -116,7 +116,7 @@ Sheet::~Sheet() } catch (...) { // Don't let an exception propagate out of a destructor (calls terminate()) - Base::Console().Error( + Base::Console().error( "clearAll() resulted in an exception when deleting the spreadsheet : %s\n", getNameInDocument()); } @@ -943,7 +943,7 @@ void Sheet::recomputeCell(CellAddress p) cell->setException(e.what()); } else { - e.ReportException(); + e.reportException(); } // Mark as erroneous @@ -1159,7 +1159,7 @@ DocumentObjectExecReturn* Sheet::execute() } catch (std::exception&) { // TODO: evaluate using a more specific exception (not_a_dag) // Cycle detected; flag all with errors - Base::Console().Error("Cyclic dependency detected in spreadsheet : %s\n", + Base::Console().error("Cyclic dependency detected in spreadsheet : %s\n", getNameInDocument()); std::ostringstream ss; ss << "Cyclic dependency"; diff --git a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp index b9b964868c..2a1778cca2 100644 --- a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp +++ b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp @@ -152,6 +152,6 @@ PyMOD_INIT_FUNC(SpreadsheetGui) loadSpreadsheetResource(); PyObject* mod = SpreadsheetGui::initModule(); - Base::Console().Log("Loading GUI of Spreadsheet module... done\n"); + Base::Console().log("Loading GUI of Spreadsheet module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Spreadsheet/Gui/Command.cpp b/src/Mod/Spreadsheet/Gui/Command.cpp index 0137d42272..a9430fcf97 100644 --- a/src/Mod/Spreadsheet/Gui/Command.cpp +++ b/src/Mod/Spreadsheet/Gui/Command.cpp @@ -212,7 +212,7 @@ void CmdSpreadsheetImport::activated(int iMsg) sheet->execute(); } else { - Base::Console().Error(errMsg.c_str()); + Base::Console().error(errMsg.c_str()); return; } } diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp index 797b30b070..2b359cc4dc 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp @@ -267,7 +267,7 @@ void DlgBindSheet::accept() QDialog::accept(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(this, tr("Bind Spreadsheet Cells"), tr("Error:\n") + QString::fromUtf8(e.what())); @@ -296,7 +296,7 @@ void DlgBindSheet::onDiscard() reject(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(this, tr("Unbind cells"), QString::fromUtf8(e.what())); Gui::Command::abortCommand(); } diff --git a/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp b/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp index 67b0fa352a..7ba6e51a1f 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp @@ -112,7 +112,7 @@ App::Property* DlgSheetConf::prepare(CellAddress& from, expr.reset(App::Expression::parse(sheet, exprTxt)); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); FC_THROWM(Base::RuntimeError, "Failed to parse expression for property"); } if (expr->hasComponent() || !expr->isDerivedFrom()) { @@ -276,7 +276,7 @@ void DlgSheetConf::accept() QDialog::accept(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(this, tr("Setup configuration table"), QString::fromUtf8(e.what())); if (commandActive) { Gui::Command::abortCommand(); @@ -334,7 +334,7 @@ void DlgSheetConf::onDiscard() QDialog::accept(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(this, tr("Unsetup configuration table"), QString::fromUtf8(e.what())); if (commandActive) { Gui::Command::abortCommand(); diff --git a/src/Mod/Spreadsheet/Gui/LineEdit.cpp b/src/Mod/Spreadsheet/Gui/LineEdit.cpp index 2b41b8991c..48e5dcae92 100644 --- a/src/Mod/Spreadsheet/Gui/LineEdit.cpp +++ b/src/Mod/Spreadsheet/Gui/LineEdit.cpp @@ -56,13 +56,13 @@ void LineEdit::setDocumentObject(const App::DocumentObject* currentDocObj, bool QPointer active_view = Gui::MainWindow::getInstance()->activeWindow(); if (!active_view) { - Base::Console().DeveloperWarning("LineEdit::setDocumentObject", + Base::Console().developerWarning("LineEdit::setDocumentObject", "The active view is not Spreadsheet"); return; } QPointer zv = active_view->findChild(); if (!zv) { - Base::Console().DeveloperWarning("LineEdit::setDocumentObject", "ZoomableView not found"); + Base::Console().developerWarning("LineEdit::setDocumentObject", "ZoomableView not found"); return; } diff --git a/src/Mod/Spreadsheet/Gui/SheetModel.cpp b/src/Mod/Spreadsheet/Gui/SheetModel.cpp index fc498d73be..9f097aac73 100644 --- a/src/Mod/Spreadsheet/Gui/SheetModel.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetModel.cpp @@ -563,7 +563,7 @@ void SheetModel::setCellData(QModelIndex index, QString str) Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } catch (const Base::Exception& e) { - e.ReportException(); + e.reportException(); Gui::Command::abortCommand(); } } diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp index e0f26d9be2..4232657279 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp @@ -817,7 +817,7 @@ void SheetTableView::pasteClipboard() GetApplication().getActiveDocument()->recompute(); } catch (Base::Exception& e) { - e.ReportException(); + e.reportException(); QMessageBox::critical(Gui::getMainWindow(), QObject::tr("Copy & Paste failed"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp index c4cab0eaed..bfea61b06f 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp @@ -450,7 +450,7 @@ void SheetView::confirmAliasChanged(const QString& text) std::string current_alias; (void)cell->getAlias(current_alias); if (text != QString::fromUtf8(current_alias.c_str())) { - Base::Console().Error("Unable to set alias: %s\n", text.toStdString().c_str()); + Base::Console().error("Unable to set alias: %s\n", text.toStdString().c_str()); } } else { diff --git a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp index 7a098cc490..cc09cbb5ee 100644 --- a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp @@ -122,7 +122,7 @@ void ViewProviderSheet::exportAsFile() sheet->exportToFile(fileName.toStdString(), delim, quote, escape); } else { - Base::Console().Error(errMsg.c_str()); + Base::Console().error(errMsg.c_str()); } } } diff --git a/src/Mod/Spreadsheet/Gui/ZoomableView.cpp b/src/Mod/Spreadsheet/Gui/ZoomableView.cpp index b5a3eae54f..7c6a3b0693 100644 --- a/src/Mod/Spreadsheet/Gui/ZoomableView.cpp +++ b/src/Mod/Spreadsheet/Gui/ZoomableView.cpp @@ -33,14 +33,14 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) , stv {ui->cells} { if (!stv) { - Base::Console().DeveloperWarning("ZoomableView", "Failed to find a SheetTableView object"); + Base::Console().developerWarning("ZoomableView", "Failed to find a SheetTableView object"); deleteLater(); return; } else { QLayoutItem* li_stv = stv->parentWidget()->layout()->replaceWidget(stv, this); if (li_stv == nullptr) { - Base::Console().DeveloperWarning("ZoomableView", + Base::Console().developerWarning("ZoomableView", "Failed to replace the SheetTableView object"); deleteLater(); return; @@ -67,7 +67,7 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) dummySB_v {stv->verticalScrollBar()}, realSB_h {ui->realSB_h}, realSB_v {ui->realSB_v}; if (!dummySB_h || !dummySB_v || !realSB_h || !realSB_v) { - Base::Console().DeveloperWarning("ZoomableView", "Failed to identify the scrollbars"); + Base::Console().developerWarning("ZoomableView", "Failed to identify the scrollbars"); deleteLater(); return; } diff --git a/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp b/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp index 3845342dff..0c82215f86 100644 --- a/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp +++ b/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp @@ -851,7 +851,7 @@ void ColorPickerPopup::showEvent(QShowEvent *) } if (!foundSelected) { - if (items.count() == 0) + if (items.isEmpty()) setFocus(); else widgetAt[0][0]->setFocus(); diff --git a/src/Mod/Start/App/AppStart.cpp b/src/Mod/Start/App/AppStart.cpp index 3bed957bde..075e0b819b 100644 --- a/src/Mod/Start/App/AppStart.cpp +++ b/src/Mod/Start/App/AppStart.cpp @@ -55,6 +55,6 @@ PyObject* initModule() PyMOD_INIT_FUNC(Start) { PyObject* mod = Start::initModule(); - Base::Console().Log("Loading Start module... done\n"); + Base::Console().log("Loading Start module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Start/App/CustomFolderModel.cpp b/src/Mod/Start/App/CustomFolderModel.cpp index 7de6452362..651425f5f9 100644 --- a/src/Mod/Start/App/CustomFolderModel.cpp +++ b/src/Mod/Start/App/CustomFolderModel.cpp @@ -59,13 +59,13 @@ void CustomFolderModel::loadCustomFolder() for (const auto& path : paths) { QDir customFolderDirectory(path); if (!customFolderDirectory.exists()) { - Base::Console().Warning( + Base::Console().warning( "BaseApp/Preferences/Mod/Start/CustomFolder: custom folder %s does not exist\n", customFolderDirectory.absolutePath().toStdString().c_str()); continue; } if (!customFolderDirectory.isReadable()) { - Base::Console().Warning( + Base::Console().warning( "BaseApp/Preferences/Mod/Start/CustomFolder: cannot read custom folder %s\n", customFolderDirectory.absolutePath().toStdString().c_str()); continue; diff --git a/src/Mod/Start/App/DisplayedFilesModel.cpp b/src/Mod/Start/App/DisplayedFilesModel.cpp index 06d631df43..b4d837e5cc 100644 --- a/src/Mod/Start/App/DisplayedFilesModel.cpp +++ b/src/Mod/Start/App/DisplayedFilesModel.cpp @@ -87,7 +87,7 @@ QByteArray loadFCStdThumbnail(const QString& pathToFCStdFile) } } catch (...) { - Base::Console().Log("Failed to load thumbnail for %s\n", pathToFCStdFile.toStdString()); + Base::Console().log("Failed to load thumbnail for %s\n", pathToFCStdFile.toStdString()); } } return {}; @@ -257,7 +257,7 @@ void DisplayedFilesModel::processNewThumbnail(const QString& file, const QByteAr Q_EMIT(dataChanged(qmi, qmi, {static_cast(DisplayedFilesModelRoles::image)})); } else { - Base::Console().Log("Unrecognized path %s\n", file.toStdString()); + Base::Console().log("Unrecognized path %s\n", file.toStdString()); } } } diff --git a/src/Mod/Start/App/ExamplesModel.cpp b/src/Mod/Start/App/ExamplesModel.cpp index c1b8c10334..a295d50c17 100644 --- a/src/Mod/Start/App/ExamplesModel.cpp +++ b/src/Mod/Start/App/ExamplesModel.cpp @@ -44,7 +44,7 @@ void ExamplesModel::loadExamples() beginResetModel(); clear(); if (!_examplesDirectory.isReadable()) { - Base::Console().Warning("Cannot read %s", + Base::Console().warning("Cannot read %s", _examplesDirectory.absolutePath().toStdString().c_str()); } auto entries = _examplesDirectory.entryList(QDir::Filter::Files | QDir::Filter::Readable, diff --git a/src/Mod/Start/App/ThumbnailSource.cpp b/src/Mod/Start/App/ThumbnailSource.cpp index d8d20b2617..b80040c93c 100644 --- a/src/Mod/Start/App/ThumbnailSource.cpp +++ b/src/Mod/Start/App/ThumbnailSource.cpp @@ -70,22 +70,22 @@ void ThumbnailSource::run() args << QLatin1String("--output=") + _thumbnailPath << _file; QProcess process; - Base::Console().Log("Creating thumbnail for %s...\n", _file.toStdString()); + Base::Console().log("Creating thumbnail for %s...\n", _file.toStdString()); process.start(f3d, args); if (!process.waitForFinished()) { process.kill(); - Base::Console().Log("Creating thumbnail for %s timed out\n", _file.toStdString()); + Base::Console().log("Creating thumbnail for %s timed out\n", _file.toStdString()); return; } if (process.exitStatus() == QProcess::CrashExit) { - Base::Console().Log("Creating thumbnail for %s crashed\n", _file.toStdString()); + Base::Console().log("Creating thumbnail for %s crashed\n", _file.toStdString()); return; } if (process.exitCode() != 0) { - Base::Console().Log("Creating thumbnail for %s failed\n", _file.toStdString()); + Base::Console().log("Creating thumbnail for %s failed\n", _file.toStdString()); return; } - Base::Console().Log("Creating thumbnail for %s succeeded, wrote to %s\n", + Base::Console().log("Creating thumbnail for %s succeeded, wrote to %s\n", _file.toStdString(), _thumbnailPath.toStdString()); } @@ -110,7 +110,7 @@ std::tuple extractF3DVersion(const QString& stdoutString) patch = split[2].toInt(); } catch (...) { - Base::Console().Log( + Base::Console().log( "Could not determine F3D version, disabling thumbnail generation\n"); } } @@ -188,5 +188,5 @@ void ThumbnailSource::setupF3D() if (_f3d.major >= 2) { _f3d.baseArgs = getF3DOptions(f3d); } - Base::Console().Log("Running f3d version %d.%d\n", _f3d.major, _f3d.minor); + Base::Console().log("Running f3d version %d.%d\n", _f3d.major, _f3d.minor); } diff --git a/src/Mod/Start/Gui/AppStartGui.cpp b/src/Mod/Start/Gui/AppStartGui.cpp index 5750b1baab..6e0a02ed46 100644 --- a/src/Mod/Start/Gui/AppStartGui.cpp +++ b/src/Mod/Start/Gui/AppStartGui.cpp @@ -119,12 +119,12 @@ PyMOD_INIT_FUNC(StartGui) static StartGui::StartLauncher* launcher = new StartGui::StartLauncher(); Q_UNUSED(launcher) - Base::Console().Log("Loading GUI of Start module... "); + Base::Console().log("Loading GUI of Start module... "); PyObject* mod = StartGui::initModule(); auto manipulator = std::make_shared(); Gui::WorkbenchManipulator::installManipulator(manipulator); loadStartResource(); - Base::Console().Log("done\n"); + Base::Console().log("done\n"); // register preferences pages new Gui::PrefPageProducer( diff --git a/src/Mod/Start/Gui/GeneralSettingsWidget.cpp b/src/Mod/Start/Gui/GeneralSettingsWidget.cpp index 3d6b024458..3f365193c0 100644 --- a/src/Mod/Start/Gui/GeneralSettingsWidget.cpp +++ b/src/Mod/Start/Gui/GeneralSettingsWidget.cpp @@ -33,6 +33,7 @@ #include #endif +#include #include "GeneralSettingsWidget.h" #include #include @@ -182,7 +183,7 @@ void GeneralSettingsWidget::onUnitSystemChanged(int index) if (index < 0) { return; // happens when clearing the combo box in retranslateUi() } - Base::UnitsApi::setSchema(static_cast(index)); + Base::UnitsApi::setSchema(index); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); hGrp->SetInt("UserSchema", index); @@ -213,15 +214,16 @@ void GeneralSettingsWidget::retranslateUi() _unitSystemLabel->setText(createLabelText(tr("Unit System"))); _unitSystemComboBox->clear(); - ParameterGrp::handle hGrpUnits = + + auto addItem = [&, index {0}](const std::string& item) mutable { + _unitSystemComboBox->addItem(QString::fromStdString(item), index++); + }; + auto descriptions = Base::UnitsApi::getDescriptions(); + std::for_each(descriptions.begin(), descriptions.end(), addItem); + + const ParameterGrp::handle hGrpUnits = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); - auto userSchema = hGrpUnits->GetInt("UserSchema", 0); - int num = static_cast(Base::UnitSystem::NumUnitSystemTypes); - for (int i = 0; i < num; i++) { - QString item = Base::UnitsApi::getDescription(static_cast(i)); - _unitSystemComboBox->addItem(item, i); - } - _unitSystemComboBox->setCurrentIndex(userSchema); + _unitSystemComboBox->setCurrentIndex(static_cast(hGrpUnits->GetInt("UserSchema", 0))); _navigationStyleLabel->setText(createLabelText(tr("Navigation Style"))); _navigationStyleComboBox->clear(); diff --git a/src/Mod/Start/Gui/StartView.cpp b/src/Mod/Start/Gui/StartView.cpp index a8b45b89f0..63ce17f892 100644 --- a/src/Mod/Start/Gui/StartView.cpp +++ b/src/Mod/Start/Gui/StartView.cpp @@ -378,13 +378,13 @@ void StartView::fileCardSelected(const QModelIndex& index) Gui::ModuleIO::verifyAndOpenFile(filename); } catch (Base::PyException& e) { - Base::Console().Error(e.getMessage().c_str()); + Base::Console().error(e.getMessage().c_str()); } catch (Base::Exception& e) { - Base::Console().Error(e.getMessage().c_str()); + Base::Console().error(e.getMessage().c_str()); } catch (...) { - Base::Console().Error("An unknown error occurred"); + Base::Console().error("An unknown error occurred"); } } diff --git a/src/Mod/Surface/App/AppSurface.cpp b/src/Mod/Surface/App/AppSurface.cpp index 0505a788fc..0108acbbdc 100644 --- a/src/Mod/Surface/App/AppSurface.cpp +++ b/src/Mod/Surface/App/AppSurface.cpp @@ -71,7 +71,7 @@ PyMOD_INIT_FUNC(Surface) } PyObject* mod = Surface::initModule(); - Base::Console().Log("Loading Surface module... done\n"); + Base::Console().log("Loading Surface module... done\n"); Base::Interpreter().addType(&Surface::BlendPointPy::Type, mod, "BlendPoint"); Base::Interpreter().addType(&Surface::BlendCurvePy::Type, mod, "BlendCurve"); diff --git a/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp index 21ad172725..6ffc238a9b 100644 --- a/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp +++ b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp @@ -98,8 +98,8 @@ int BlendPointPy::PyInit(PyObject* args, PyObject*) BRepAdaptor_Curve adapt(e); if (param < adapt.FirstParameter() || param > adapt.LastParameter()) { PyErr_Warn(PyExc_UserWarning, "BlendPoint: edge is not a closed curve"); - Base::Console().Message("fp=%f\n", adapt.FirstParameter()); - Base::Console().Message("lp=%f\n", adapt.LastParameter()); + Base::Console().message("fp=%f\n", adapt.FirstParameter()); + Base::Console().message("lp=%f\n", adapt.LastParameter()); } adapt.D0(param, Pt); diff --git a/src/Mod/Surface/Gui/AppSurfaceGui.cpp b/src/Mod/Surface/Gui/AppSurfaceGui.cpp index 365226ea99..6b58be7835 100644 --- a/src/Mod/Surface/Gui/AppSurfaceGui.cpp +++ b/src/Mod/Surface/Gui/AppSurfaceGui.cpp @@ -87,6 +87,6 @@ PyMOD_INIT_FUNC(SurfaceGui) // clang-format on PyObject* mod = SurfaceGui::initModule(); - Base::Console().Log("Loading GUI of Surface module... done\n"); + Base::Console().log("Loading GUI of Surface module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp index 90b6456641..2c5caa111a 100644 --- a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp +++ b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp @@ -452,7 +452,7 @@ void GeomFillSurface::changeFillType(GeomFill_FillingStyle fillType) editedObject->FillType.setValue(static_cast(fillType)); editedObject->recomputeFeature(); if (!editedObject->isValid()) { - Base::Console().Error("Surface filling: %s", editedObject->getStatusString()); + Base::Console().error("Surface filling: %s", editedObject->getStatusString()); } } } diff --git a/src/Mod/TechDraw/App/AppTechDraw.cpp b/src/Mod/TechDraw/App/AppTechDraw.cpp index 370211d953..a4a5435119 100644 --- a/src/Mod/TechDraw/App/AppTechDraw.cpp +++ b/src/Mod/TechDraw/App/AppTechDraw.cpp @@ -82,7 +82,7 @@ PyMOD_INIT_FUNC(TechDraw) PyMOD_Return(nullptr); } PyObject* mod = TechDraw::initModule(); - Base::Console().Log("Loading TechDraw module... done\n"); + Base::Console().log("Loading TechDraw module... done\n"); TechDraw::DrawPage ::init(); TechDraw::DrawView ::init(); diff --git a/src/Mod/TechDraw/App/AppTechDrawPy.cpp b/src/Mod/TechDraw/App/AppTechDrawPy.cpp index a9d3a2c0b1..185d36e43f 100644 --- a/src/Mod/TechDraw/App/AppTechDrawPy.cpp +++ b/src/Mod/TechDraw/App/AppTechDrawPy.cpp @@ -211,7 +211,7 @@ private: str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception &e) { @@ -219,7 +219,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { @@ -227,7 +227,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } } @@ -284,7 +284,7 @@ private: } if (sortedWires.empty()) { - Base::Console().Warning("ATDP::edgeWalker: Wire detection failed\n"); + Base::Console().warning("ATDP::edgeWalker: Wire detection failed\n"); return Py::None(); } else { @@ -322,7 +322,7 @@ private: } if (edgeList.empty()) { - Base::Console().Message("ATDP::findOuterWire: input is empty\n"); + Base::Console().message("ATDP::findOuterWire: input is empty\n"); return Py::None(); } @@ -343,7 +343,7 @@ private: } if(sortedWires.empty()) { - Base::Console().Warning("ATDP::findOuterWire: Outline wire detection failed\n"); + Base::Console().warning("ATDP::findOuterWire: Outline wire detection failed\n"); return Py::None(); } else { outerWire = new TopoShapeWirePy(new TopoShape(*sortedWires.begin())); @@ -372,7 +372,7 @@ private: TopoShapePy* pShape = static_cast(pcObjShape); if (!pShape) { - Base::Console().Message("TRACE - AATDP::findShapeOutline - input shape is null\n"); + Base::Console().message("TRACE - AATDP::findShapeOutline - input shape is null\n"); return Py::None(); } @@ -408,7 +408,7 @@ private: } if(sortedWires.empty()) { - Base::Console().Warning("ATDP::findShapeOutline: Outline wire detection failed\n"); + Base::Console().warning("ATDP::findShapeOutline: Outline wire detection failed\n"); return Py::None(); } else { outerWire = new TopoShapeWirePy(new TopoShape(*sortedWires.begin())); @@ -435,7 +435,7 @@ private: dvp = static_cast(obj); TechDraw::GeometryObjectPtr gObj = dvp->getGeometryObject(); if (!gObj) { - Base::Console().Message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); + Base::Console().message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); return Py::String(); } TopoDS_Shape shape = ShapeUtils::mirrorShape(gObj->getVisHard()); @@ -498,7 +498,7 @@ private: dvp = static_cast(obj); TechDraw::GeometryObjectPtr gObj = dvp->getGeometryObject(); if (!gObj) { - Base::Console().Message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); + Base::Console().message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); return Py::String(); } @@ -568,7 +568,7 @@ private: TechDraw::GeometryObjectPtr gObj = dvp->getGeometryObject(); if (!gObj) { // this test might be redundant here since we already checked hasGeometry. - Base::Console().Message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); + Base::Console().message("TechDraw: %s has no geometry object!\n", dvp->Label.getValue()); return; } TopoDS_Shape shape = ShapeUtils::mirrorShape(gObj->getVisHard()); @@ -849,7 +849,7 @@ private: TopoShapePy* pShape = static_cast(pcObjShape); if (!pShape) { - Base::Console().Error("ShapeUtils::findCentroid - input shape is null\n"); + Base::Console().error("ShapeUtils::findCentroid - input shape is null\n"); return Py::None(); } @@ -1020,7 +1020,7 @@ private: } Base::FileInfo fi(patFile); if (!fi.isReadable()) { - Base::Console().Error(".pat File: %s is not readable\n", patFile.c_str()); + Base::Console().error(".pat File: %s is not readable\n", patFile.c_str()); return Py::None(); } std::vector specs = TechDraw::DrawGeomHatch::getDecodedSpecsFromFile(patFile, patName); diff --git a/src/Mod/TechDraw/App/CenterLine.cpp b/src/Mod/TechDraw/App/CenterLine.cpp index 965fffd935..4d88862f97 100644 --- a/src/Mod/TechDraw/App/CenterLine.cpp +++ b/src/Mod/TechDraw/App/CenterLine.cpp @@ -142,7 +142,7 @@ void CenterLine::initialize() TechDraw::BaseGeomPtr CenterLine::BaseGeomPtrFromVectors(Base::Vector3d pt1, Base::Vector3d pt2) { - // Base::Console().Message("CE::CE(p1, p2)\n"); + // Base::Console().message("CE::CE(p1, p2)\n"); Base::Vector3d p1 = DrawUtil::invertY(pt1); Base::Vector3d p2 = DrawUtil::invertY(pt2); gp_Pnt gp1(p1.x, p1.y, p1.z); @@ -157,7 +157,7 @@ CenterLine* CenterLine::CenterLineBuilder(const DrawViewPart* partFeat, const Mode mode, const bool flip) { -// Base::Console().Message("CL::CLBuilder()\n - subNames: %d\n", subNames.size()); +// Base::Console().message("CL::CLBuilder()\n - subNames: %d\n", subNames.size()); std::pair ends; std::vector faces; std::vector edges; @@ -191,9 +191,9 @@ CenterLine* CenterLine::CenterLineBuilder(const DrawViewPart* partFeat, verts = subNames; } if ((ends.first).IsEqual(ends.second, Precision::Confusion())) { - Base::Console().Warning("CenterLineBuilder - endpoints are equal: %s\n", + Base::Console().warning("CenterLineBuilder - endpoints are equal: %s\n", DrawUtil::formatVector(ends.first).c_str()); - Base::Console().Warning("CenterLineBuilder - check V/H/A and/or Flip parameters\n"); + Base::Console().warning("CenterLineBuilder - check V/H/A and/or Flip parameters\n"); return nullptr; } @@ -212,7 +212,7 @@ CenterLine* CenterLine::CenterLineBuilder(const DrawViewPart* partFeat, TechDraw::BaseGeomPtr CenterLine::scaledGeometry(const TechDraw::DrawViewPart* partFeat) { -// Base::Console().Message("CL::scaledGeometry() - m_type: %d\n", m_type); +// Base::Console().message("CL::scaledGeometry() - m_type: %d\n", m_type); double scale = partFeat->getScale(); double viewAngleDeg = partFeat->Rotation.getValue(); std::pair ends; @@ -220,7 +220,7 @@ TechDraw::BaseGeomPtr CenterLine::scaledGeometry(const TechDraw::DrawViewPart* p if (m_faces.empty() && m_edges.empty() && m_verts.empty() ) { -// Base::Console().Message("CL::scaledGeometry - no geometry to scale!\n"); +// Base::Console().message("CL::scaledGeometry - no geometry to scale!\n"); //CenterLine was created by points without a geometry reference, ends = calcEndPointsNoRef(m_start, m_end, scale, m_extendBy, m_hShift, m_vShift, m_rotate, viewAngleDeg); @@ -245,14 +245,14 @@ TechDraw::BaseGeomPtr CenterLine::scaledGeometry(const TechDraw::DrawViewPart* p } catch (...) { - Base::Console().Error("CL::scaledGeometry - failed to calculate endpoints!\n"); + Base::Console().error("CL::scaledGeometry - failed to calculate endpoints!\n"); return nullptr; } Base::Vector3d p1 = ends.first; Base::Vector3d p2 = ends.second; if (p1.IsEqual(p2, 0.00001)) { - Base::Console().Warning("Centerline endpoints are equal. Could not draw.\n"); + Base::Console().warning("Centerline endpoints are equal. Could not draw.\n"); //what to do here? //return current geom? return m_geometry; } @@ -274,7 +274,7 @@ TechDraw::BaseGeomPtr CenterLine::scaledGeometry(const TechDraw::DrawViewPart* p TechDraw::BaseGeomPtr CenterLine::scaledAndRotatedGeometry(TechDraw::DrawViewPart* partFeat) { -// Base::Console().Message("CL::scaledGeometry() - m_type: %d\n", m_type); +// Base::Console().message("CL::scaledGeometry() - m_type: %d\n", m_type); double scale = partFeat->getScale(); double viewAngleDeg = partFeat->Rotation.getValue(); std::pair ends; @@ -282,7 +282,7 @@ TechDraw::BaseGeomPtr CenterLine::scaledAndRotatedGeometry(TechDraw::DrawViewPar if (m_faces.empty() && m_edges.empty() && m_verts.empty() ) { -// Base::Console().Message("CL::scaledGeometry - no geometry to scale!\n"); +// Base::Console().message("CL::scaledGeometry - no geometry to scale!\n"); //CenterLine was created by points without a geometry reference, ends = calcEndPointsNoRef(m_start, m_end, scale, m_extendBy, m_hShift, m_vShift, m_rotate, viewAngleDeg); @@ -307,7 +307,7 @@ TechDraw::BaseGeomPtr CenterLine::scaledAndRotatedGeometry(TechDraw::DrawViewPar } catch (...) { - Base::Console().Error("CL::scaledGeometry - failed to calculate endpoints!\n"); + Base::Console().error("CL::scaledGeometry - failed to calculate endpoints!\n"); return nullptr; } @@ -315,7 +315,7 @@ TechDraw::BaseGeomPtr CenterLine::scaledAndRotatedGeometry(TechDraw::DrawViewPar Base::Vector3d p1 = ends.first; Base::Vector3d p2 = ends.second; if (p1.IsEqual(p2, 0.00001)) { - Base::Console().Warning("Centerline endpoints are equal. Could not draw.\n"); + Base::Console().warning("Centerline endpoints are equal. Could not draw.\n"); //what to do here? //return current geom? return m_geometry; } @@ -382,8 +382,8 @@ std::string CenterLine::toString() const void CenterLine::dump(const char* title) { - Base::Console().Message("CL::dump - %s \n", title); - Base::Console().Message("CL::dump - %s \n", toString().c_str()); + Base::Console().message("CL::dump - %s \n", title); + Base::Console().message("CL::dump - %s \n", toString().c_str()); } //! rotate a notional 2d vector from p1 to p2 around its midpoint by angleDeg @@ -416,7 +416,7 @@ std::pair CenterLine::calcEndPointsNoRef(const B const double vShift, const double rotate, const double viewAngleDeg) { -// Base::Console().Message("CL::calcEndPointsNoRef()\n"); +// Base::Console().message("CL::calcEndPointsNoRef()\n"); Base::Vector3d p1 = start; Base::Vector3d p2 = end; Base::Vector3d mid = (p1 + p2) / 2.0; @@ -465,9 +465,9 @@ std::pair CenterLine::calcEndPoints(const DrawVi const double vShift, const double rotate) { -// Base::Console().Message("CL::calcEndPoints()\n"); +// Base::Console().message("CL::calcEndPoints()\n"); if (faceNames.empty()) { - Base::Console().Warning("CL::calcEndPoints - no faces!\n"); + Base::Console().warning("CL::calcEndPoints - no faces!\n"); return std::pair(); } @@ -510,7 +510,7 @@ std::pair CenterLine::calcEndPoints(const DrawVi BRepBndLib::AddOptimal(faceEdgeCompound, faceBox); if (faceBox.IsVoid()) { - Base::Console().Error("CL::calcEndPoints - faceBox is void!\n"); + Base::Console().error("CL::calcEndPoints - faceBox is void!\n"); throw Base::IndexError("CenterLine wrong number of faces."); } @@ -536,7 +536,7 @@ std::pair CenterLine::calcEndPoints(const DrawVi p1 = Base::Vector3d(Xmin, Ymid, 0.0); p2 = Base::Vector3d(Xmax, Ymid, 0.0); } else { //vert == Mode::ALIGNED //aligned, but aligned doesn't make sense for face(s) bbox - Base::Console().Message("CL::calcEndPoints - aligned is not applicable to Face center lines\n"); + Base::Console().message("CL::calcEndPoints - aligned is not applicable to Face center lines\n"); p1 = Base::Vector3d(Xmid, Ymax, 0.0); p2 = Base::Vector3d(Xmid, Ymin, 0.0); } @@ -591,10 +591,10 @@ std::pair CenterLine::calcEndPoints2Lines(const { Q_UNUSED(flip) -// Base::Console().Message("CL::calc2Lines() - mode: %d flip: %d edgeNames: %d\n", mode, flip, edgeNames.size()); +// Base::Console().message("CL::calc2Lines() - mode: %d flip: %d edgeNames: %d\n", mode, flip, edgeNames.size()); std::pair result; if (edgeNames.empty()) { - Base::Console().Warning("CL::calcEndPoints2Lines - no edges!\n"); + Base::Console().warning("CL::calcEndPoints2Lines - no edges!\n"); return result; } @@ -610,11 +610,11 @@ std::pair CenterLine::calcEndPoints2Lines(const if (bg) { edges.push_back(bg); } else { - Base::Console().Message("CL::calcEndPoints2Lines - no geom for index: %d\n", idx); + Base::Console().message("CL::calcEndPoints2Lines - no geom for index: %d\n", idx); } } if (edges.size() != 2) { - Base::Console().Message("CL::calcEndPoints2Lines - wrong number of edges: %d!\n", edges.size()); + Base::Console().message("CL::calcEndPoints2Lines - wrong number of edges: %d!\n", edges.size()); throw Base::IndexError("CenterLine wrong number of edges."); } @@ -709,9 +709,9 @@ std::pair CenterLine::calcEndPoints2Points(const const bool flip) { -// Base::Console().Message("CL::calc2Points() - mode: %d\n", mode); +// Base::Console().message("CL::calc2Points() - mode: %d\n", mode); if (vertNames.empty()) { - Base::Console().Warning("CL::calcEndPoints2Points - no points!\n"); + Base::Console().warning("CL::calcEndPoints2Points - no points!\n"); return std::pair(); } @@ -891,7 +891,7 @@ void CenterLine::Save(Base::Writer &writer) const //stored geometry if (!m_geometry) { - return Base::Console().Error("CL::Save - m_geometry is null\n"); + return Base::Console().error("CL::Save - m_geometry is null\n"); } writer.Stream() << writer.ind() << "getGeomType() <<"\"/>" << std::endl; @@ -905,7 +905,7 @@ void CenterLine::Save(Base::Writer &writer) const TechDraw::AOCPtr aoc = std::static_pointer_cast(m_geometry); aoc->Save(writer); } else { - Base::Console().Message("CL::Save - unimplemented geomType: %d\n", static_cast(m_geometry->getGeomType())); + Base::Console().message("CL::Save - unimplemented geomType: %d\n", static_cast(m_geometry->getGeomType())); } writer.Stream() << writer.ind() << "" << std::endl; @@ -917,7 +917,7 @@ void CenterLine::Restore(Base::XMLReader &reader) if (!CosmeticVertex::restoreCosmetic()) { return; } -// Base::Console().Message("CL::Restore - reading elements\n"); +// Base::Console().message("CL::Restore - reading elements\n"); // read my Element reader.readElement("Start"); // get the value of my Attribute @@ -1012,7 +1012,7 @@ void CenterLine::Restore(Base::XMLReader &reader) aoc->setOCCEdge(GeometryUtils::edgeFromCircleArc(aoc)); m_geometry = aoc; } else { - Base::Console().Warning("CL::Restore - unimplemented geomType: %d\n", static_cast(gType)); + Base::Console().warning("CL::Restore - unimplemented geomType: %d\n", static_cast(gType)); } // older documents may not have the LineNumber element, so we need to check the diff --git a/src/Mod/TechDraw/App/Cosmetic.cpp b/src/Mod/TechDraw/App/Cosmetic.cpp index 3e95a72d1e..974f2533b4 100644 --- a/src/Mod/TechDraw/App/Cosmetic.cpp +++ b/src/Mod/TechDraw/App/Cosmetic.cpp @@ -76,7 +76,7 @@ CosmeticEdge::CosmeticEdge(const TopoDS_Edge& e) : CosmeticEdge::CosmeticEdge(const TechDraw::BaseGeomPtr g) { -// Base::Console().Message("CE::CE(bg)\n"); +// Base::Console().message("CE::CE(bg)\n"); m_geometry = g; //we assume input edge is already in Yinverted coordinates permaStart = m_geometry->getStartPoint(); @@ -192,8 +192,8 @@ std::string CosmeticEdge::toString() const void CosmeticEdge::dump(const char* title) const { - Base::Console().Message("CE::dump - %s \n", title); - Base::Console().Message("CE::dump - %s \n", toString().c_str()); + Base::Console().message("CE::dump - %s \n", title); + Base::Console().message("CE::dump - %s \n", toString().c_str()); } // Persistence implementers @@ -223,7 +223,7 @@ void CosmeticEdge::Save(Base::Writer &writer) const TechDraw::AOCPtr aoc = std::static_pointer_cast(m_geometry); aoc->inverted()->Save(writer); } else { - Base::Console().Warning("CE::Save - unimplemented geomType: %d\n", static_cast(m_geometry->getGeomType())); + Base::Console().warning("CE::Save - unimplemented geomType: %d\n", static_cast(m_geometry->getGeomType())); } writer.Stream() << writer.ind() << "" << endl; @@ -235,7 +235,7 @@ void CosmeticEdge::Restore(Base::XMLReader &reader) if (!CosmeticVertex::restoreCosmetic()) { return; } -// Base::Console().Message("CE::Restore - reading elements\n"); +// Base::Console().message("CE::Restore - reading elements\n"); reader.readElement("Style"); m_format.setStyle(reader.getAttributeAsInteger("value")); reader.readElement("Weight"); @@ -275,7 +275,7 @@ void CosmeticEdge::Restore(Base::XMLReader &reader) permaEnd = aoc->center; permaRadius = aoc->radius; } else { - Base::Console().Warning("CE::Restore - unimplemented geomType: %d\n", static_cast(gType)); + Base::Console().warning("CE::Restore - unimplemented geomType: %d\n", static_cast(gType)); } // older documents may not have the LineNumber element, so we need to check the // next entry. if it is a start element, then we check if it is a start element @@ -294,7 +294,7 @@ void CosmeticEdge::Restore(Base::XMLReader &reader) CosmeticEdge* CosmeticEdge::clone() const { - Base::Console().Message("CE::clone()\n"); + Base::Console().message("CE::clone()\n"); CosmeticEdge* cpy = new CosmeticEdge(); cpy->m_geometry = m_geometry->copy(); cpy->m_format = m_format; @@ -352,8 +352,8 @@ GeomFormat::~GeomFormat() void GeomFormat::dump(const char* title) const { - Base::Console().Message("GF::dump - %s \n", title); - Base::Console().Message("GF::dump - %s \n", toString().c_str()); + Base::Console().message("GF::dump - %s \n", title); + Base::Console().message("GF::dump - %s \n", toString().c_str()); } std::string GeomFormat::toString() const diff --git a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp index c989ec3881..c22ac782ee 100644 --- a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp @@ -167,13 +167,13 @@ Py::String CosmeticEdgePy::getTag() const //Py::Object CosmeticEdgePy::getGeometry(void) const //{ //// TechDraw::BaseGeomPtr bg = getCosmeticEdgePtr()->m_geometry; -// Base::Console().Message("Not implemented yet"); +// Base::Console().message("Not implemented yet"); // return Py::asObject(Py_None); //} //void CosmeticEdgePy::setGeometry(Py::Object arg) //{ -// Base::Console().Message("Not implemented yet"); +// Base::Console().message("Not implemented yet"); // PyObject* p = arg.ptr(); // if (PyObject_TypeCheck(p, &(TechDraw::BaseGeomPy::Type))) { // //TODO diff --git a/src/Mod/TechDraw/App/CosmeticExtension.cpp b/src/Mod/TechDraw/App/CosmeticExtension.cpp index 6f835d0ce1..2157024fcc 100644 --- a/src/Mod/TechDraw/App/CosmeticExtension.cpp +++ b/src/Mod/TechDraw/App/CosmeticExtension.cpp @@ -65,7 +65,7 @@ TechDraw::DrawViewPart* CosmeticExtension::getOwner() //! remove cosmetic elements for a list of subelement names void CosmeticExtension::deleteCosmeticElements(std::vector removables) { - // Base::Console().Message("CEx::deleteCosmeticElements(%d removables)\n", removables.size()); + // Base::Console().message("CEx::deleteCosmeticElements(%d removables)\n", removables.size()); DrawViewPart* viewPart = getOwner(); for (auto& name : removables) { if (DU::getGeomTypeFromName(name) == "Vertex" && @@ -114,7 +114,7 @@ void CosmeticExtension::clearCosmeticVertexes() /// add the cosmetic verts in the property list to view's vertex geometry list void CosmeticExtension::addCosmeticVertexesToGeom() { -// Base::Console().Message("CE::addCosmeticVertexesToGeom()\n"); +// Base::Console().message("CE::addCosmeticVertexesToGeom()\n"); const std::vector cVerts = CosmeticVertexes.getValues(); for (auto& cv : cVerts) { double scale = getOwner()->getScale(); @@ -128,10 +128,10 @@ void CosmeticExtension::addCosmeticVertexesToGeom() /// add a single cosmetic vertex in the property list to the view's vertex geometry list int CosmeticExtension::add1CVToGV(const std::string& tag) { -// Base::Console().Message("CE::add1CVToGV(%s)\n", tag.c_str()); +// Base::Console().message("CE::add1CVToGV(%s)\n", tag.c_str()); TechDraw::CosmeticVertex* cv = getCosmeticVertex(tag); if (!cv) { - Base::Console().Message("CE::add1CVToGV - cv %s not found\n", tag.c_str()); + Base::Console().message("CE::add1CVToGV - cv %s not found\n", tag.c_str()); return 0; } double scale = getOwner()->getScale(); @@ -145,7 +145,7 @@ int CosmeticExtension::add1CVToGV(const std::string& tag) /// update the parent view's vertex geometry with all the cosmetic vertices in the list property void CosmeticExtension::refreshCVGeoms() { - // Base::Console().Message("CE::refreshCVGeoms()\n"); + // Base::Console().message("CE::refreshCVGeoms()\n"); std::vector gVerts = getOwner()->getVertexGeometry(); std::vector newGVerts; @@ -162,7 +162,7 @@ void CosmeticExtension::refreshCVGeoms() /// find the position of a cosmetic vertex with the given tag in the parent view's geometry list int CosmeticExtension::getCVIndex(const std::string& tag) { - // Base::Console().Message("CE::getCVIndex(%s)\n", tag.c_str()); + // Base::Console().message("CE::getCVIndex(%s)\n", tag.c_str()); std::vector gVerts = getOwner()->getVertexGeometry(); std::vector cVerts = CosmeticVertexes.getValues(); @@ -178,7 +178,7 @@ int CosmeticExtension::getCVIndex(const std::string& tag) int base = gVerts.size(); i = 0; for (auto& cv : cVerts) { - // Base::Console().Message("CE::getCVIndex - cv tag: %s\n", + // Base::Console().message("CE::getCVIndex - cv tag: %s\n", // cv->getTagAsString().c_str()); if (cv->getTagAsString() == tag) { return base + i; @@ -186,7 +186,7 @@ int CosmeticExtension::getCVIndex(const std::string& tag) i++; } - // Base::Console().Message("CE::getCVIndex - returns: %d\n", result); + // Base::Console().message("CE::getCVIndex - returns: %d\n", result); return -1; } @@ -196,7 +196,7 @@ int CosmeticExtension::getCVIndex(const std::string& tag) /// invert should be set to false. std::string CosmeticExtension::addCosmeticVertex(const Base::Vector3d& pos, bool invert) { -// Base::Console().Message("CEx::addCosmeticVertex(%s)\n", +// Base::Console().message("CEx::addCosmeticVertex(%s)\n", // DrawUtil::formatVector(pos).c_str()); std::vector verts = CosmeticVertexes.getValues(); Base::Vector3d tempPos = pos; @@ -212,7 +212,7 @@ std::string CosmeticExtension::addCosmeticVertex(const Base::Vector3d& pos, bool /// retrieve a cosmetic vertex by unique id TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertex(const std::string& tagString) const { -// Base::Console().Message("CEx::getCosmeticVertex(%s)\n", tagString.c_str()); +// Base::Console().message("CEx::getCosmeticVertex(%s)\n", tagString.c_str()); const std::vector verts = CosmeticVertexes.getValues(); for (auto& cv: verts) { std::string cvTag = cv->getTagAsString(); @@ -227,7 +227,7 @@ TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertex(const std::string /// used when selecting TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertexBySelection(const std::string& name) const { -// Base::Console().Message("CEx::getCVBySelection(%s)\n", name.c_str()); +// Base::Console().message("CEx::getCVBySelection(%s)\n", name.c_str()); App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); if (!dvp) { @@ -244,7 +244,7 @@ TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertexBySelection(const /// retrieve a cosmetic vertex by index (the 5 in Vertex5) TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertexBySelection(const int i) const { -// Base::Console().Message("CEx::getCVBySelection(%d)\n", i); +// Base::Console().message("CEx::getCVBySelection(%d)\n", i); std::stringstream ss; ss << "Vertex" << i; std::string vName = ss.str(); @@ -254,7 +254,7 @@ TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertexBySelection(const /// remove the cosmetic vertex with the given tag from the list property void CosmeticExtension::removeCosmeticVertex(const std::string& delTag) { -// Base::Console().Message("DVP::removeCV(%s)\n", delTag.c_str()); +// Base::Console().message("DVP::removeCV(%s)\n", delTag.c_str()); std::vector cVerts = CosmeticVertexes.getValues(); std::vector newVerts; for (auto& cv: cVerts) { @@ -292,7 +292,7 @@ void CosmeticExtension::clearCosmeticEdges() /// add the cosmetic edges to geometry edge list void CosmeticExtension::addCosmeticEdgesToGeom() { -// Base::Console().Message("CEx::addCosmeticEdgesToGeom()\n"); +// Base::Console().message("CEx::addCosmeticEdgesToGeom()\n"); const std::vector cEdges = CosmeticEdges.getValues(); for (auto& ce : cEdges) { double scale = getOwner()->getScale(); @@ -308,10 +308,10 @@ void CosmeticExtension::addCosmeticEdgesToGeom() /// add a single cosmetic edge to the geometry edge list int CosmeticExtension::add1CEToGE(const std::string& tag) { - // Base::Console().Message("CEx::add1CEToGE(%s) 2\n", tag.c_str()); + // Base::Console().message("CEx::add1CEToGE(%s) 2\n", tag.c_str()); TechDraw::CosmeticEdge* ce = getCosmeticEdge(tag); if (!ce) { - Base::Console().Message("CEx::add1CEToGE 2 - ce %s not found\n", tag.c_str()); + Base::Console().message("CEx::add1CEToGE 2 - ce %s not found\n", tag.c_str()); return -1; } double scale = getOwner()->getScale(); @@ -325,7 +325,7 @@ int CosmeticExtension::add1CEToGE(const std::string& tag) /// update Edge geometry with current CE's void CosmeticExtension::refreshCEGeoms() { - // Base::Console().Message("CEx::refreshCEGeoms()\n"); + // Base::Console().message("CEx::refreshCEGeoms()\n"); std::vector gEdges = getOwner()->getEdgeGeometry(); std::vector oldGEdges; for (auto& ge : gEdges) { @@ -342,7 +342,7 @@ void CosmeticExtension::refreshCEGeoms() std::string CosmeticExtension::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end) { -// Base::Console().Message("CEx::addCosmeticEdge(s, e)\n"); +// Base::Console().message("CEx::addCosmeticEdge(s, e)\n"); std::vector edges = CosmeticEdges.getValues(); TechDraw::CosmeticEdge* ce = new TechDraw::CosmeticEdge(start, end); edges.push_back(ce); @@ -354,7 +354,7 @@ std::string CosmeticExtension::addCosmeticEdge(Base::Vector3d start, /// returns unique CE id std::string CosmeticExtension::addCosmeticEdge(TechDraw::BaseGeomPtr bg) { -// Base::Console().Message("CEx::addCosmeticEdge(bg: %X)\n", bg); +// Base::Console().message("CEx::addCosmeticEdge(bg: %X)\n", bg); std::vector edges = CosmeticEdges.getValues(); TechDraw::CosmeticEdge* ce = new TechDraw::CosmeticEdge(bg); edges.push_back(ce); @@ -365,7 +365,7 @@ std::string CosmeticExtension::addCosmeticEdge(TechDraw::BaseGeomPtr bg) /// retrieve a CE by unique id TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdge(const std::string& tagString) const { -// Base::Console().Message("CEx::getCosmeticEdge(%s)\n", tagString.c_str()); +// Base::Console().message("CEx::getCosmeticEdge(%s)\n", tagString.c_str()); const std::vector edges = CosmeticEdges.getValues(); for (auto& ce: edges) { std::string ceTag = ce->getTagAsString(); @@ -375,7 +375,7 @@ TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdge(const std::string& ta } // None found -// Base::Console().Message("CEx::getCosmeticEdge - CE for tag: %s not found.\n", tagString.c_str()); +// Base::Console().message("CEx::getCosmeticEdge - CE for tag: %s not found.\n", tagString.c_str()); return nullptr; } @@ -383,7 +383,7 @@ TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdge(const std::string& ta /// used when selecting TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdgeBySelection(const std::string& name) const { - // Base::Console().Message("CEx::getCEBySelection(%s)\n", name.c_str()); + // Base::Console().message("CEx::getCEBySelection(%s)\n", name.c_str()); App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); if (!dvp) { @@ -401,7 +401,7 @@ TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdgeBySelection(const std: /// find the cosmetic edge corresponding to the input parameter (the 5 in Edge5) TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdgeBySelection(int i) const { - // Base::Console().Message("CEx::getCEBySelection(%d)\n", i); + // Base::Console().message("CEx::getCEBySelection(%d)\n", i); std::stringstream edgeName; edgeName << "Edge" << i; return getCosmeticEdgeBySelection(edgeName.str()); @@ -410,7 +410,7 @@ TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdgeBySelection(int i) con /// remove the cosmetic edge with the given tag from the list property void CosmeticExtension::removeCosmeticEdge(const std::string& delTag) { - // Base::Console().Message("DVP::removeCE(%s)\n", delTag.c_str()); + // Base::Console().message("DVP::removeCE(%s)\n", delTag.c_str()); std::vector cEdges = CosmeticEdges.getValues(); std::vector newEdges; for (auto& ce: cEdges) { @@ -427,7 +427,7 @@ void CosmeticExtension::removeCosmeticEdge(const std::string& delTag) /// remove the cosmetic edges with the given tags from the list property void CosmeticExtension::removeCosmeticEdge(const std::vector& delTags) { - // Base::Console().Message("DVP::removeCE(%d tags)\n", delTags.size()); + // Base::Console().message("DVP::removeCE(%d tags)\n", delTags.size()); std::vector cEdges = CosmeticEdges.getValues(); for (auto& t: delTags) { removeCosmeticEdge(t); @@ -449,10 +449,10 @@ void CosmeticExtension::clearCenterLines() int CosmeticExtension::add1CLToGE(const std::string& tag) { - // Base::Console().Message("CEx::add1CLToGE(%s) 2\n", tag.c_str()); + // Base::Console().message("CEx::add1CLToGE(%s) 2\n", tag.c_str()); TechDraw::CenterLine* cl = getCenterLine(tag); if (!cl) { -// Base::Console().Message("CEx::add1CLToGE 2 - cl %s not found\n", tag.c_str()); +// Base::Console().message("CEx::add1CLToGE 2 - cl %s not found\n", tag.c_str()); return -1; } TechDraw::BaseGeomPtr scaledGeom = cl->scaledAndRotatedGeometry(getOwner()); @@ -464,7 +464,7 @@ int CosmeticExtension::add1CLToGE(const std::string& tag) //update Edge geometry with current CL's void CosmeticExtension::refreshCLGeoms() { - // Base::Console().Message("CE::refreshCLGeoms()\n"); + // Base::Console().message("CE::refreshCLGeoms()\n"); std::vector gEdges = getOwner()->getEdgeGeometry(); std::vector newGEdges; for (auto& ge : gEdges) { @@ -479,12 +479,12 @@ void CosmeticExtension::refreshCLGeoms() //add the center lines to geometry Edges list void CosmeticExtension::addCenterLinesToGeom() { - // Base::Console().Message("CE::addCenterLinesToGeom()\n"); + // Base::Console().message("CE::addCenterLinesToGeom()\n"); const std::vector lines = CenterLines.getValues(); for (auto& cl : lines) { TechDraw::BaseGeomPtr scaledGeom = cl->scaledAndRotatedGeometry(getOwner()); if (!scaledGeom) { - Base::Console().Error("CE::addCenterLinesToGeom - scaledGeometry is null\n"); + Base::Console().error("CE::addCenterLinesToGeom - scaledGeometry is null\n"); continue; } // int idx = @@ -497,7 +497,7 @@ void CosmeticExtension::addCenterLinesToGeom() std::string CosmeticExtension::addCenterLine(Base::Vector3d start, Base::Vector3d end) { -// Base::Console().Message("CEx::addCenterLine(%s)\n", +// Base::Console().message("CEx::addCenterLine(%s)\n", // DrawUtil::formatVector(start).c_str(), // DrawUtil::formatVector(end).c_str()); std::vector cLines = CenterLines.getValues(); @@ -509,7 +509,7 @@ std::string CosmeticExtension::addCenterLine(Base::Vector3d start, std::string CosmeticExtension::addCenterLine(TechDraw::CenterLine* cl) { -// Base::Console().Message("CEx::addCenterLine(cl: %X)\n", cl); +// Base::Console().message("CEx::addCenterLine(cl: %X)\n", cl); std::vector cLines = CenterLines.getValues(); cLines.push_back(cl); CenterLines.setValues(cLines); @@ -519,7 +519,7 @@ std::string CosmeticExtension::addCenterLine(TechDraw::CenterLine* cl) std::string CosmeticExtension::addCenterLine(TechDraw::BaseGeomPtr bg) { -// Base::Console().Message("CEx::addCenterLine(bg: %X)\n", bg); +// Base::Console().message("CEx::addCenterLine(bg: %X)\n", bg); std::vector cLines = CenterLines.getValues(); TechDraw::CenterLine* cl = new TechDraw::CenterLine(bg); cLines.push_back(cl); @@ -530,7 +530,7 @@ std::string CosmeticExtension::addCenterLine(TechDraw::BaseGeomPtr bg) //get CL by unique id TechDraw::CenterLine* CosmeticExtension::getCenterLine(const std::string& tagString) const { -// Base::Console().Message("CEx::getCenterLine(%s)\n", tagString.c_str()); +// Base::Console().message("CEx::getCenterLine(%s)\n", tagString.c_str()); const std::vector cLines = CenterLines.getValues(); for (auto& cl: cLines) { std::string clTag = cl->getTagAsString(); @@ -545,7 +545,7 @@ TechDraw::CenterLine* CosmeticExtension::getCenterLine(const std::string& tagStr // used when selecting TechDraw::CenterLine* CosmeticExtension::getCenterLineBySelection(const std::string& name) const { -// Base::Console().Message("CEx::getCLBySelection(%s)\n", name.c_str()); +// Base::Console().message("CEx::getCLBySelection(%s)\n", name.c_str()); App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); if (!dvp) { @@ -562,7 +562,7 @@ TechDraw::CenterLine* CosmeticExtension::getCenterLineBySelection(const std::str //overload for index only TechDraw::CenterLine* CosmeticExtension::getCenterLineBySelection(int i) const { -// Base::Console().Message("CEx::getCLBySelection(%d)\n", i); +// Base::Console().message("CEx::getCLBySelection(%d)\n", i); std::stringstream edgeName; edgeName << "Edge" << i; return getCenterLineBySelection(edgeName.str()); @@ -570,7 +570,7 @@ TechDraw::CenterLine* CosmeticExtension::getCenterLineBySelection(int i) const void CosmeticExtension::removeCenterLine(const std::string& delTag) { - // Base::Console().Message("DVP::removeCL(%s)\n", delTag.c_str()); + // Base::Console().message("DVP::removeCL(%s)\n", delTag.c_str()); std::vector cLines = CenterLines.getValues(); std::vector newLines; for (auto& cl: cLines) { @@ -603,7 +603,7 @@ void CosmeticExtension::clearGeomFormats() //only adds gf to gflist property. does not add to display geometry until dvp repaints. std::string CosmeticExtension::addGeomFormat(TechDraw::GeomFormat* gf) { -// Base::Console().Message("CEx::addGeomFormat(gf: %X)\n", gf); +// Base::Console().message("CEx::addGeomFormat(gf: %X)\n", gf); std::vector formats = GeomFormats.getValues(); TechDraw::GeomFormat* newGF = new TechDraw::GeomFormat(gf); formats.push_back(newGF); @@ -615,7 +615,7 @@ std::string CosmeticExtension::addGeomFormat(TechDraw::GeomFormat* gf) //get GF by unique id TechDraw::GeomFormat* CosmeticExtension::getGeomFormat(const std::string& tagString) const { -// Base::Console().Message("CEx::getGeomFormat(%s)\n", tagString.c_str()); +// Base::Console().message("CEx::getGeomFormat(%s)\n", tagString.c_str()); const std::vector formats = GeomFormats.getValues(); for (auto& gf: formats) { std::string gfTag = gf->getTagAsString(); @@ -632,7 +632,7 @@ TechDraw::GeomFormat* CosmeticExtension::getGeomFormat(const std::string& tagStr // used when selecting TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(const std::string& name) const { -// Base::Console().Message("CEx::getCEBySelection(%s)\n", name.c_str()); +// Base::Console().message("CEx::getCEBySelection(%s)\n", name.c_str()); App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); if (!dvp) { @@ -653,7 +653,7 @@ TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(const std::str //overload for index only TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(int i) const { -// Base::Console().Message("CEx::getCEBySelection(%d)\n", i); +// Base::Console().message("CEx::getCEBySelection(%d)\n", i); std::stringstream edgeName; edgeName << "Edge" << i; return getGeomFormatBySelection(edgeName.str()); @@ -661,7 +661,7 @@ TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(int i) const void CosmeticExtension::removeGeomFormat(const std::string& delTag) { -// Base::Console().Message("DVP::removeCE(%s)\n", delTag.c_str()); +// Base::Console().message("DVP::removeCE(%s)\n", delTag.c_str()); std::vector cFormats = GeomFormats.getValues(); std::vector newFormats; for (auto& gf: cFormats) { diff --git a/src/Mod/TechDraw/App/CosmeticVertex.cpp b/src/Mod/TechDraw/App/CosmeticVertex.cpp index 35275c0546..9d7df4780b 100644 --- a/src/Mod/TechDraw/App/CosmeticVertex.cpp +++ b/src/Mod/TechDraw/App/CosmeticVertex.cpp @@ -208,13 +208,13 @@ Base::Vector3d CosmeticVertex::makeCanonicalPointInverted(DrawViewPart* dvp, Bas CosmeticVertex* CosmeticVertex::copy() const { -// Base::Console().Message("CV::copy()\n"); +// Base::Console().message("CV::copy()\n"); return new CosmeticVertex(this); } CosmeticVertex* CosmeticVertex::clone() const { -// Base::Console().Message("CV::clone()\n"); +// Base::Console().message("CV::clone()\n"); CosmeticVertex* cpy = this->copy(); cpy->setTag(this->getTag()); return cpy; @@ -232,6 +232,6 @@ PyObject* CosmeticVertex::getPyObject() // To do: make const void CosmeticVertex::dump(const char* title) { - Base::Console().Message("CV::dump - %s \n", title); - Base::Console().Message("CV::dump - %s \n", toString().c_str()); + Base::Console().message("CV::dump - %s \n", title); + Base::Console().message("CV::dump - %s \n", toString().c_str()); } diff --git a/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp b/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp index 3b92e6c3fc..5fe31eec25 100644 --- a/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp @@ -180,7 +180,7 @@ void CosmeticVertexPy::setColor(Py::Object arg) CosmeticVertex* cv = getCosmeticVertexPtr(); cv->color = c; } else { - Base::Console().Error("CEPI::setColor - not a tuple!\n"); + Base::Console().error("CEPI::setColor - not a tuple!\n"); std::string error = std::string("type must be 'tuple', not "); error += pTuple->ob_type->tp_name; throw Py::TypeError(error); diff --git a/src/Mod/TechDraw/App/DimensionAutoCorrect.cpp b/src/Mod/TechDraw/App/DimensionAutoCorrect.cpp index a18edac90c..aecb2be68b 100644 --- a/src/Mod/TechDraw/App/DimensionAutoCorrect.cpp +++ b/src/Mod/TechDraw/App/DimensionAutoCorrect.cpp @@ -87,7 +87,7 @@ using DU = DrawUtil; //! was created. bool DimensionAutoCorrect::referencesHaveValidGeometry(std::vector& referenceState) const { - // Base::Console().Message("DAC::referencesHaveValidGeometry()\n"); + // Base::Console().message("DAC::referencesHaveValidGeometry()\n"); ReferenceVector refsAll = getDimension()->getEffectiveReferences(); const std::vector savedGeometry = getDimension()->SavedGeometry.getValues(); @@ -126,7 +126,7 @@ bool DimensionAutoCorrect::referencesHaveValidGeometry(std::vector& refere bool DimensionAutoCorrect::autocorrectReferences(std::vector& referenceState, ReferenceVector& repairedRefs) const { - // Base::Console().Message("DAC::autocorrectReferences()\n"); + // Base::Console().message("DAC::autocorrectReferences()\n"); if (!Preferences::autoCorrectDimRefs()) { return false; } @@ -199,7 +199,7 @@ bool DimensionAutoCorrect::autocorrectReferences(std::vector& referenceSta //! fix a single reference with an exact match to geomToMatch bool DimensionAutoCorrect::fix1GeomExact(ReferenceEntry& refToFix, const TopoDS_Shape &geomToMatch) const { - // Base::Console().Message("DAC::fix1GeomExact()\n"); + // Base::Console().message("DAC::fix1GeomExact()\n"); ReferenceEntry fixedRef = refToFix; Part::TopoShape topoShapeToMatch(geomToMatch); bool success {false}; @@ -229,7 +229,7 @@ bool DimensionAutoCorrect::fix1GeomExact(ReferenceEntry& refToFix, const TopoDS_ //! fix a single reference with an Similar match to geomToMatch bool DimensionAutoCorrect::fix1GeomSimilar(ReferenceEntry& refToFix, const TopoDS_Shape &geomToMatch) const { - // Base::Console().Message("DAC::fix1GeomSimilar()\n"); + // Base::Console().message("DAC::fix1GeomSimilar()\n"); Part::TopoShape topoShapeToMatch(geomToMatch); bool success {false}; if (refToFix.is3d()) { @@ -261,7 +261,7 @@ bool DimensionAutoCorrect::fix1GeomSimilar(ReferenceEntry& refToFix, const TopoD bool DimensionAutoCorrect::findExactVertex2d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findExactVertex2d()\n"); + // Base::Console().message("DAC::findExactVertex2d()\n"); getMatcher()->setPointTolerance(EWTOLERANCE); auto refObj = refToFix.getObject(); auto refDvp = dynamic_cast(refObj); @@ -281,7 +281,7 @@ bool DimensionAutoCorrect::findExactVertex2d(ReferenceEntry& refToFix, //! and return a reference pointing to the matching edge. bool DimensionAutoCorrect::findExactEdge2d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findExactEdge2d()\n"); + // Base::Console().message("DAC::findExactEdge2d()\n"); auto refObj = refToFix.getObject(); auto refDvp = dynamic_cast(refObj); if (refDvp) { @@ -301,7 +301,7 @@ bool DimensionAutoCorrect::findExactEdge2d(ReferenceEntry& refToFix, const Part: bool DimensionAutoCorrect::findExactVertex3d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findExactVertex3d()\n"); + // Base::Console().message("DAC::findExactVertex3d()\n"); getMatcher()->setPointTolerance(EWTOLERANCE); // try the referenced object @@ -331,7 +331,7 @@ bool DimensionAutoCorrect::findExactVertex3d(ReferenceEntry& refToFix, //! and return a reference pointing to the matching edge. bool DimensionAutoCorrect::findExactEdge3d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findExactEdge3d() - cache: %d\n", m_3dObjectCache.size()); + // Base::Console().message("DAC::findExactEdge3d() - cache: %d\n", m_3dObjectCache.size()); // first, try to find a match in the referenced object auto refObj = refToFix.getObject(); if (refObj) { @@ -367,10 +367,10 @@ bool DimensionAutoCorrect::findExactEdge3d(ReferenceEntry& refToFix, const Part: bool DimensionAutoCorrect::findSimilarVertex2d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findSimilarVertex2d()\n"); + // Base::Console().message("DAC::findSimilarVertex2d()\n"); (void)refToFix; (void)refGeom; - // Base::Console().Message("DAC::findSimilarVertex2d is not implemented yet\n"); + // Base::Console().message("DAC::findSimilarVertex2d is not implemented yet\n"); return false; } @@ -379,10 +379,10 @@ bool DimensionAutoCorrect::findSimilarVertex2d(ReferenceEntry& refToFix, bool DimensionAutoCorrect::findSimilarEdge2d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findSimilarEdge2d()\n"); + // Base::Console().message("DAC::findSimilarEdge2d()\n"); (void)refToFix; (void)refGeom; - // Base::Console().Message("DAC::findSimilarEdge2d is not implemented yet\n"); + // Base::Console().message("DAC::findSimilarEdge2d is not implemented yet\n"); return false; } @@ -392,10 +392,10 @@ bool DimensionAutoCorrect::findSimilarEdge2d(ReferenceEntry& refToFix, bool DimensionAutoCorrect::findSimilarVertex3d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findSimilarVertex3d()\n"); + // Base::Console().message("DAC::findSimilarVertex3d()\n"); (void)refToFix; (void)refGeom; - // Base::Console().Message("DAC::findSimilarVertex3d is not implemented yet\n"); + // Base::Console().message("DAC::findSimilarVertex3d is not implemented yet\n"); return false; } @@ -405,10 +405,10 @@ bool DimensionAutoCorrect::findSimilarVertex3d(ReferenceEntry& refToFix, bool DimensionAutoCorrect::findSimilarEdge3d(ReferenceEntry& refToFix, const Part::TopoShape& refGeom) const { - // Base::Console().Message("DAC::findSimilarEdge3d(%s)\n", refToFix.getObjectName().c_str()); + // Base::Console().message("DAC::findSimilarEdge3d(%s)\n", refToFix.getObjectName().c_str()); (void)refToFix; (void)refGeom; - // Base::Console().Message("DAC::findSimilarEdge3d is not implemented yet\n"); + // Base::Console().message("DAC::findSimilarEdge3d is not implemented yet\n"); return false; } @@ -471,7 +471,7 @@ ReferenceEntry DimensionAutoCorrect::searchViewForVert(DrawViewPart* obj, const Part::TopoShape& refVertex, bool exact) const { - // Base::Console().Message("DAC::searchViewForVert()\n"); + // Base::Console().message("DAC::searchViewForVert()\n"); (void)exact; std::vector gVertexAll = getDimension()->getViewPart()->getVertexGeometry(); @@ -494,7 +494,7 @@ ReferenceEntry DimensionAutoCorrect::searchViewForVert(DrawViewPart* obj, ReferenceEntry DimensionAutoCorrect::searchViewForExactEdge(DrawViewPart* obj, const Part::TopoShape& refEdge) const { - // Base::Console().Message("DAC::searchViewForExactEdge()\n"); + // Base::Console().message("DAC::searchViewForExactEdge()\n"); auto gEdgeAll = getDimension()->getViewPart()->getEdgeGeometry(); int iEdge {0}; for (auto& edge : gEdgeAll) { @@ -516,10 +516,10 @@ ReferenceEntry DimensionAutoCorrect::searchViewForExactEdge(DrawViewPart* obj, ReferenceEntry DimensionAutoCorrect::searchViewForSimilarEdge(DrawViewPart* obj, const Part::TopoShape& refEdge) const { - // Base::Console().Message("DAC::searchViewForSimilarEdge()\n"); + // Base::Console().message("DAC::searchViewForSimilarEdge()\n"); (void)obj; (void)refEdge; - Base::Console().Message("DAC::searchViewForSimilarEdge is not implemented yet\n"); + Base::Console().message("DAC::searchViewForSimilarEdge is not implemented yet\n"); return {}; } @@ -529,7 +529,7 @@ ReferenceEntry DimensionAutoCorrect::searchObjForEdge(App::DocumentObject* obj, const Part::TopoShape& refEdge, bool exact) const { - // Base::Console().Message("DAC::searchObjForEdge(%s)\n", obj->Label.getValue()); + // Base::Console().message("DAC::searchObjForEdge(%s)\n", obj->Label.getValue()); (void)exact; auto shape3d = Part::Feature::getShape(obj); if (shape3d.IsNull()) { @@ -553,7 +553,7 @@ ReferenceEntry DimensionAutoCorrect::searchObjForEdge(App::DocumentObject* obj, //! have been repaired bool DimensionAutoCorrect::fixBrokenReferences(ReferenceVector& fixedReferences) const { - // Base::Console().Message("DAC::fixBrokenReferences()\n"); + // Base::Console().message("DAC::fixBrokenReferences()\n"); bool success {true}; const std::vector savedGeometry = getDimension()->SavedGeometry.getValues(); int iGeom {0}; diff --git a/src/Mod/TechDraw/App/DimensionFormatter.cpp b/src/Mod/TechDraw/App/DimensionFormatter.cpp index 2df17fb753..40656acf73 100644 --- a/src/Mod/TechDraw/App/DimensionFormatter.cpp +++ b/src/Mod/TechDraw/App/DimensionFormatter.cpp @@ -39,17 +39,11 @@ using namespace TechDraw; bool DimensionFormatter::isMultiValueSchema() const { - bool angularMeasure = (m_dimension->Type.isValue("Angle") || - m_dimension->Type.isValue("Angle3Pt")); + const bool angularMeasure = + (m_dimension->Type.isValue("Angle") || m_dimension->Type.isValue("Angle3Pt")); - if (Base::UnitsApi::isMultiUnitAngle() && - angularMeasure) { - return true; - } else if (Base::UnitsApi::isMultiUnitLength() && - !angularMeasure) { - return true; - } - return false; + return (Base::UnitsApi::isMultiUnitAngle() && angularMeasure) + || (Base::UnitsApi::isMultiUnitLength() && !angularMeasure); } std::string DimensionFormatter::formatValue(const qreal value, @@ -57,145 +51,117 @@ std::string DimensionFormatter::formatValue(const qreal value, const Format partial, const bool isDim) const { -// Base::Console().Message("DF::formatValue() - %s isRestoring: %d\n", -// m_dimension->getNameInDocument(), m_dimension->isRestoring()); - bool angularMeasure = m_dimension->Type.isValue("Angle") || m_dimension->Type.isValue("Angle3Pt"); - bool areaMeasure = m_dimension->Type.isValue("Area"); - QLocale loc; + const bool angularMeasure = + m_dimension->Type.isValue("Angle") || m_dimension->Type.isValue("Angle3Pt"); + const bool areaMeasure = m_dimension->Type.isValue("Area"); - Base::Quantity asQuantity; - asQuantity.setValue(value); + Base::Unit unit; if (angularMeasure) { - asQuantity.setUnit(Base::Unit::Angle); + unit = Base::Unit::Angle; } else if (areaMeasure) { - asQuantity.setUnit(Base::Unit::Area); + unit = Base::Unit::Area; } else { - asQuantity.setUnit(Base::Unit::Length); + unit = Base::Unit::Length; } + Base::Quantity asQuantity {value, unit}; + + QStringList qsl = getPrefixSuffixSpec(qFormatSpec); + const std::string formatPrefix = qsl[0].toStdString(); + const std::string formatSuffix = qsl[1].toStdString(); + QString formatSpecifier = qsl[2]; + // this handles mm to inch/km/parsec etc and decimal positions but // won't give more than Global_Decimals precision - QString qUserString = QString::fromStdString(asQuantity.getUserString()); + std::string basicString = formatPrefix + asQuantity.getUserString() + formatSuffix; - //get formatSpec prefix/suffix/specifier - QStringList qsl = getPrefixSuffixSpec(qFormatSpec); - QString formatPrefix = qsl[0]; //FormatSpec prefix - QString formatSuffix = qsl[1]; //FormatSpec suffix - QString formatSpecifier = qsl[2]; //FormatSpec specifier - - QString qMultiValueStr; - QString qBasicUnit = QString::fromStdString(Base::UnitsApi::getBasicLengthUnit()); - - QString formattedValue; if (isMultiValueSchema() && partial == Format::UNALTERED) { - //handle multi value schemes (yd/ft/in, dms, etc). don't even try to use Alt Decimals or hide units - qMultiValueStr = formatPrefix + qUserString + formatSuffix; - return qMultiValueStr.toStdString(); - } else { - //not multivalue schema - if (formatSpecifier.isEmpty()) { - Base::Console().Warning("Warning - no numeric format in Format Spec %s - %s\n", - qPrintable(qFormatSpec), m_dimension->getNameInDocument()); - return qFormatSpec.toStdString(); - } + return basicString; // Don't even try to use Alt Decimals or hide units + } - // for older TD drawings the formatSpecifier "%g" was used, but the number of decimals was - // neverheless limited. To keep old drawings, we limit the number of decimals too - // if the TD preferences option to use the global decimal number is set - // the formatSpecifier can have a prefix and/or suffix - if (m_dimension->useDecimals() && formatSpecifier.contains(QStringLiteral("%g"), Qt::CaseInsensitive)) { - int globalPrecision = Base::UnitsApi::getDecimals(); - // change formatSpecifier to e.g. "%.2f" - QString newSpecifier = QString::fromStdString("%." + std::to_string(globalPrecision) + "f"); - formatSpecifier.replace(QStringLiteral("%g"), newSpecifier, Qt::CaseInsensitive); - } + if (formatSpecifier.isEmpty()) { + Base::Console().warning("Warning - no numeric format in Format Spec %s - %s\n", + qPrintable(qFormatSpec), + m_dimension->getNameInDocument()); + return qFormatSpec.toStdString(); + } - // since we are not using a multiValueSchema, we know that angles are in '°' and for - // lengths we can get the unit of measure from UnitsApi::getBasicLengthUnit. + // for older TD drawings the formatSpecifier "%g" was used, but the number of decimals was + // nevertheless limited. To keep old drawings, we limit the number of decimals too + // if the TD preferences option to use the global decimal number is set + // the formatSpecifier can have a prefix and/or suffix + if (m_dimension->useDecimals() + && formatSpecifier.contains(QStringLiteral("%g"), Qt::CaseInsensitive)) { + const int globalPrecision = Base::UnitsApi::getDecimals(); + // change formatSpecifier to e.g. "%.2f" + const QString newSpecifier = + QString::fromStdString("%." + std::to_string(globalPrecision) + "f"); + formatSpecifier.replace(QStringLiteral("%g"), newSpecifier, Qt::CaseInsensitive); + } - // TODO: check the weird schemas (MKS, Imperial1)that report different UoM - // for different values + // since we are not using a multiValueSchema, we know that angles are in '°' and for + // lengths we can get the unit of measure from UnitsApi::getBasicLengthUnit. - // get value in the base unit with default decimals - // for the conversion we use the same method as in DlgUnitsCalculator::valueChanged - // get the conversion factor for the unit - // the result is now just val / convertValue because val is always in the base unit - // don't do this for angular values since they are not in the BaseLengthUnit - double userVal; - if (angularMeasure) { - userVal = asQuantity.getValue(); - qBasicUnit = QStringLiteral("°"); - } - else { - double convertValue = Base::Quantity::parse("1" + qBasicUnit.toStdString()).getValue(); - userVal = asQuantity.getValue() / convertValue; - if (areaMeasure) { - userVal = userVal / convertValue; // divide again as area is length² - qBasicUnit = qBasicUnit + QStringLiteral("²"); - } - } + // TODO: check the weird schemas (MKS, Imperial1) that report different UoM for different values - if (isTooSmall(userVal, formatSpecifier)) { - Base::Console().Warning("Dimension %s value %.6f is too small for format specifier: %s\n", - m_dimension->getNameInDocument(), userVal, qPrintable(formatSpecifier)); - } + // get value in the base unit with default decimals + // for the conversion we use the same method as in DlgUnitsCalculator::valueChanged + // get the conversion factor for the unit + // the result is now just val / convertValue because val is always in the base unit + // don't do this for angular values since they are not in the BaseLengthUnit + std::string qBasicUnit = + angularMeasure ? "°" : Base::UnitsApi::getBasicLengthUnit(); + double userVal = asQuantity.getValue(); - formattedValue = formatValueToSpec(userVal, formatSpecifier); - - // replace decimal sign if necessary - QChar dp = QChar::fromLatin1('.'); - if (loc.decimalPoint() != dp) { - formattedValue.replace(dp, loc.decimalPoint()); + if (!angularMeasure) { + const double convertValue = Base::Quantity::parse("1" + qBasicUnit).getValue(); + userVal /= convertValue; + if (areaMeasure) { + userVal /= convertValue; // divide again as area is length² + qBasicUnit += "²"; } } - //formattedValue is now in formatSpec format with local decimal separator + if (isTooSmall(userVal, formatSpecifier)) { + Base::Console().warning("Dimension %s value %.6f is too small for format specifier: %s\n", + m_dimension->getNameInDocument(), + userVal, + qPrintable(formatSpecifier)); + } + + QString formattedValue = formatValueToSpec(userVal, formatSpecifier); + + // replace decimal sign if necessary + constexpr QChar dp = QChar::fromLatin1('.'); + if (const QLocale loc; loc.decimalPoint() != dp) { + formattedValue.replace(dp, loc.decimalPoint()); + } + + // formattedValue is now in formatSpec format with local decimal separator std::string formattedValueString = formattedValue.toStdString(); - if (partial == Format::UNALTERED) { // prefix + unit subsystem string + suffix - return formatPrefix.toStdString() + - qUserString.toStdString() + - formatSuffix.toStdString(); + + if (partial == Format::UNALTERED) { + return basicString; } - else if (partial == Format::FORMATTED) { + + if (partial == Format::FORMATTED) { + std::string unitStr {}; + if (angularMeasure) { - //always insert unit after value - return formatPrefix.toStdString() + formattedValueString + "°" + - formatSuffix.toStdString(); + unitStr = "°"; } - else if (m_dimension->showUnits() || areaMeasure){ - if (isDim && m_dimension->haveTolerance()) { - //unit will be included in tolerance so don't repeat it here - return formatPrefix.toStdString() + - formattedValueString + - formatSuffix.toStdString(); - } - else { - //no tolerance, so we need to include unit - return formatPrefix.toStdString() + - formattedValueString + " " + - qBasicUnit.toStdString() + - formatSuffix.toStdString(); - } - } - else { - //showUnits is false - return formatPrefix.toStdString() + - formattedValueString + - formatSuffix.toStdString(); + else if ((m_dimension->showUnits() || areaMeasure) + && !(isDim && m_dimension->haveTolerance())) { + unitStr = " " + qBasicUnit; } + + return formatPrefix + formattedValueString + unitStr + formatSuffix; } - else if (partial == Format::UNIT) { - if (angularMeasure) { - return qBasicUnit.toStdString(); - } - else if (m_dimension->showUnits() || areaMeasure) { - return qBasicUnit.toStdString(); - } - else { - return ""; - } + + if (partial == Format::UNIT) { + return angularMeasure || m_dimension->showUnits() || areaMeasure ? qBasicUnit : ""; } return formattedValueString; @@ -368,13 +334,10 @@ QString DimensionFormatter::formatValueToSpec(const double value, QString format bool DimensionFormatter::isNumericFormat(const QString& formatSpecifier) const { - QRegularExpression rxFormat(QStringLiteral("%[+-]?[0-9]*\\.*[0-9]*[aefgwAEFGW]")); //printf double format spec + //printf double format spec + const QRegularExpression rxFormat(QStringLiteral("%[+-]?[0-9]*\\.*[0-9]*[aefgwAEFGW]")); QRegularExpressionMatch rxMatch; - int pos = formatSpecifier.indexOf(rxFormat, 0, &rxMatch); - if (pos != -1) { - return true; - } - return false; + return formatSpecifier.indexOf(rxFormat, 0, &rxMatch) != -1; } //TODO: similar code here and above @@ -393,7 +356,7 @@ QStringList DimensionFormatter::getPrefixSuffixSpec(const QString& fSpec) const result.append(formatSuffix); result.append(match); } else { //printf format not found! - Base::Console().Warning("Warning - no numeric format in formatSpec %s - %s\n", + Base::Console().warning("Warning - no numeric format in formatSpec %s - %s\n", qPrintable(fSpec), m_dimension->getNameInDocument()); result.append(QString()); result.append(QString()); @@ -458,7 +421,7 @@ bool DimensionFormatter::isTooSmall(const double value, const QString& formatSpe return true; } } else { - Base::Console().Warning("Failed to parse dimension format spec\n"); + Base::Console().warning("Failed to parse dimension format spec\n"); } return false; } diff --git a/src/Mod/TechDraw/App/DimensionFormatter.h b/src/Mod/TechDraw/App/DimensionFormatter.h index dd100ecce0..c5a3194179 100644 --- a/src/Mod/TechDraw/App/DimensionFormatter.h +++ b/src/Mod/TechDraw/App/DimensionFormatter.h @@ -41,28 +41,28 @@ public: UNIT // return only the unit of measure }; - DimensionFormatter() {} - DimensionFormatter(DrawViewDimension* dim) { m_dimension = dim; } + DimensionFormatter() = default; + explicit DimensionFormatter(DrawViewDimension* dim) + : m_dimension {dim} + {} ~DimensionFormatter() = default; //void setDimension(DrawViewDimension* dim) { m_dimension = dim; } bool isMultiValueSchema() const; - std::string formatValue(const qreal value, - const QString& qFormatSpec, - const Format partial, - const bool isDim) const; - std::string getFormattedToleranceValue(const Format partial) const; - std::pair getFormattedToleranceValues(const Format partial) const; - std::string getFormattedDimensionValue(const Format partial) const; + std::string formatValue(qreal value, const QString& qFormatSpec, Format partial, bool isDim) const; + std::string getFormattedToleranceValue(Format partial) const; + std::pair getFormattedToleranceValues(Format partial) const; + std::string getFormattedDimensionValue(Format partial) const; QStringList getPrefixSuffixSpec(const QString& fSpec) const; std::string getDefaultFormatSpec(bool isToleranceFormat) const; - bool isTooSmall(const double value, const QString& formatSpec) const; - QString formatValueToSpec(const double value, QString formatSpecifier) const; - bool isNumericFormat(const QString& formatSpecifier) const; private: - DrawViewDimension* m_dimension; + bool isTooSmall(double value, const QString& formatSpec) const; + QString formatValueToSpec(double value, QString formatSpecifier) const; + bool isNumericFormat(const QString& formatSpecifier) const; + + DrawViewDimension* m_dimension {nullptr}; }; -} //end namespace TechDraw +} // end namespace TechDraw #endif diff --git a/src/Mod/TechDraw/App/DimensionGeometry.cpp b/src/Mod/TechDraw/App/DimensionGeometry.cpp index 67b3b1cdbe..a6187345e3 100644 --- a/src/Mod/TechDraw/App/DimensionGeometry.cpp +++ b/src/Mod/TechDraw/App/DimensionGeometry.cpp @@ -114,8 +114,8 @@ void pointPair::invertY() void pointPair::dump(const std::string& text) const { - Base::Console().Message("pointPair - %s\n", text.c_str()); - Base::Console().Message("pointPair - first: %s second: %s\n", + Base::Console().message("pointPair - %s\n", text.c_str()); + Base::Console().message("pointPair - first: %s second: %s\n", DU::formatVector(first()).c_str(), DU::formatVector(second()).c_str()); } @@ -233,10 +233,10 @@ anglePoints anglePoints::toDisplayForm(DrawViewPart* dvp) const } void anglePoints::dump(const std::string& text) const { - Base::Console().Message("anglePoints - %s\n", text.c_str()); - Base::Console().Message("anglePoints - ends - first: %s second: %s\n", + Base::Console().message("anglePoints - %s\n", text.c_str()); + Base::Console().message("anglePoints - ends - first: %s second: %s\n", DU::formatVector(first()).c_str(), DU::formatVector(second()).c_str()); - Base::Console().Message("anglePoints - vertex: %s\n", DU::formatVector(vertex()).c_str()); + Base::Console().message("anglePoints - vertex: %s\n", DU::formatVector(vertex()).c_str()); } arcPoints::arcPoints() : @@ -350,17 +350,17 @@ arcPoints arcPoints::toCanonicalForm(DrawViewPart* dvp) const void arcPoints::dump(const std::string& text) const { - Base::Console().Message("arcPoints - %s\n", text.c_str()); - Base::Console().Message("arcPoints - radius: %.3f center: %s\n", radius, + Base::Console().message("arcPoints - %s\n", text.c_str()); + Base::Console().message("arcPoints - radius: %.3f center: %s\n", radius, DrawUtil::formatVector(center).c_str()); - Base::Console().Message("arcPoints - isArc: %d arcCW: %d\n", isArc, arcCW); - Base::Console().Message("arcPoints - onCurve: %s %s\n", + Base::Console().message("arcPoints - isArc: %d arcCW: %d\n", isArc, arcCW); + Base::Console().message("arcPoints - onCurve: %s %s\n", DrawUtil::formatVector(onCurve.first()).c_str(), DrawUtil::formatVector(onCurve.second()).c_str()); - Base::Console().Message("arcPoints - arcEnds: %s %s\n", + Base::Console().message("arcPoints - arcEnds: %s %s\n", DrawUtil::formatVector(arcEnds.first()).c_str(), DrawUtil::formatVector(arcEnds.second()).c_str()); - Base::Console().Message("arcPoints - midArc: %s\n", DrawUtil::formatVector(midArc).c_str()); + Base::Console().message("arcPoints - midArc: %s\n", DrawUtil::formatVector(midArc).c_str()); } @@ -396,7 +396,7 @@ void areaPoint::invertY() void areaPoint::dump(const std::string& text) const { - Base::Console().Message("areaPoint - %s\n", text.c_str()); - Base::Console().Message("areaPoint - area: %.3f center: %s\n", area, + Base::Console().message("areaPoint - %s\n", text.c_str()); + Base::Console().message("areaPoint - area: %.3f center: %s\n", area, DrawUtil::formatVector(center).c_str()); } diff --git a/src/Mod/TechDraw/App/DimensionReferences.cpp b/src/Mod/TechDraw/App/DimensionReferences.cpp index a81f1bbc6b..c756a457f6 100644 --- a/src/Mod/TechDraw/App/DimensionReferences.cpp +++ b/src/Mod/TechDraw/App/DimensionReferences.cpp @@ -150,7 +150,7 @@ TopoDS_Shape ReferenceEntry::getGeometry2d() const } } catch (...) { - Base::Console().Message("RE::getGeometry2d - no shape for dimension 2d reference - gType: **%s**\n", gType.c_str()); + Base::Console().message("RE::getGeometry2d - no shape for dimension 2d reference - gType: **%s**\n", gType.c_str()); } return {}; diff --git a/src/Mod/TechDraw/App/DrawBrokenView.cpp b/src/Mod/TechDraw/App/DrawBrokenView.cpp index 170b09cd3a..0e7fb2c86f 100644 --- a/src/Mod/TechDraw/App/DrawBrokenView.cpp +++ b/src/Mod/TechDraw/App/DrawBrokenView.cpp @@ -151,7 +151,7 @@ App::DocumentObjectExecReturn* DrawBrokenView::execute() TopoDS_Shape shape = getSourceShape(); if (shape.IsNull()) { - Base::Console().Message("DBV::execute - %s - Source shape is Null.\n", getNameInDocument()); + Base::Console().message("DBV::execute - %s - Source shape is Null.\n", getNameInDocument()); return DrawView::execute(); // NOLINT } @@ -188,7 +188,7 @@ TopoDS_Shape DrawBrokenView::apply1Break(const App::DocumentObject& breakObj, co { auto breakPoints = breakPointsFromObj(breakObj); if (breakPoints.first.IsEqual(breakPoints.second, EWTOLERANCE)) { - Base::Console().Message("DBV::apply1Break - break points are equal\n"); + Base::Console().message("DBV::apply1Break - break points are equal\n"); return inShape; } @@ -203,7 +203,7 @@ TopoDS_Shape DrawBrokenView::apply1Break(const App::DocumentObject& breakObj, co auto halfSpace0 = makeHalfSpace(breakPoints.first, moveDir0, breakPoints.second); FCBRepAlgoAPI_Cut mkCut0(inShape, halfSpace0); if (!mkCut0.IsDone()) { - Base::Console().Message("DBV::apply1Break - cut0 failed\n"); + Base::Console().message("DBV::apply1Break - cut0 failed\n"); } TopoDS_Shape cut0 = mkCut0.Shape(); @@ -215,7 +215,7 @@ TopoDS_Shape DrawBrokenView::apply1Break(const App::DocumentObject& breakObj, co auto halfSpace1 = makeHalfSpace(breakPoints.second, moveDir1, breakPoints.first); FCBRepAlgoAPI_Cut mkCut1(inShape, halfSpace1); if (!mkCut1.IsDone()) { - Base::Console().Message("DBV::apply1Break - cut1 failed\n"); + Base::Console().message("DBV::apply1Break - cut1 failed\n"); } TopoDS_Shape cut1 = mkCut1.Shape(); @@ -402,7 +402,7 @@ bool DrawBrokenView::isBreakObjectSketch(const App::DocumentObject& breakObj) } // there should be 2 if (sketchEdges.size() != 2) { - Base::Console().Message("DBV::isBreakObjectSketch - wrong number of edges\n"); + Base::Console().message("DBV::isBreakObjectSketch - wrong number of edges\n"); return false; } // they should both have the same orientation @@ -553,7 +553,7 @@ std::pair DrawBrokenView::breakBoundsFromEdge(co } if (!DU::fpCompare(fabs(direction.Dot(stdY)), 1.0, EWTOLERANCE) ) { - Base::Console().Message("DBV::breakBoundsFromEdge - direction is not X or Y\n"); + Base::Console().message("DBV::breakBoundsFromEdge - direction is not X or Y\n"); // TODO: throw? return nonsense? } @@ -596,7 +596,7 @@ double DrawBrokenView::breaklineLengthFromSketch(const App::DocumentObject& brea if (sketchEdges.size() < 2) { // need 2 edges - Base::Console().Message("DBV::breaklineLengthFromSketch - not enough edges\n"); + Base::Console().message("DBV::breaklineLengthFromSketch - not enough edges\n"); } std::pair ends0 = SU::getEdgeEnds(sketchEdges.front()); @@ -1158,9 +1158,9 @@ bool DrawBrokenView::isDirectionReversed(Base::Vector3d direction) const void DrawBrokenView::printBreakList(const std::string& text, const BreakList& inBreaks) const { - Base::Console().Message("DBV - %s\n", text.c_str()); + Base::Console().message("DBV - %s\n", text.c_str()); for (auto& entry : inBreaks) { - Base::Console().Message(" > label: %s > low: %.3f > high: %.3f > net: %.3f\n", entry.breakObj->Label.getValue(), + Base::Console().message(" > label: %s > low: %.3f > high: %.3f > net: %.3f\n", entry.breakObj->Label.getValue(), entry.lowLimit, entry.highLimit, entry.netRemoved); } } diff --git a/src/Mod/TechDraw/App/DrawComplexSection.cpp b/src/Mod/TechDraw/App/DrawComplexSection.cpp index 76425f6a30..bbc518ecb6 100644 --- a/src/Mod/TechDraw/App/DrawComplexSection.cpp +++ b/src/Mod/TechDraw/App/DrawComplexSection.cpp @@ -174,7 +174,7 @@ TopoDS_Shape DrawComplexSection::makeCuttingTool(double dMax) bool isPositionOK = validateProfilePosition(profileWire, sectionCS); if (!isPositionOK) { //profile is not in a good position. Result might not be right. - Base::Console().Warning("DCS::makeCuttingTool - %s - profile is outside shape box\n", + Base::Console().warning("DCS::makeCuttingTool - %s - profile is outside shape box\n", getNameInDocument()); } @@ -302,7 +302,7 @@ void DrawComplexSection::makeSectionCut(const TopoDS_Shape& baseShape) waitingForAlign(true); } catch (...) { - Base::Console().Message("DCS::makeSectionCut - failed to make alignedPieces"); + Base::Console().message("DCS::makeSectionCut - failed to make alignedPieces"); return; } @@ -326,7 +326,6 @@ void DrawComplexSection::onSectionCutFinished() //for Aligned strategy, cut the rawShape by each segment of the tool void DrawComplexSection::makeAlignedPieces(const TopoDS_Shape& rawShape) { - if (!canBuild(getSectionCS(), CuttingToolWireObject.getValue())) { throw Base::RuntimeError("Profile is parallel to Section Normal"); } @@ -469,7 +468,7 @@ DrawComplexSection::findSectionPlaneIntersections(const TopoDS_Shape& shapeToInt { if (shapeToIntersect.IsNull()) { // this shouldn't happen - Base::Console().Warning("DCS::findSectionPlaneInter - %s - cut shape is Null\n", + Base::Console().warning("DCS::findSectionPlaneInter - %s - cut shape is Null\n", getNameInDocument()); return {}; } @@ -486,7 +485,7 @@ TopoDS_Compound DrawComplexSection::singleToolIntersections(const TopoDS_Shape& App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); if (!isLinearProfile(toolObj)) { //TODO: special handling here - // Base::Console().Message("DCS::singleToolIntersection - profile has curves\n"); + // Base::Console().message("DCS::singleToolIntersection - profile has curves\n"); } BRep_Builder builder; @@ -526,7 +525,7 @@ TopoDS_Compound DrawComplexSection::alignedToolIntersections(const TopoDS_Shape& App::DocumentObject* toolObj = CuttingToolWireObject.getValue(); if (!isLinearProfile(toolObj)) { //TODO: special handling here? - // Base::Console().Message("DCS::alignedToolIntersection - profile has curves\n"); + // Base::Console().message("DCS::alignedToolIntersection - profile has curves\n"); } gp_Pln effectivePlane = getSectionPlane(); @@ -730,7 +729,7 @@ TopoDS_Wire DrawComplexSection::makeSectionLineWire() } else { //probably can't happen as cut profile has been checked before this - Base::Console().Message("DCS::makeSectionLineGeometry - profile is type: %d\n", + Base::Console().message("DCS::makeSectionLineGeometry - profile is type: %d\n", static_cast(sScaled.ShapeType())); return TopoDS_Wire(); } @@ -817,7 +816,7 @@ bool DrawComplexSection::validateOffsetProfile(TopoDS_Wire profile, Base::Vector if (angleRad < angleThresholdRad && angleRad > 0.0) { // profile segment is slightly skewed. possible bad SectionNormal? - Base::Console().Warning("%s profile is slightly skewed. Check SectionNormal low decimal places\n", + Base::Console().warning("%s profile is slightly skewed. Check SectionNormal low decimal places\n", getNameInDocument()); return false; } @@ -1419,13 +1418,13 @@ std::vector> DrawComplexSection::getSegmentViewDi if (!checkSectionCS()) { // results will likely be incorrect // this message will show for every recompute of the complex section. - Base::Console().Warning("Coordinate system for ComplexSection is invalid. Check SectionNormal, Direction or XDirection.\n"); + Base::Console().warning("Coordinate system for ComplexSection is invalid. Check SectionNormal, Direction or XDirection.\n"); } auto profileVector = Base::convertTo(makeProfileVector(profileWire)); auto parallelDot = profileVector.Dot(sectionNormal); if (DU::fpCompare(std::fabs(parallelDot), 1, EWTOLERANCE)) { - Base::Console().Warning("Section normal is parallel to profile vector. Results may be incorrect.\n"); + Base::Console().warning("Section normal is parallel to profile vector. Results may be incorrect.\n"); } auto profilePlanWire = closeProfile(profileWire, sectionNormal, m_shapeSize); diff --git a/src/Mod/TechDraw/App/DrawDimHelper.cpp b/src/Mod/TechDraw/App/DrawDimHelper.cpp index 11f0c81063..f5fd78f9d3 100644 --- a/src/Mod/TechDraw/App/DrawDimHelper.cpp +++ b/src/Mod/TechDraw/App/DrawDimHelper.cpp @@ -81,7 +81,7 @@ DrawViewDimension* DrawDimHelper::makeExtentDim(DrawViewPart* dvp, DrawViewDimension* DrawDimHelper::makeExtentDim(DrawViewPart* dvp, std::vector edgeNames, int direction) { - // Base::Console().Message("DDH::makeExtentDim() - dvp: %s edgeNames: %d\n", + // Base::Console().message("DDH::makeExtentDim() - dvp: %s edgeNames: %d\n", // dvp->Label.getValue(), edgeNames.size()); if (!dvp) { return nullptr; @@ -147,7 +147,7 @@ void DrawDimHelper::makeExtentDim3d(DrawViewPart* dvp, const std::string& dimTyp void DrawDimHelper::makeExtentDim3d(DrawViewPart* dvp, ReferenceVector references, int direction) { - // Base::Console().Message("DDH::makeExtentDim3d() - dvp: %s references: %d\n", + // Base::Console().message("DDH::makeExtentDim3d() - dvp: %s references: %d\n", // dvp->Label.getValue(), references.size()); if (!dvp) { return; @@ -205,7 +205,7 @@ void DrawDimHelper::makeExtentDim3d(DrawViewPart* dvp, ReferenceVector reference std::pair DrawDimHelper::minMax(DrawViewPart* dvp, std::vector edgeNames, int direction) { - // Base::Console().Message("DDH::minMax() - edgeName: %d\n", edgeNames.size()); + // Base::Console().message("DDH::minMax() - edgeName: %d\n", edgeNames.size()); std::pair result; Base::Vector3d refMin; Base::Vector3d refMax; @@ -297,7 +297,7 @@ DrawDimHelper::minMax(DrawViewPart* dvp, std::vector edgeNames, int //computation intensive for a cosmetic result. gp_Pnt DrawDimHelper::findClosestPoint(std::vector inEdges, TopoDS_Edge& boundary) { - // Base::Console().Message("DDH::findClosestPoint() - edges: %d\n", inEdges.size()); + // Base::Console().message("DDH::findClosestPoint() - edges: %d\n", inEdges.size()); // //find an extent point that is actually on one of the curves double minDistance(std::numeric_limits::max()); @@ -305,12 +305,12 @@ gp_Pnt DrawDimHelper::findClosestPoint(std::vector inEdges, TopoDS_ for (auto& edge : inEdges) { BRepExtrema_DistShapeShape extss(edge, boundary); if (!extss.IsDone()) { - Base::Console().Warning( + Base::Console().warning( "DDH::findClosestPoint - BRepExtrema_DistShapeShape failed - 1\n"); continue; } if (extss.NbSolution() == 0) { - Base::Console().Warning( + Base::Console().warning( "DDH::findClosestPoint - BRepExtrema_DistShapeShape failed - 2\n"); continue; } @@ -325,7 +325,7 @@ gp_Pnt DrawDimHelper::findClosestPoint(std::vector inEdges, TopoDS_ std::pair DrawDimHelper::minMax3d(DrawViewPart* dvp, ReferenceVector references, int direction) { - // Base::Console().Message("DDH::minMax3d() - references: %d\n", references.size()); + // Base::Console().message("DDH::minMax3d() - references: %d\n", references.size()); std::pair result; Base::Vector3d refMin; Base::Vector3d refMax; @@ -420,7 +420,7 @@ DrawDimHelper::makeDistDim(DrawViewPart* dvp, std::string dimType, Base::Vector3d inMax,//expects scaled from makeExtentDim bool extent) { - // Base::Console().Message("DDH::makeDistDim() - inMin: %s inMax: %s\n", + // Base::Console().message("DDH::makeDistDim() - inMin: %s inMax: %s\n", // DrawUtil::formatVector(inMin).c_str(), // DrawUtil::formatVector(inMax).c_str()); TechDraw::DrawPage* page = dvp->findParentPage(); diff --git a/src/Mod/TechDraw/App/DrawGeomHatch.cpp b/src/Mod/TechDraw/App/DrawGeomHatch.cpp index 1728e86b2e..9afc7d4539 100644 --- a/src/Mod/TechDraw/App/DrawGeomHatch.cpp +++ b/src/Mod/TechDraw/App/DrawGeomHatch.cpp @@ -126,7 +126,7 @@ void DrawGeomHatch::onChanged(const App::Property* prop) App::DocumentObjectExecReturn *DrawGeomHatch::execute() { -// Base::Console().Message("DGH::execute()\n"); +// Base::Console().message("DGH::execute()\n"); //does execute even need to exist? Its all about the property value changes DrawViewPart* parent = getSourceView(); if (parent) { @@ -145,7 +145,7 @@ void DrawGeomHatch::onDocumentRestored() void DrawGeomHatch::replacePatIncluded(std::string newHatchFileName) { -// Base::Console().Message("DGH::replaceFileIncluded(%s)\n", newHatchFileName.c_str()); +// Base::Console().message("DGH::replaceFileIncluded(%s)\n", newHatchFileName.c_str()); if (newHatchFileName.empty()) { return; } @@ -160,13 +160,13 @@ void DrawGeomHatch::replacePatIncluded(std::string newHatchFileName) void DrawGeomHatch::setupObject() { -// Base::Console().Message("DGH::setupObject()\n"); +// Base::Console().message("DGH::setupObject()\n"); replacePatIncluded(FilePattern.getValue()); } void DrawGeomHatch::unsetupObject() { -// Base::Console().Message("DGH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); +// Base::Console().message("DGH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); App::DocumentObject* source = Source.getValue(); DrawView* dv = freecad_cast(source); if (dv) { @@ -179,7 +179,7 @@ void DrawGeomHatch::unsetupObject() void DrawGeomHatch::makeLineSets() { -// Base::Console().Message("DGH::makeLineSets()\n"); +// Base::Console().message("DGH::makeLineSets()\n"); if (!PatIncluded.isEmpty() && !NamePattern.isEmpty()) { m_lineSets.clear(); @@ -229,7 +229,7 @@ std::vector DrawGeomHatch::getDecodedSpecsFromFile(std::string file { Base::FileInfo fi(fileSpec); if (!fi.isReadable()) { - Base::Console().Error("DrawGeomHatch::getDecodedSpecsFromFile not able to open %s!\n", fileSpec.c_str()); + Base::Console().error("DrawGeomHatch::getDecodedSpecsFromFile not able to open %s!\n", fileSpec.c_str()); return std::vector(); } return PATLineSpec::getSpecsForPattern(fileSpec, myPattern); @@ -307,7 +307,7 @@ std::vector DrawGeomHatch::getTrimmedLines(DrawViewPart* source, double hatchRotation, Base::Vector3d hatchOffset) { -// Base::Console().Message("DGH::getTrimmedLines() - rotation: %.3f hatchOffset: %s\n", hatchRotation, DrawUtil::formatVector(hatchOffset).c_str()); +// Base::Console().message("DGH::getTrimmedLines() - rotation: %.3f hatchOffset: %s\n", hatchRotation, DrawUtil::formatVector(hatchOffset).c_str()); (void)source; std::vector result; @@ -444,7 +444,7 @@ std::vector DrawGeomHatch::makeEdgeOverlay(PATLineSpec hatchLine, B // we handle hatch as a set of parallel lines made of dashes, here we loop on each line for (int i = firstRepeatIndex ; i <= lastRepeatIndex ; ++i) { Base::Vector3d currentOrigin = origin + static_cast(i) * hatchIntervalAndOffset; - + int firstDashIndex, lastDashIndex; if (std::abs(hatchDirection.x) > std::abs(hatchDirection.y)) { // we compute intersections with minX and maxX firstDashIndex = (hatchDirection.x > 0.) @@ -499,7 +499,7 @@ TopoDS_Edge DrawGeomHatch::makeLine(const Base::Vector3d& s, const Base::Vector3 //! these will be clipped to shape on the gui side std::vector DrawGeomHatch::getFaceOverlay(int iFace) { -// Base::Console().Message("TRACE - DGH::getFaceOverlay(%d)\n", iFace); +// Base::Console().message("TRACE - DGH::getFaceOverlay(%d)\n", iFace); std::vector result; DrawViewPart* source = getSourceView(); if (!source || diff --git a/src/Mod/TechDraw/App/DrawHatch.cpp b/src/Mod/TechDraw/App/DrawHatch.cpp index ac049443ba..904cb10546 100644 --- a/src/Mod/TechDraw/App/DrawHatch.cpp +++ b/src/Mod/TechDraw/App/DrawHatch.cpp @@ -126,7 +126,7 @@ bool DrawHatch::affectsFace(int i) //remove a subElement(Face) from Source PropertyLinkSub bool DrawHatch::removeSub(std::string toRemove) { -// Base::Console().Message("DH::removeSub(%s)\n", toRemove.c_str()); +// Base::Console().message("DH::removeSub(%s)\n", toRemove.c_str()); bool removed = false; const std::vector &sourceNames = Source.getSubValues(); std::vector newList; @@ -146,7 +146,7 @@ bool DrawHatch::removeSub(std::string toRemove) bool DrawHatch::removeSub(int i) { -// Base::Console().Message("DH::removeSub(%d)\n", i); +// Base::Console().message("DH::removeSub(%d)\n", i); std::stringstream ss; ss << "Face" << i; return removeSub(ss.str()); @@ -160,7 +160,7 @@ bool DrawHatch::empty(void) void DrawHatch::replaceFileIncluded(std::string newHatchFileName) { -// Base::Console().Message("DH::replaceFileIncluded(%s)\n", newHatchFileName.c_str()); +// Base::Console().message("DH::replaceFileIncluded(%s)\n", newHatchFileName.c_str()); if (newHatchFileName.empty()) { return; } @@ -175,13 +175,13 @@ void DrawHatch::replaceFileIncluded(std::string newHatchFileName) void DrawHatch::setupObject() { -// Base::Console().Message("DH::setupObject()\n"); +// Base::Console().message("DH::setupObject()\n"); replaceFileIncluded(HatchPattern.getValue()); } void DrawHatch::unsetupObject(void) { -// Base::Console().Message("DH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); +// Base::Console().message("DH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); App::DocumentObject* source = Source.getValue(); DrawView* dv = freecad_cast(source); if (dv) { diff --git a/src/Mod/TechDraw/App/DrawLeaderLine.cpp b/src/Mod/TechDraw/App/DrawLeaderLine.cpp index 4b2bf7f63b..e2aa00a4a7 100644 --- a/src/Mod/TechDraw/App/DrawLeaderLine.cpp +++ b/src/Mod/TechDraw/App/DrawLeaderLine.cpp @@ -130,7 +130,7 @@ short DrawLeaderLine::mustExecute() const App::DocumentObjectExecReturn *DrawLeaderLine::execute() { - // Base::Console().Message("DLL::execute()\n"); + // Base::Console().message("DLL::execute()\n"); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } @@ -166,7 +166,7 @@ bool DrawLeaderLine::keepUpdated() double DrawLeaderLine::getBaseScale() const { -// Base::Console().Message("DLL::getBaseScale()\n"); +// Base::Console().message("DLL::getBaseScale()\n"); DrawView* parent = getBaseView(); if (!parent) { return 1.0; @@ -176,7 +176,7 @@ double DrawLeaderLine::getBaseScale() const double DrawLeaderLine::getScale() const { -// Base::Console().Message("DLL::getScale()\n"); +// Base::Console().message("DLL::getScale()\n"); if (!Scalable.getValue()) { return 1.0; } @@ -296,9 +296,9 @@ Base::Vector3d DrawLeaderLine::lastSegmentDirection() const //! pagePoints are in mm from bottom left of page. DrawLeaderLine* DrawLeaderLine::makeLeader(DrawViewPart* parent, std::vector pagePoints, int iStartSymbol, int iEndSymbol) { - Base::Console().Message("DLL::makeLeader(%s, %d, %d, %d)\n", parent->getNameInDocument(), pagePoints.size(), iStartSymbol, iEndSymbol); + Base::Console().message("DLL::makeLeader(%s, %d, %d, %d)\n", parent->getNameInDocument(), pagePoints.size(), iStartSymbol, iEndSymbol); if (pagePoints.size() < 2) { - Base::Console().Message("DLL::makeLeader - not enough pagePoints\n"); + Base::Console().message("DLL::makeLeader - not enough pagePoints\n"); return {}; } @@ -364,7 +364,7 @@ std::vector DrawLeaderLine::getScaledAndRotatedPoints(bool doSc auto dvp = getBaseView(); if (!dvp) { // document is restoring? - // Base::Console().Message("DLL::getScaledAndRotatedPoints - no DV\n"); + // Base::Console().message("DLL::getScaledAndRotatedPoints - no DV\n"); return {}; } @@ -455,7 +455,7 @@ bool DrawLeaderLine::isParentReady() const if (!parent || (dvp && !dvp->hasGeometry())) { // still restoring or // we are attached to a dvp that has no geometry, so don't bother trying to draw yet - Base::Console().Message("DLL:: - no parent or geometry\n"); + Base::Console().message("DLL:: - no parent or geometry\n"); return false; } return true; @@ -468,9 +468,9 @@ bool DrawLeaderLine::getDefAuto() const void DrawLeaderLine::dumpWaypoints(const std::vector &points, const std::string &label) { - Base::Console().Message("DLL::dumpWaypoints - %s\n", label.c_str()); + Base::Console().message("DLL::dumpWaypoints - %s\n", label.c_str()); for (auto& p : points) { - Base::Console().Message(">>>> a point: %s\n", DU::formatVector(p).c_str()); + Base::Console().message(">>>> a point: %s\n", DU::formatVector(p).c_str()); } } diff --git a/src/Mod/TechDraw/App/DrawPage.cpp b/src/Mod/TechDraw/App/DrawPage.cpp index fb86cc0b4b..2c3c982b0c 100644 --- a/src/Mod/TechDraw/App/DrawPage.cpp +++ b/src/Mod/TechDraw/App/DrawPage.cpp @@ -99,7 +99,7 @@ void DrawPage::onChanged(const App::Property* prop) if (prop == &KeepUpdated && KeepUpdated.getValue()) { if (!isRestoring() && !isUnsetting()) { //would be nice if this message was displayed immediately instead of after the recomputeFeature - Base::Console().Message("Rebuilding Views for: %s/%s\n", getNameInDocument(), + Base::Console().message("Rebuilding Views for: %s/%s\n", getNameInDocument(), Label.getValue()); updateAllViews(); purgeTouched(); @@ -270,7 +270,7 @@ int DrawPage::addView(App::DocumentObject* docObj, bool setPosition) //check if View fits on Page if (!view->checkFit(this)) { - Base::Console().Warning("%s is larger than page. Will be scaled.\n", + Base::Console().warning("%s is larger than page. Will be scaled.\n", view->getNameInDocument()); view->ScaleType.setValue("Automatic"); } @@ -325,7 +325,7 @@ void DrawPage::onDocumentRestored() void DrawPage::redrawCommand() { - // Base::Console().Message("DP::redrawCommand()\n"); + // Base::Console().message("DP::redrawCommand()\n"); forceRedraw(true); updateAllViews(); forceRedraw(false); @@ -333,7 +333,7 @@ void DrawPage::redrawCommand() void DrawPage::updateAllViews() { - // Base::Console().Message("DP::updateAllViews()\n"); + // Base::Console().message("DP::updateAllViews()\n"); //unordered list of views within page std::vector featViews = getAllViews(); @@ -374,7 +374,7 @@ std::vector DrawPage::getViews() const v = static_cast(v)->getLinkedObject(); addChildren = true; } - + if (!v->isDerivedFrom()) { continue; } @@ -441,7 +441,7 @@ void DrawPage::unsetupObject() Views.setValues(emptyViews); } catch (...) { - Base::Console().Warning("DP::unsetupObject - %s - error while deleting children\n", + Base::Console().warning("DP::unsetupObject - %s - error while deleting children\n", getNameInDocument()); } diff --git a/src/Mod/TechDraw/App/DrawProjGroup.cpp b/src/Mod/TechDraw/App/DrawProjGroup.cpp index 591ada8f52..fd100ed107 100644 --- a/src/Mod/TechDraw/App/DrawProjGroup.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroup.cpp @@ -92,7 +92,7 @@ DrawProjGroup::DrawProjGroup() //TODO: this duplicates code in DVP std::vector DrawProjGroup::getAllSources() const { - // Base::Console().Message("DPG::getAllSources()\n"); + // Base::Console().message("DPG::getAllSources()\n"); const std::vector links = Source.getValues(); std::vector xLinks; XSource.getLinks(xLinks); @@ -169,7 +169,7 @@ void DrawProjGroup::onChanged(const App::Property* prop) App::DocumentObjectExecReturn* DrawProjGroup::execute() { - // Base::Console().Message("DPG::execute() - %s - waitingForChildren: %d\n", + // Base::Console().message("DPG::execute() - %s - waitingForChildren: %d\n", // getNameInDocument(), waitingForChildren()); if (!keepUpdated()) return App::DocumentObject::StdReturn; @@ -227,7 +227,7 @@ short DrawProjGroup::mustExecute() const void DrawProjGroup::reportReady() { - // Base::Console().Message("DPG::reportReady - waitingForChildren: %d\n", waitingForChildren()); + // Base::Console().message("DPG::reportReady - waitingForChildren: %d\n", waitingForChildren()); if (waitingForChildren()) { //not ready yet return; @@ -255,7 +255,7 @@ TechDraw::DrawPage* DrawProjGroup::getPage() const { return findParentPage(); } //does the unscaled DPG fit on the page? bool DrawProjGroup::checkFit() const { - // Base::Console().Message("DPG::checkFit() - %s\n", getNameInDocument()); + // Base::Console().message("DPG::checkFit() - %s\n", getNameInDocument()); if (waitingForChildren()) { //assume everything fits since we don't know what size the children are return true; @@ -268,7 +268,7 @@ bool DrawProjGroup::checkFit() const bool DrawProjGroup::checkFit(DrawPage* page) const { - // Base::Console().Message("DPG::checkFit(page) - %s\n", getNameInDocument()); + // Base::Console().message("DPG::checkFit(page) - %s\n", getNameInDocument()); if (waitingForChildren()) { return true; } @@ -283,7 +283,7 @@ bool DrawProjGroup::checkFit(DrawPage* page) const //calculate a scale that fits all views on page double DrawProjGroup::autoScale() const { - // Base::Console().Message("DPG::autoScale() - %s\n", getNameInDocument()); + // Base::Console().message("DPG::autoScale() - %s\n", getNameInDocument()); auto page = findParentPage(); if (!page) { throw Base::RuntimeError("No page is assigned to this feature"); @@ -293,7 +293,7 @@ double DrawProjGroup::autoScale() const double DrawProjGroup::autoScale(double w, double h) const { - // Base::Console().Message("DPG::autoScale(%.3f, %.3f) - %s\n", w, h, getNameInDocument()); + // Base::Console().message("DPG::autoScale(%.3f, %.3f) - %s\n", w, h, getNameInDocument()); //get the space used by views + white space at 1:1 scale QRectF bigBox = getRect(false);//unscaled box @@ -309,7 +309,7 @@ QRectF DrawProjGroup::getRect() const { return getRect(true); } QRectF DrawProjGroup::getRect(bool scaled) const { - // Base::Console().Message("DPG::getRect - views: %d\n", Views.getValues().size()); + // Base::Console().message("DPG::getRect - views: %d\n", Views.getValues().size()); std::array viewPtrs; arrangeViewPointers(viewPtrs); double totalWidth, totalHeight; @@ -359,7 +359,7 @@ App::DocumentObject* DrawProjGroup::getProjObj(const char* viewProjType) const auto projPtr(freecad_cast(it)); if (!projPtr) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error("PROBLEM - DPG::getProjObj - non DPGI entry in Views! %s / %s\n", + Base::Console().error("PROBLEM - DPG::getProjObj - non DPGI entry in Views! %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } @@ -377,7 +377,7 @@ DrawProjGroupItem* DrawProjGroup::getProjItem(const char* viewProjType) const auto result(dynamic_cast(docObj)); if (!result && docObj) { //should never have a item in DPG that is not a DPGI. - Base::Console().Error("PROBLEM - DPG::getProjItem finds non-DPGI in Group %s / %s\n", + Base::Console().error("PROBLEM - DPG::getProjItem finds non-DPGI in Group %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } @@ -409,7 +409,7 @@ bool DrawProjGroup::hasProjection(const char* viewProjType) const auto view(dynamic_cast(it)); if (!view) { //should never have a item in DPG that is not a DPGI. - Base::Console().Error("PROBLEM - DPG::hasProjection finds non-DPGI in Group %s / %s\n", + Base::Console().error("PROBLEM - DPG::hasProjection finds non-DPGI in Group %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } @@ -423,12 +423,12 @@ bool DrawProjGroup::hasProjection(const char* viewProjType) const bool DrawProjGroup::canDelete(const char* viewProjType) const { - // Base::Console().Message("DPG::canDelete(%s)\n", viewProjType); + // Base::Console().message("DPG::canDelete(%s)\n", viewProjType); for (const auto it : Views.getValues()) { auto view(dynamic_cast(it)); if (!view) { //should never have a item in DPG that is not a DPGI. - Base::Console().Error("PROBLEM - DPG::hasProjection finds non-DPGI in Group %s / %s\n", + Base::Console().error("PROBLEM - DPG::hasProjection finds non-DPGI in Group %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } @@ -453,13 +453,13 @@ bool DrawProjGroup::canDelete(const char* viewProjType) const App::DocumentObject* DrawProjGroup::addProjection(const char* viewProjType) { - // Base::Console().Message("DPG::addProjection(%s)\n", viewProjType ? viewProjType : "null"); + // Base::Console().message("DPG::addProjection(%s)\n", viewProjType ? viewProjType : "null"); DrawProjGroupItem* view(nullptr); std::pair vecs; DrawPage* dp = findParentPage(); if (!dp) - Base::Console().Error("DPG:addProjection - %s - DPG is not on a page!\n", + Base::Console().error("DPG:addProjection - %s - DPG is not on a page!\n", getNameInDocument()); if (checkViewProjType(viewProjType) && !hasProjection(viewProjType)) { @@ -467,7 +467,7 @@ App::DocumentObject* DrawProjGroup::addProjection(const char* viewProjType) view = getDocument()->addObject(FeatName.c_str()); if (!view) { //should never happen that we create a DPGI that isn't a DPGI!! - Base::Console().Error("PROBLEM - DPG::addProjection - created a non DPGI! %s / %s\n", + Base::Console().error("PROBLEM - DPG::addProjection - created a non DPGI! %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: new projection is not a DPGI!"); } @@ -523,7 +523,7 @@ int DrawProjGroup::removeProjection(const char* viewProjType) } else { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error( + Base::Console().error( "PROBLEM - DPG::removeProjection - tries to remove non DPGI! %s / %s\n", getNameInDocument(), viewProjType); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); @@ -547,7 +547,7 @@ int DrawProjGroup::purgeProjections() } else { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error("PROBLEM - DPG::purgeProjection - tries to remove non DPGI! %s\n", + Base::Console().error("PROBLEM - DPG::purgeProjection - tries to remove non DPGI! %s\n", getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } @@ -568,13 +568,13 @@ std::pair DrawProjGroup::getDirsFromFront(DrawPr std::pair DrawProjGroup::getDirsFromFront(ProjDirection viewType) { - // Base::Console().Message("DPG::getDirsFromFront(%s)\n", viewType.c_str()); + // Base::Console().message("DPG::getDirsFromFront(%s)\n", viewType.c_str()); std::pair result; Base::Vector3d projDir, rotVec; DrawProjGroupItem* anch = getAnchor(); if (!anch) { - Base::Console().Warning("DPG::getDirsFromFront - %s - No Anchor!\n", Label.getValue()); + Base::Console().warning("DPG::getDirsFromFront - %s - No Anchor!\n", Label.getValue()); throw Base::RuntimeError("Project Group missing Anchor projection item"); } @@ -594,7 +594,7 @@ gp_Dir DrawProjGroup::vec2dir(Base::Vector3d v) //this can be improved. this implementation positions views too far apart. Base::Vector3d DrawProjGroup::getXYPosition(const char* viewTypeCStr) { - // Base::Console().Message("DPG::getXYPosition(%s)\n", Label.getValue()); + // Base::Console().message("DPG::getXYPosition(%s)\n", Label.getValue()); // Third Angle: FTL T FTRight 0 1 2 // L F Right Rear 3 4 5 6 // FBL B FBRight 7 8 9 @@ -761,7 +761,7 @@ int DrawProjGroup::getViewIndex(const char* viewTypeCStr) const projType = dp->ProjectionType.getValueAsString(); } else { - Base::Console().Warning( + Base::Console().warning( "DPG: %s - can not find parent page. Using default Projection Type. (1)\n", getNameInDocument()); int projConv = getDefProjConv(); @@ -835,9 +835,9 @@ void DrawProjGroup::arrangeViewPointers( projType = dp->ProjectionType.getValueAsString(); } else { - Base::Console().Error("DPG:arrangeViewPointers - %s - DPG is not on a page!\n", + Base::Console().error("DPG:arrangeViewPointers - %s - DPG is not on a page!\n", getNameInDocument()); - Base::Console().Warning( + Base::Console().warning( "DPG:arrangeViewPointers - using system default Projection Type\n", getNameInDocument()); int projConv = getDefProjConv(); @@ -850,7 +850,7 @@ void DrawProjGroup::arrangeViewPointers( // Iterate through views and populate viewPtrs if (strcmp(projType, "Third Angle") != 0 && strcmp(projType, "First Angle") != 0) { - Base::Console().Warning("DPG: %s - unknown Projection convention: %s\n", + Base::Console().warning("DPG: %s - unknown Projection convention: %s\n", getNameInDocument(), projType); throw Base::ValueError( "Unknown Projection convention in DrawProjGroup::arrangeViewPointers"); @@ -869,7 +869,7 @@ void DrawProjGroup::arrangeViewPointers( auto oView(freecad_cast(it)); if (!oView) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error( + Base::Console().error( "PROBLEM - DPG::arrangeViewPointers - non DPGI in Views! %s\n", getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); @@ -908,7 +908,7 @@ void DrawProjGroup::arrangeViewPointers( viewPtrs[thirdAngle ? 9 : 0] = oView; } else { - Base::Console().Warning("DPG: %s - unknown view type: %s. \n", + Base::Console().warning("DPG: %s - unknown view type: %s. \n", getNameInDocument(), viewTypeCStr); throw Base::TypeError( "Unknown view type in DrawProjGroup::arrangeViewPointers."); @@ -942,7 +942,7 @@ void DrawProjGroup::makeViewBbs(std::array(it)); if (!view) { @@ -956,7 +956,7 @@ void DrawProjGroup::recomputeChildren() void DrawProjGroup::autoPositionChildren() { - // Base::Console().Message("DPG::autoPositionChildren() - %s - waiting: %d\n", + // Base::Console().message("DPG::autoPositionChildren() - %s - waiting: %d\n", // getNameInDocument(), waitingForChildren()); for (const auto it : Views.getValues()) { auto view(freecad_cast(it)); @@ -975,7 +975,7 @@ void DrawProjGroup::autoPositionChildren() */ void DrawProjGroup::updateChildrenScale() { - // Base::Console().Message("DPG::updateChildrenScale() - waiting: %d\n", waitingForChildren()); + // Base::Console().message("DPG::updateChildrenScale() - waiting: %d\n", waitingForChildren()); for (const auto it : Views.getValues()) { auto view(freecad_cast(it)); if (!view) { @@ -998,7 +998,7 @@ void DrawProjGroup::updateChildrenSource() auto view(freecad_cast(it)); if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error( + Base::Console().error( "PROBLEM - DPG::updateChildrenSource - non DPGI entry in Views! %s\n", getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); @@ -1022,7 +1022,7 @@ void DrawProjGroup::updateChildrenLock() auto view(freecad_cast(it)); if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error( + Base::Console().error( "PROBLEM - DPG::updateChildrenLock - non DPGI entry in Views! %s\n", getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); @@ -1037,7 +1037,7 @@ void DrawProjGroup::updateChildrenEnforce(void) auto view(freecad_cast(it)); if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Error( + Base::Console().error( "PROBLEM - DPG::updateChildrenEnforce - non DPGI entry in Views! %s\n", getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); @@ -1183,7 +1183,7 @@ int DrawProjGroup::getDefProjConv() const { return Preferences::projectionAngle( */ void DrawProjGroup::dumpISO(const char* title) { - Base::Console().Message("DPG ISO: %s\n", title); + Base::Console().message("DPG ISO: %s\n", title); for (auto& docObj : Views.getValues()) { Base::Vector3d dir; Base::Vector3d axis; @@ -1192,7 +1192,7 @@ void DrawProjGroup::dumpISO(const char* title) dir = v->Direction.getValue(); axis = v->getXDirection(); - Base::Console().Message("%s: %s/%s\n", t.c_str(), DrawUtil::formatVector(dir).c_str(), + Base::Console().message("%s: %s/%s\n", t.c_str(), DrawUtil::formatVector(dir).c_str(), DrawUtil::formatVector(axis).c_str()); } } diff --git a/src/Mod/TechDraw/App/DrawProjGroupItem.cpp b/src/Mod/TechDraw/App/DrawProjGroupItem.cpp index 489e72afa3..1bba85f636 100644 --- a/src/Mod/TechDraw/App/DrawProjGroupItem.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroupItem.cpp @@ -108,7 +108,7 @@ bool DrawProjGroupItem::showLock() const App::DocumentObjectExecReturn *DrawProjGroupItem::execute() { -// Base::Console().Message("DPGI::execute() - %s / %s\n", getNameInDocument(), Label.getValue()); +// Base::Console().message("DPGI::execute() - %s / %s\n", getNameInDocument(), Label.getValue()); if (!keepUpdated()) { return DrawView::execute(); } @@ -135,7 +135,7 @@ App::DocumentObjectExecReturn *DrawProjGroupItem::execute() void DrawProjGroupItem::postHlrTasks() { -// Base::Console().Message("DPGI::postHlrTasks() - %s\n", getNameInDocument()); +// Base::Console().message("DPGI::postHlrTasks() - %s\n", getNameInDocument()); DrawViewPart::postHlrTasks(); DrawProjGroup* pGroup = getPGroup(); @@ -154,7 +154,7 @@ void DrawProjGroupItem::autoPosition() if (!pGroup) { return; } -// Base::Console().Message("DPGI::autoPosition(%s)\n", Label.getValue()); +// Base::Console().message("DPGI::autoPosition(%s)\n", Label.getValue()); if (LockPosition.getValue()) { return; } @@ -171,7 +171,7 @@ void DrawProjGroupItem::autoPosition() void DrawProjGroupItem::onDocumentRestored() { -// Base::Console().Message("DPGI::onDocumentRestored() - %s\n", getNameInDocument()); +// Base::Console().message("DPGI::onDocumentRestored() - %s\n", getNameInDocument()); DrawView::onDocumentRestored(); App::DocumentObjectExecReturn* rc = DrawProjGroupItem::execute(); if (rc) { @@ -191,7 +191,7 @@ bool DrawProjGroupItem::isAnchor() const Base::Vector3d DrawProjGroupItem::getXDirection() const { -// Base::Console().Message("DPGI::getXDirection() - %s\n", Label.getValue()); +// Base::Console().message("DPGI::getXDirection() - %s\n", Label.getValue()); Base::Vector3d result(1.0, 0.0, 0.0); //default X App::Property* prop = getPropertyByName("XDirection"); if (prop) { @@ -210,14 +210,14 @@ Base::Vector3d DrawProjGroupItem::getXDirection() const } } else { //not sure this branch can actually happen - Base::Console().Message("DPGI::getXDirection - unexpected branch taken!\n"); + Base::Console().message("DPGI::getXDirection - unexpected branch taken!\n"); prop = getPropertyByName("RotationVector"); if (prop) { result = RotationVector.getValue(); } else { - Base::Console().Message("DPGI::getXDirection - missing RotationVector and XDirection\n"); + Base::Console().message("DPGI::getXDirection - missing RotationVector and XDirection\n"); } } return result; @@ -227,7 +227,7 @@ Base::Vector3d DrawProjGroupItem::getLegacyX(const Base::Vector3d& pt, const Base::Vector3d& axis, const bool flip) const { -// Base::Console().Message("DPGI::getLegacyX() - %s\n", Label.getValue()); +// Base::Console().message("DPGI::getLegacyX() - %s\n", Label.getValue()); App::Property* prop = getPropertyByName("RotationVector"); if (prop) { Base::Vector3d result = RotationVector.getValue(); @@ -312,7 +312,7 @@ void DrawProjGroupItem::unsetupObject() } if (getPGroup()->getAnchor() == this && !getPGroup()->isUnsetting()) { - Base::Console().Warning("Warning - DPG (%s/%s) may be corrupt - Anchor deleted\n", + Base::Console().warning("Warning - DPG (%s/%s) may be corrupt - Anchor deleted\n", getPGroup()->getNameInDocument(), getPGroup()->Label.getValue()); getPGroup()->Anchor.setValue(nullptr); //this catches situation where DPGI is deleted w/o DPG::removeProjection } diff --git a/src/Mod/TechDraw/App/DrawProjectSplit.cpp b/src/Mod/TechDraw/App/DrawProjectSplit.cpp index 7853e729b6..dbf69c2f21 100644 --- a/src/Mod/TechDraw/App/DrawProjectSplit.cpp +++ b/src/Mod/TechDraw/App/DrawProjectSplit.cpp @@ -98,7 +98,7 @@ std::vector DrawProjectSplit::getEdgesForWalker(TopoDS_Shape shape, if (!DrawUtil::isZeroEdge(e, 2.0 * EWTOLERANCE)) { nonZero.push_back(e); } else { - Base::Console().Message("DPS::getEdgesForWalker found ZeroEdge!\n"); + Base::Console().message("DPS::getEdgesForWalker found ZeroEdge!\n"); } } @@ -140,7 +140,7 @@ bool DrawProjectSplit::isOnEdge(TopoDS_Edge e, TopoDS_Vertex v, double& param, b double dist = DrawUtil::simpleMinDist(v, e); if (dist < 0.0) { - Base::Console().Error("DPS::isOnEdge - simpleMinDist failed: %.3f\n", dist); + Base::Console().error("DPS::isOnEdge - simpleMinDist failed: %.3f\n", dist); return false; } else if (dist < Precision::Confusion()) { const gp_Pnt pt = BRep_Tool::Pnt(v); //have to duplicate method 3 to get param @@ -222,7 +222,7 @@ std::vector DrawProjectSplit::split1Edge(TopoDS_Edge e, std::vector double last = BRepLProp_CurveTool::LastParameter(adapt); if (first > last) { //TODO parms.reverse(); - Base::Console().Message("DPS::split1Edge - edge is backwards!\n"); + Base::Console().message("DPS::split1Edge - edge is backwards!\n"); return result; } std::vector parms; @@ -245,7 +245,7 @@ std::vector DrawProjectSplit::split1Edge(TopoDS_Edge e, std::vector } } catch (Standard_Failure&) { - Base::Console().Message("DPS::split1Edge failed building edge segment\n"); + Base::Console().message("DPS::split1Edge failed building edge segment\n"); } } return result; @@ -322,7 +322,7 @@ std::vector DrawProjectSplit::removeDuplicateEdges(std::vector DrawProjectSplit::scrubEdges(const std::vector& origEdges, std::vector &closedEdges) { -// Base::Console().Message("DPS::scrubEdges() - BaseGeom in: %d\n", origEdges.size()); +// Base::Console().message("DPS::scrubEdges() - BaseGeom in: %d\n", origEdges.size()); //make a copy of the input edges so the loose tolerances of face finding are //not applied to the real edge geometry. See TopoDS_Shape::TShape(). std::vector copyEdges; @@ -420,7 +420,7 @@ std::vector DrawProjectSplit::scrubEdges(const std::vector DrawProjectSplit::scrubEdges(std::vector& origEdges, std::vector &closedEdges) { -// Base::Console().Message("DPS::scrubEdges() - TopoDS_Edges in: %d\n", origEdges.size()); +// Base::Console().message("DPS::scrubEdges() - TopoDS_Edges in: %d\n", origEdges.size()); std::vector openEdges; // We must have at least 2 edges to perform the General Fuse operation @@ -428,7 +428,7 @@ std::vector DrawProjectSplit::scrubEdges(std::vector& if (origEdges.empty()) { //how did this happen? if Scale is zero, all the edges will be zero length, //but Scale property has constraint, so this shouldn't happen! - //Base::Console().Message("DPS::scrubEdges(2) - origEdges is empty\n"); + //Base::Console().message("DPS::scrubEdges(2) - origEdges is empty\n"); } else { TopoDS_Edge &edge = origEdges.front(); @@ -466,7 +466,7 @@ std::vector DrawProjectSplit::scrubEdges(std::vector& Standard_SStream errorStream; bopBuilder.DumpErrors(errorStream); const std::string &errorStr = errorStream.str(); - Base::Console().Error("DrawProjectSplit::scrubEdges - OCC fuse failed with error(s):\n%s\n", errorStr.c_str()); + Base::Console().error("DrawProjectSplit::scrubEdges - OCC fuse failed with error(s):\n%s\n", errorStr.c_str()); return std::vector(); } @@ -474,7 +474,7 @@ std::vector DrawProjectSplit::scrubEdges(std::vector& Standard_SStream warnStream; bopBuilder.DumpWarnings(warnStream); const std::string &warnStr = warnStream.str(); - Base::Console().Warning("DrawProjectSplit::scrubEdges - OCC fuse raised warning(s):\n%s\n", warnStr.c_str()); + Base::Console().warning("DrawProjectSplit::scrubEdges - OCC fuse raised warning(s):\n%s\n", warnStr.c_str()); } const TopoDS_Shape &bopResult = bopBuilder.Shape(); @@ -529,7 +529,7 @@ vertexMap DrawProjectSplit::getUniqueVertexes(std::vector inEdges) std::vector DrawProjectSplit::pruneUnconnected(vertexMap verts, std::vector edges) { -// Base::Console().Message("DPS::pruneUnconnected() - edges in: %d\n", edges.size()); +// Base::Console().message("DPS::pruneUnconnected() - edges in: %d\n", edges.size()); //check if edge ends are used at least twice => edge is joined to another edge std::vector newPile; std::vector deadEnds; @@ -589,7 +589,7 @@ bool DrawProjectSplit::sameEndPoints(const TopoDS_Edge &e1, const TopoDS_Edge &e //eliminate edges that overlap another edge std::vector DrawProjectSplit::removeOverlapEdges(const std::vector &inEdges) { -// Base::Console().Message("DPS::removeOverlapEdges() - %d edges in\n", inEdges.size()); +// Base::Console().message("DPS::removeOverlapEdges() - %d edges in\n", inEdges.size()); std::vector outEdges; std::vector overlapEdges; std::vector skipThisEdge(inEdges.size(), false); @@ -634,7 +634,7 @@ std::vector DrawProjectSplit::removeOverlapEdges(const std::vector< outEdges.insert(outEdges.end(), overlapEdges.begin(), overlapEdges.end()); } -// Base::Console().Message("DPS::removeOverlapEdges() - %d edges out\n", outEdges.size()); +// Base::Console().message("DPS::removeOverlapEdges() - %d edges out\n", outEdges.size()); return outEdges; } @@ -720,10 +720,10 @@ bool DrawProjectSplit::boxesIntersect(const TopoDS_Edge &edge0, const TopoDS_Edg //this is an aid to debugging and isn't used in normal processing. void DrawProjectSplit::dumpVertexMap(vertexMap verts) { - Base::Console().Message("DPS::dumpVertexMap - %d verts\n", verts.size()); + Base::Console().message("DPS::dumpVertexMap - %d verts\n", verts.size()); int iVert = 0; for (auto& item : verts) { - Base::Console().Message("%d: %s - %d\n",iVert, + Base::Console().message("%d: %s - %d\n",iVert, DrawUtil::formatVector(item.first).c_str(), item.second); iVert++; } diff --git a/src/Mod/TechDraw/App/DrawRichAnno.cpp b/src/Mod/TechDraw/App/DrawRichAnno.cpp index 24af1a1c02..890d664665 100644 --- a/src/Mod/TechDraw/App/DrawRichAnno.cpp +++ b/src/Mod/TechDraw/App/DrawRichAnno.cpp @@ -78,7 +78,7 @@ short DrawRichAnno::mustExecute() const App::DocumentObjectExecReturn *DrawRichAnno::execute() { -// Base::Console().Message("DRA::execute() - @ (%.3f, %.3f)\n", X.getValue(), Y.getValue()); +// Base::Console().message("DRA::execute() - @ (%.3f, %.3f)\n", X.getValue(), Y.getValue()); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } @@ -88,7 +88,7 @@ App::DocumentObjectExecReturn *DrawRichAnno::execute() DrawView* DrawRichAnno::getBaseView() const { -// Base::Console().Message("DRA::getBaseView() - %s\n", getNameInDocument()); +// Base::Console().message("DRA::getBaseView() - %s\n", getNameInDocument()); return freecad_cast(AnnoParent.getValue()); } @@ -97,7 +97,7 @@ DrawView* DrawRichAnno::getBaseView() const //more than 1 DrawPage claims a DrawRichAnno. DrawPage* DrawRichAnno::findParentPage() const { -// Base::Console().Message("DRA::findParentPage()\n"); +// Base::Console().message("DRA::findParentPage()\n"); if (!AnnoParent.getValue()) { return DrawView::findParentPage(); } diff --git a/src/Mod/TechDraw/App/DrawSVGTemplate.cpp b/src/Mod/TechDraw/App/DrawSVGTemplate.cpp index 3734327708..4150d95230 100644 --- a/src/Mod/TechDraw/App/DrawSVGTemplate.cpp +++ b/src/Mod/TechDraw/App/DrawSVGTemplate.cpp @@ -102,7 +102,7 @@ void DrawSVGTemplate::onSettingDocument() //? should this check for creation of a template or a page? void DrawSVGTemplate::slotCreatedObject(const App::DocumentObject& obj) { - // Base::Console().Message("DSVGT::slotCreatedObject()\n"); + // Base::Console().message("DSVGT::slotCreatedObject()\n"); if (!obj.isDerivedFrom()) { // we don't care return; @@ -112,7 +112,7 @@ void DrawSVGTemplate::slotCreatedObject(const App::DocumentObject& obj) void DrawSVGTemplate::slotDeletedObject(const App::DocumentObject& obj) { - // Base::Console().Message("DSVGT::slotDeletedObject()\n"); + // Base::Console().message("DSVGT::slotDeletedObject()\n"); if (!obj.isDerivedFrom()) { // we don't care return; @@ -206,12 +206,12 @@ bool DrawSVGTemplate::getTemplateDocument(std::string sourceFile, QDomDocument& } QFile templateFile(QString::fromStdString(sourceFile)); if (!templateFile.open(QIODevice::ReadOnly)) { - Base::Console().Error("DrawSVGTemplate::processTemplate can't read embedded template %s!\n", PageResult.getValue()); + Base::Console().error("DrawSVGTemplate::processTemplate can't read embedded template %s!\n", PageResult.getValue()); return false; } if (!templateDocument.setContent(&templateFile)) { - Base::Console().Error("DrawSVGTemplate::processTemplate - failed to parse file: %s\n", + Base::Console().error("DrawSVGTemplate::processTemplate - failed to parse file: %s\n", PageResult.getValue()); return false; } diff --git a/src/Mod/TechDraw/App/DrawTile.cpp b/src/Mod/TechDraw/App/DrawTile.cpp index a970831d2c..d08be9b314 100644 --- a/src/Mod/TechDraw/App/DrawTile.cpp +++ b/src/Mod/TechDraw/App/DrawTile.cpp @@ -69,7 +69,7 @@ short DrawTile::mustExecute() const App::DocumentObjectExecReturn *DrawTile::execute() { -// Base::Console().Message("DT::execute()\n"); +// Base::Console().message("DT::execute()\n"); return DocumentObject::execute(); } @@ -87,7 +87,7 @@ void DrawTile::handleChangedPropertyType(Base::XMLReader &reader, const char *Ty DrawView* DrawTile::getParent() const { -// Base::Console().Message("DT::getParent() - %s\n", getNameInDocument()); +// Base::Console().message("DT::getParent() - %s\n", getNameInDocument()); return freecad_cast(TileParent.getValue()); } diff --git a/src/Mod/TechDraw/App/DrawTileWeld.cpp b/src/Mod/TechDraw/App/DrawTileWeld.cpp index 2f0b8d3910..f060344f80 100644 --- a/src/Mod/TechDraw/App/DrawTileWeld.cpp +++ b/src/Mod/TechDraw/App/DrawTileWeld.cpp @@ -78,7 +78,7 @@ void DrawTileWeld::onChanged(const App::Property* prop) void DrawTileWeld::replaceFileIncluded(std::string newSymbolFile) { -// Base::Console().Message("DTW::replaceFileIncluded(%s)\n", newSymbolFile.c_str()); +// Base::Console().message("DTW::replaceFileIncluded(%s)\n", newSymbolFile.c_str()); if (newSymbolFile.empty()) { return; } diff --git a/src/Mod/TechDraw/App/DrawUtil.cpp b/src/Mod/TechDraw/App/DrawUtil.cpp index f3ca7ea551..efeaaef384 100644 --- a/src/Mod/TechDraw/App/DrawUtil.cpp +++ b/src/Mod/TechDraw/App/DrawUtil.cpp @@ -78,7 +78,7 @@ using namespace TechDraw; /*static*/ int DrawUtil::getIndexFromName(const std::string& geomName) { - // Base::Console().Message("DU::getIndexFromName(%s)\n", geomName.c_str()); + // Base::Console().message("DU::getIndexFromName(%s)\n", geomName.c_str()); boost::regex re("\\d+$");// one of more digits at end of string boost::match_results what; boost::match_flag_type flags = boost::match_default; @@ -189,7 +189,7 @@ double DrawUtil::simpleMinDist(TopoDS_Shape s1, TopoDS_Shape s2) { BRepExtrema_DistShapeShape extss(s1, s2); if (!extss.IsDone()) { - Base::Console().Message("DU::simpleMinDist - BRepExtrema_DistShapeShape failed"); + Base::Console().message("DU::simpleMinDist - BRepExtrema_DistShapeShape failed"); return -1; } int count = extss.NbSolution(); @@ -245,7 +245,7 @@ double DrawUtil::angleWithX(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) param = adapt.LastParameter(); } else { //TARFU - Base::Console().Message("Error: DU::angleWithX - v is neither first nor last \n"); + Base::Console().message("Error: DU::angleWithX - v is neither first nor last \n"); } gp_Pnt paramPoint; gp_Vec derivative; @@ -284,7 +284,7 @@ double DrawUtil::incidenceAngleAtVertex(TopoDS_Edge e, TopoDS_Vertex v, double t offsetPoint = Base::Vector3d(gOffsetPoint.X(), gOffsetPoint.Y(), gOffsetPoint.Z()); } else { //TARFU - // Base::Console().Message("DU::incidenceAngle - v is neither first nor last \n"); + // Base::Console().message("DU::incidenceAngle - v is neither first nor last \n"); } incidenceVec = anglePoint - offsetPoint; incidenceAngle = atan2(incidenceVec.y, incidenceVec.x); @@ -434,7 +434,7 @@ bool DrawUtil::apparentIntersection(TopoDS_Edge& edge0, TopoDS_Edge& edge1, gp_P gp_Vec D(gStart1.XYZ()); gp_Vec e(gEnd0.XYZ() - gStart0.XYZ());//direction of line0 gp_Vec f(gEnd1.XYZ() - gStart1.XYZ());//direction of line1 - Base::Console().Message( + Base::Console().message( "DU::apparentInter - e: %s f: %s\n", formatVector(e).c_str(), formatVector(f).c_str()); //check for cases the algorithm doesn't handle well @@ -450,7 +450,7 @@ bool DrawUtil::apparentIntersection(TopoDS_Edge& edge0, TopoDS_Edge& edge1, gp_P } gp_Vec g(D - C);//between a point on each line - Base::Console().Message("DU::apparentInter - C: %s D: %s g: %s\n", + Base::Console().message("DU::apparentInter - C: %s D: %s g: %s\n", formatVector(C).c_str(), formatVector(D).c_str(), formatVector(g).c_str()); @@ -459,7 +459,7 @@ bool DrawUtil::apparentIntersection(TopoDS_Edge& edge0, TopoDS_Edge& edge1, gp_P double h = fxg.Magnitude(); gp_Vec fxe = f.Crossed(e); double k = fxe.Magnitude(); - Base::Console().Message("DU::apparentInter - h: %.3f k: %.3f\n", h, k); + Base::Console().message("DU::apparentInter - h: %.3f k: %.3f\n", h, k); if (fpCompare(k, 0.0)) { //no intersection return false; @@ -492,7 +492,7 @@ bool DrawUtil::intersect2Lines3d(Base::Vector3d point0, Base::Vector3d dir0, Bas dir1n.Normalize(); if (fabs(dir0n.Dot(dir1n)) == 1.0) { //parallel lines, no intersection - Base::Console().Message("DU::intersect2 - parallel lines, no intersection\n"); + Base::Console().message("DU::intersect2 - parallel lines, no intersection\n"); return false; } @@ -857,7 +857,7 @@ double DrawUtil::getWidthInDirection(gp_Dir direction, TopoDS_Shape& shape) if (shapeBox.IsVoid()) { //this really shouldn't happen here as null shapes should have been caught //long before this - Base::Console().Error("DU::getWidthInDirection - shapeBox is void\n"); + Base::Console().error("DU::getWidthInDirection - shapeBox is void\n"); return 0.0; } shapeBox.Get(xMin, yMin, zMin, xMax, yMax, zMax); @@ -894,7 +894,7 @@ gp_Vec DrawUtil::maskDirection(gp_Vec inVec, gp_Dir directionToMask) return {inVec.X(), inVec.Y(), 0.0}; } - Base::Console().Message("DU:maskDirection - directionToMask is not cardinal\n"); + Base::Console().message("DU:maskDirection - directionToMask is not cardinal\n"); return {}; } @@ -989,7 +989,7 @@ Base::Vector3d DrawUtil::Intersect2d(Base::Vector3d p1, Base::Vector3d d1, Base: double det = A1 * B2 - A2 * B1; if (fpCompare(det, 0.0, Precision::Confusion())) { - Base::Console().Message("Lines are parallel\n"); + Base::Console().message("Lines are parallel\n"); return Base::Vector3d(0.0, 0.0, 0.0); } @@ -1013,7 +1013,7 @@ Base::Vector2d DrawUtil::Intersect2d(Base::Vector2d p1, Base::Vector2d d1, Base: double det = A1 * B2 - A2 * B1; if (fpCompare(det, 0.0, Precision::Confusion())) { - Base::Console().Message("Lines are parallel\n"); + Base::Console().message("Lines are parallel\n"); return Base::Vector2d(0.0, 0.0); } @@ -1055,7 +1055,7 @@ QPointF DrawUtil::invertY(QPointF v) //! Note: the centering operation is not considered here Base::Vector3d DrawUtil::toAppSpace(const DrawViewPart& dvp, const Base::Vector3d &qtPoint) { -// Base::Console().Message("DGU::toPaperSpace(%s)\n", formatVector(qtPoint).c_str()); +// Base::Console().message("DGU::toPaperSpace(%s)\n", formatVector(qtPoint).c_str()); // From Y+ is down to Y+ is up Base::Vector3d appPoint = invertY(qtPoint); @@ -1081,7 +1081,7 @@ Base::Vector3d DrawUtil::toAppSpace(const DrawViewPart& dvp, const QPointF& qtP //obs? was used in CSV prototype of Cosmetics std::vector DrawUtil::split(std::string csvLine) { - // Base::Console().Message("DU::split - csvLine: %s\n", csvLine.c_str()); + // Base::Console().message("DU::split - csvLine: %s\n", csvLine.c_str()); std::vector result; std::stringstream lineStream(csvLine); std::string cell; @@ -1095,7 +1095,7 @@ std::vector DrawUtil::split(std::string csvLine) //obs? was used in CSV prototype of Cosmetics std::vector DrawUtil::tokenize(std::string csvLine, std::string delimiter) { - // Base::Console().Message("DU::tokenize - csvLine: %s delimit: %s\n", csvLine.c_str(), delimiter.c_str()); + // Base::Console().message("DU::tokenize - csvLine: %s delimit: %s\n", csvLine.c_str(), delimiter.c_str()); std::string s(csvLine); size_t pos = 0; std::vector tokens; @@ -1111,7 +1111,7 @@ std::vector DrawUtil::tokenize(std::string csvLine, std::string del Base::Color DrawUtil::pyTupleToColor(PyObject* pColor) { - // Base::Console().Message("DU::pyTupleToColor()\n"); + // Base::Console().message("DU::pyTupleToColor()\n"); double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; if (!PyTuple_Check(pColor)) { return Base::Color(red, green, blue, alpha); @@ -1135,7 +1135,7 @@ Base::Color DrawUtil::pyTupleToColor(PyObject* pColor) PyObject* DrawUtil::colorToPyTuple(Base::Color color) { - // Base::Console().Message("DU::pyTupleToColor()\n"); + // Base::Console().message("DU::pyTupleToColor()\n"); PyObject* pTuple = PyTuple_New(4); PyObject* pRed = PyFloat_FromDouble(color.r); PyObject* pGreen = PyFloat_FromDouble(color.g); @@ -1197,7 +1197,7 @@ bool DrawUtil::isCrazy(TopoDS_Edge e) } } - // Base::Console().Message("DU::isCrazy - returns: %d ratio: %.3f\n", false, ratio); + // Base::Console().message("DU::isCrazy - returns: %d ratio: %.3f\n", false, ratio); return false; } @@ -1831,7 +1831,7 @@ void DrawUtil::findCircularArcRectangleIntersections(const Base::Vector2d& circl //create empty outSpec file if inSpec void DrawUtil::copyFile(std::string inSpec, std::string outSpec) { - // Base::Console().Message("DU::copyFile(%s, %s)\n", inSpec.c_str(), outSpec.c_str()); + // Base::Console().message("DU::copyFile(%s, %s)\n", inSpec.c_str(), outSpec.c_str()); if (inSpec.empty()) { // create an empty file Base::FileInfo fi(outSpec); @@ -1844,7 +1844,7 @@ void DrawUtil::copyFile(std::string inSpec, std::string outSpec) } bool rc = fi.copyTo(outSpec.c_str()); if (!rc) { - Base::Console().Message( + Base::Console().message( "DU::copyFile - failed - in: %s out:%s\n", inSpec.c_str(), outSpec.c_str()); } } @@ -1883,12 +1883,12 @@ bool DrawUtil::isGuiUp() // various debugging routines. void DrawUtil::dumpVertexes(const char* text, const TopoDS_Shape& s) { - Base::Console().Message("DUMP - %s\n", text); + Base::Console().message("DUMP - %s\n", text); TopExp_Explorer expl(s, TopAbs_VERTEX); for (int i = 1; expl.More(); expl.Next(), i++) { const TopoDS_Vertex& v = TopoDS::Vertex(expl.Current()); gp_Pnt pnt = BRep_Tool::Pnt(v); - Base::Console().Message("v%d: (%.3f, %.3f, %.3f)\n", i, pnt.X(), pnt.Y(), pnt.Z()); + Base::Console().message("v%d: (%.3f, %.3f, %.3f)\n", i, pnt.X(), pnt.Y(), pnt.Z()); } } @@ -1897,7 +1897,7 @@ void DrawUtil::countFaces(const char* text, const TopoDS_Shape& s) TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(s, TopAbs_FACE, mapOfFaces); int num = mapOfFaces.Extent(); - Base::Console().Message("COUNT - %s has %d Faces\n", text, num); + Base::Console().message("COUNT - %s has %d Faces\n", text, num); } //count # of unique Wires in shape. @@ -1906,7 +1906,7 @@ void DrawUtil::countWires(const char* text, const TopoDS_Shape& s) TopTools_IndexedMapOfShape mapOfWires; TopExp::MapShapes(s, TopAbs_WIRE, mapOfWires); int num = mapOfWires.Extent(); - Base::Console().Message("COUNT - %s has %d wires\n", text, num); + Base::Console().message("COUNT - %s has %d wires\n", text, num); } void DrawUtil::countEdges(const char* text, const TopoDS_Shape& s) @@ -1914,12 +1914,12 @@ void DrawUtil::countEdges(const char* text, const TopoDS_Shape& s) TopTools_IndexedMapOfShape mapOfEdges; TopExp::MapShapes(s, TopAbs_EDGE, mapOfEdges); int num = mapOfEdges.Extent(); - Base::Console().Message("COUNT - %s has %d edges\n", text, num); + Base::Console().message("COUNT - %s has %d edges\n", text, num); } void DrawUtil::dumpEdges(const char* text, const TopoDS_Shape& s) { - Base::Console().Message("DUMP - %s\n", text); + Base::Console().message("DUMP - %s\n", text); TopExp_Explorer expl(s, TopAbs_EDGE); for (int i = 1; expl.More(); expl.Next(), i++) { const TopoDS_Edge& e = TopoDS::Edge(expl.Current()); @@ -1929,9 +1929,9 @@ void DrawUtil::dumpEdges(const char* text, const TopoDS_Shape& s) void DrawUtil::dump1Vertex(const char* text, const TopoDS_Vertex& v) { - // Base::Console().Message("DUMP - dump1Vertex - %s\n",text); + // Base::Console().message("DUMP - dump1Vertex - %s\n",text); gp_Pnt pnt = BRep_Tool::Pnt(v); - Base::Console().Message("%s: (%.3f, %.3f, %.3f)\n", text, pnt.X(), pnt.Y(), pnt.Z()); + Base::Console().message("%s: (%.3f, %.3f, %.3f)\n", text, pnt.X(), pnt.Y(), pnt.Z()); } void DrawUtil::dumpEdge(const char* label, int i, TopoDS_Edge e) @@ -1943,9 +1943,9 @@ void DrawUtil::dumpEdge(const char* label, int i, TopoDS_Edge e) const gp_Pnt& vStart = propStart.Value(); BRepLProp_CLProps propEnd(adapt, end, 0, Precision::Confusion()); const gp_Pnt& vEnd = propEnd.Value(); - //Base::Console().Message("%s edge:%d start:(%.3f, %.3f, %.3f)/%0.3f end:(%.2f, %.3f, %.3f)/%.3f\n", label, i, + //Base::Console().message("%s edge:%d start:(%.3f, %.3f, %.3f)/%0.3f end:(%.2f, %.3f, %.3f)/%.3f\n", label, i, // vStart.X(), vStart.Y(), vStart.Z(), start, vEnd.X(), vEnd.Y(), vEnd.Z(), end); - Base::Console().Message( + Base::Console().message( "%s edge:%d start:(%.3f, %.3f, %.3f) end:(%.2f, %.3f, %.3f) Orient: %d\n", label, i, @@ -1957,7 +1957,7 @@ void DrawUtil::dumpEdge(const char* label, int i, TopoDS_Edge e) vEnd.Z(), static_cast(e.Orientation())); double edgeLength = GCPnts_AbscissaPoint::Length(adapt, Precision::Confusion()); - Base::Console().Message(">>>>>>> length: %.3f distance: %.3f ratio: %.3f type: %d\n", + Base::Console().message(">>>>>>> length: %.3f distance: %.3f ratio: %.3f type: %d\n", edgeLength, vStart.Distance(vEnd), edgeLength / vStart.Distance(vEnd), @@ -1991,7 +1991,7 @@ void DrawUtil::dumpCS(const char* text, const gp_Ax2& CS) gp_Dir baseX = CS.XDirection(); gp_Dir baseY = CS.YDirection(); gp_Pnt baseOrg = CS.Location(); - Base::Console().Message("DU::dumpCS - %s Loc: %s Axis: %s X: %s Y: %s\n", + Base::Console().message("DU::dumpCS - %s Loc: %s Axis: %s X: %s Y: %s\n", text, DrawUtil::formatVector(baseOrg).c_str(), DrawUtil::formatVector(baseAxis).c_str(), @@ -2005,7 +2005,7 @@ void DrawUtil::dumpCS3(const char* text, const gp_Ax3& CS) gp_Dir baseX = CS.XDirection(); gp_Dir baseY = CS.YDirection(); gp_Pnt baseOrg = CS.Location(); - Base::Console().Message("DU::dumpCS3 - %s Loc: %s Axis: %s X: %s Y: %s\n", + Base::Console().message("DU::dumpCS3 - %s Loc: %s Axis: %s X: %s Y: %s\n", text, DrawUtil::formatVector(baseOrg).c_str(), DrawUtil::formatVector(baseAxis).c_str(), diff --git a/src/Mod/TechDraw/App/DrawView.cpp b/src/Mod/TechDraw/App/DrawView.cpp index 91e16505ab..4b7f1e7a71 100644 --- a/src/Mod/TechDraw/App/DrawView.cpp +++ b/src/Mod/TechDraw/App/DrawView.cpp @@ -115,7 +115,7 @@ DrawView::~DrawView() App::DocumentObjectExecReturn *DrawView::execute() { -// Base::Console().Message("DV::execute() - %s touched: %d\n", getNameInDocument(), isTouched()); +// Base::Console().message("DV::execute() - %s touched: %d\n", getNameInDocument(), isTouched()); if (!findParentPage()) { return App::DocumentObject::execute(); } @@ -439,6 +439,26 @@ DrawView *DrawView::claimParent() const return getCollection(); } +//! return *unique* list of DrawView derived items which consider this DVP to be their 'owner' +//! if a dimension has two references to this dvp, it will appear twice in the inlist, so we need to +//! pick out duplicates. +std::vector DrawView::getUniqueChildren() const +{ + std::vector result; + auto children = getInList(); + std::sort(children.begin(), children.end(), std::less<>()); + auto newEnd = std::unique(children.begin(), children.end()); + children.erase(newEnd, children.end()); + for (auto& child : children) { + auto* childDV = freecad_cast(child); + if (childDV && childDV->claimParent() == this) { + result.push_back(childDV); + } + } + return result; +} + + DrawViewClip* DrawView::getClipGroup() { for (auto* obj : getInList()) { @@ -470,7 +490,7 @@ double DrawView::autoScale() const //compare 1:1 rect of view to pagesize(pw, h) double DrawView::autoScale(double pw, double ph) const { -// Base::Console().Message("DV::autoScale(Page: %.3f, %.3f) - %s\n", pw, ph, getNameInDocument()); +// Base::Console().message("DV::autoScale(Page: %.3f, %.3f) - %s\n", pw, ph, getNameInDocument()); QRectF viewBox = getRect(); //getRect is scaled (ie current actual size) if (!viewBox.isValid()) { return 1.0; @@ -487,7 +507,7 @@ double DrawView::autoScale(double pw, double ph) const bool DrawView::checkFit() const { -// Base::Console().Message("DV::checkFit() - %s\n", getNameInDocument()); +// Base::Console().message("DV::checkFit() - %s\n", getNameInDocument()); auto page = findParentPage(); return checkFit(page); } @@ -495,7 +515,7 @@ bool DrawView::checkFit() const //!check if View is too big for page bool DrawView::checkFit(TechDraw::DrawPage* p) const { -// Base::Console().Message("DV::checkFit(page) - %s\n", getNameInDocument()); +// Base::Console().message("DV::checkFit(page) - %s\n", getNameInDocument()); bool result = true; double width = 0.0; @@ -516,7 +536,7 @@ bool DrawView::checkFit(TechDraw::DrawPage* p) const void DrawView::setPosition(double x, double y, bool force) { -// Base::Console().Message("DV::setPosition(%.3f, %.3f) - \n", x,y, getNameInDocument()); +// Base::Console().message("DV::setPosition(%.3f, %.3f) - \n", x,y, getNameInDocument()); if ( (!isLocked()) || (force) ) { double currX = X.getValue(); @@ -633,7 +653,7 @@ void DrawView::handleChangedPropertyType(Base::XMLReader &reader, const char * T bool DrawView::keepUpdated() { -// Base::Console().Message("DV::keepUpdated() - %s\n", getNameInDocument()); +// Base::Console().message("DV::keepUpdated() - %s\n", getNameInDocument()); if (overrideKeepUpdated()) { return true; } @@ -688,7 +708,7 @@ double DrawView::prefScale() void DrawView::requestPaint() { -// Base::Console().Message("DV::requestPaint() - %s\n", getNameInDocument()); +// Base::Console().message("DV::requestPaint() - %s\n", getNameInDocument()); signalGuiPaint(this); } @@ -703,11 +723,11 @@ void DrawView::showProgressMessage(std::string featureName, std::string text) //! the unique name within the document (ex ActiveView001), and use it to update the Label property. void DrawView::translateLabel(std::string context, std::string baseName, std::string uniqueName) { -// Base::Console().Message("DV::translateLabel - context: %s baseName: %s uniqueName: %s\n", +// Base::Console().message("DV::translateLabel - context: %s baseName: %s uniqueName: %s\n", // context.c_str(), baseName.c_str(), uniqueName.c_str()); Label.setValue(DU::translateArbitrary(context, baseName, uniqueName)); -// Base::Console().Message("DV::translateLabel - new label: %s\n", Label.getValue()); +// Base::Console().message("DV::translateLabel - new label: %s\n", Label.getValue()); } PyObject *DrawView::getPyObject(void) diff --git a/src/Mod/TechDraw/App/DrawView.h b/src/Mod/TechDraw/App/DrawView.h index 7c261ff819..9adcc33069 100644 --- a/src/Mod/TechDraw/App/DrawView.h +++ b/src/Mod/TechDraw/App/DrawView.h @@ -87,6 +87,7 @@ public: virtual DrawPage* findParentPage() const; virtual std::vector findAllParentPages() const; virtual DrawView *claimParent() const; + std::vector getUniqueChildren() const; virtual int countParentPages() const; virtual QRectF getRect() const; //must be overridden by derived class diff --git a/src/Mod/TechDraw/App/DrawViewArch.cpp b/src/Mod/TechDraw/App/DrawViewArch.cpp index e5366bddfb..b62ed19756 100644 --- a/src/Mod/TechDraw/App/DrawViewArch.cpp +++ b/src/Mod/TechDraw/App/DrawViewArch.cpp @@ -101,7 +101,7 @@ App::DocumentObjectExecReturn *DrawViewArch::execute() //if (sourceObj is not ArchSection) return App::Property* proxy = sourceObj->getPropertyByName("Proxy"); if (!proxy) { - Base::Console().Error("DVA::execute - %s is not an ArchSection\n", sourceObj->Label.getValue()); + Base::Console().error("DVA::execute - %s is not an ArchSection\n", sourceObj->Label.getValue()); //this is definitely not an ArchSection return DrawView::execute(); } diff --git a/src/Mod/TechDraw/App/DrawViewDetail.cpp b/src/Mod/TechDraw/App/DrawViewDetail.cpp index 9d69e0d113..4e7f322d0e 100644 --- a/src/Mod/TechDraw/App/DrawViewDetail.cpp +++ b/src/Mod/TechDraw/App/DrawViewDetail.cpp @@ -104,7 +104,7 @@ DrawViewDetail::~DrawViewDetail() { //don't delete this object while it still has dependent tasks running if (m_detailFuture.isRunning()) { - Base::Console().Message("%s is waiting for detail cut to finish\n", Label.getValue()); + Base::Console().message("%s is waiting for detail cut to finish\n", Label.getValue()); m_detailFuture.waitForFinished(); } } @@ -268,13 +268,13 @@ void DrawViewDetail::makeDetailShape(const TopoDS_Shape& shape3d, DrawViewPart* BRepBuilderAPI_MakeFace mkFace(gpln, -radius, radius, -radius, radius); extrusionFace = mkFace.Face(); if (extrusionFace.IsNull()) { - Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool base face\n", + Base::Console().warning("DVD::makeDetailShape - %s - failed to create tool base face\n", getNameInDocument()); return; } tool = BRepPrimAPI_MakePrism(extrusionFace, extrudeDir, false, true).Shape(); if (tool.IsNull()) { - Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool (prism)\n", + Base::Console().warning("DVD::makeDetailShape - %s - failed to create tool (prism)\n", getNameInDocument()); return; } @@ -285,7 +285,7 @@ void DrawViewDetail::makeDetailShape(const TopoDS_Shape& shape3d, DrawViewPart* BRepPrimAPI_MakeCylinder mkTool(cs, radius, extrudeLength); tool = mkTool.Shape(); if (tool.IsNull()) { - Base::Console().Warning("DVD::detailExec - %s - failed to create tool (cylinder)\n", + Base::Console().warning("DVD::detailExec - %s - failed to create tool (cylinder)\n", getNameInDocument()); return; } diff --git a/src/Mod/TechDraw/App/DrawViewDimExtent.cpp b/src/Mod/TechDraw/App/DrawViewDimExtent.cpp index 46e04d3dd8..d5c489e149 100644 --- a/src/Mod/TechDraw/App/DrawViewDimExtent.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimExtent.cpp @@ -64,7 +64,7 @@ DrawViewDimExtent::DrawViewDimExtent(void) App::DocumentObjectExecReturn *DrawViewDimExtent::execute(void) { -// Base::Console().Message("DVDE::execute() - %s\n", getNameInDocument()); +// Base::Console().message("DVDE::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } @@ -94,7 +94,7 @@ App::DocumentObjectExecReturn *DrawViewDimExtent::execute(void) //! validate 2D references - only checks if the target exists bool DrawViewDimExtent::checkReferences2D() const { -// Base::Console().Message("DVDE::checkReferences2d() - %s\n", getNameInDocument()); +// Base::Console().message("DVDE::checkReferences2d() - %s\n", getNameInDocument()); const std::vector &objects = References2D.getValues(); if (objects.empty()) { return false; @@ -111,7 +111,7 @@ bool DrawViewDimExtent::checkReferences2D() const } pointPair DrawViewDimExtent::getPointsExtent(ReferenceVector references) { -// Base::Console().Message("DVD::getPointsExtent() - %s\n", getNameInDocument()); +// Base::Console().message("DVD::getPointsExtent() - %s\n", getNameInDocument()); App::DocumentObject* refObject = references.front().getObject(); int direction = DirExtent.getValue(); if (refObject->isDerivedFrom()) { diff --git a/src/Mod/TechDraw/App/DrawViewDimension.cpp b/src/Mod/TechDraw/App/DrawViewDimension.cpp index 81b3d28ef9..02f634d17d 100644 --- a/src/Mod/TechDraw/App/DrawViewDimension.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimension.cpp @@ -481,7 +481,7 @@ App::DocumentObjectExecReturn* DrawViewDimension::execute() } if (!m_referencesCorrect) { // this test needs Phase 2 of auto correct to be useful - Base::Console().Log("The references for %s have changed and autocorrect could not match the geometry\n", Label.getValue()); + Base::Console().log("The references for %s have changed and autocorrect could not match the geometry\n", Label.getValue()); } resetLinear(); @@ -549,26 +549,26 @@ bool DrawViewDimension::okToProceed() // TODO: translate these messages and figure out how to present them to // the user since we can't pop up a message box here. // this case is probably temporary during restore - // Base::Console().Message("DVD::okToProceed - no view for dimension\n"); + // Base::Console().message("DVD::okToProceed - no view for dimension\n"); return false; } if (!(has2DReferences() || has3DReferences())) { // no references, can't do anything - // Base::Console().Message("DVD::okToProceed - Dimension object has no valid references\n"); + // Base::Console().message("DVD::okToProceed - Dimension object has no valid references\n"); return false; } if (!getViewPart()->hasGeometry()) { // can't do anything until Source has geometry - // Base::Console().Message("DVD::okToProceed - Dimension object has no geometry\n"); + // Base::Console().message("DVD::okToProceed - Dimension object has no geometry\n"); return false; } // is this check still relevant or is it replaced by the autocorrect and // validate methods? if (References3D.getValues().empty() && !checkReferences2D()) { - // Base::Console().Warning("%s has invalid 2D References\n", getNameInDocument()); + // Base::Console().warning("%s has invalid 2D References\n", getNameInDocument()); return false; } return validateReferenceForm(); @@ -667,7 +667,7 @@ double DrawViewDimension::getDimValue() if (MeasureType.isValue("True")) { // True Values if (!measurement->has3DReferences()) { - Base::Console().Warning("%s - True dimension has no 3D References\n", + Base::Console().warning("%s - True dimension has no 3D References\n", getNameInDocument()); return result; } @@ -676,7 +676,7 @@ double DrawViewDimension::getDimValue() else { // Projected Values if (!checkReferences2D()) { - Base::Console().Warning("DVD::getDimValue - %s - 2D references are corrupt (5)\n", + Base::Console().warning("DVD::getDimValue - %s - 2D references are corrupt (5)\n", getNameInDocument()); return result; } @@ -1094,7 +1094,7 @@ arcPoints DrawViewDimension::arcPointsFromBaseGeom(TechDraw::BaseGeomPtr base) else { // fubar - can't have non-circular spline as target of Diameter dimension, but this is // already checked, so something has gone badly wrong. - Base::Console().Error("%s: can not make a Circle from this B-spline edge\n", + Base::Console().error("%s: can not make a Circle from this B-spline edge\n", getNameInDocument()); throw Base::RuntimeError("Bad B-spline geometry for arc dimension"); } @@ -1535,7 +1535,7 @@ RefType DrawViewDimension::getRefType() const if (subNames.empty()) { // something went wrong, there were no subNames. - Base::Console().Message("DVD::getRefType - %s - there are no subNames.\n", + Base::Console().message("DVD::getRefType - %s - there are no subNames.\n", getNameInDocument()); return RefType::invalidRef; } @@ -1927,14 +1927,14 @@ void DrawViewDimension::clear3DMeasurements() void DrawViewDimension::dumpRefs2D(const char* text) const { - Base::Console().Message("DUMP - %s\n", text); + Base::Console().message("DUMP - %s\n", text); const std::vector& objects = References2D.getValues(); const std::vector& subElements = References2D.getSubValues(); auto objIt = objects.begin(); auto subIt = subElements.begin(); int i = 0; for (; objIt != objects.end(); objIt++, subIt++, i++) { - Base::Console().Message("DUMP - ref: %d object: %s subElement: %s\n", + Base::Console().message("DUMP - ref: %d object: %s subElement: %s\n", i, (*objIt)->getNameInDocument(), (*subIt).c_str()); @@ -2142,7 +2142,7 @@ Base::BoundBox3d DrawViewDimension::getSavedBox() if (bbxCorners.empty()) { // need to advise caller if BoxCorners not filled in yet. zero length // diagonal? - Base::Console().Message("DVD::getSavedBox - no corners!\n"); + Base::Console().message("DVD::getSavedBox - no corners!\n"); return Base::BoundBox3d(); } return Base::BoundBox3d(bbxCorners.front().x, diff --git a/src/Mod/TechDraw/App/DrawViewDraft.cpp b/src/Mod/TechDraw/App/DrawViewDraft.cpp index b73d64dbb9..7b98e2f94c 100644 --- a/src/Mod/TechDraw/App/DrawViewDraft.cpp +++ b/src/Mod/TechDraw/App/DrawViewDraft.cpp @@ -79,7 +79,7 @@ short DrawViewDraft::mustExecute() const App::DocumentObjectExecReturn *DrawViewDraft::execute() { -// Base::Console().Message("DVDr::execute() \n"); +// Base::Console().message("DVDr::execute() \n"); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } diff --git a/src/Mod/TechDraw/App/DrawViewImage.cpp b/src/Mod/TechDraw/App/DrawViewImage.cpp index 8a3da9d447..4276ce538c 100644 --- a/src/Mod/TechDraw/App/DrawViewImage.cpp +++ b/src/Mod/TechDraw/App/DrawViewImage.cpp @@ -88,7 +88,7 @@ QRectF DrawViewImage::getRect() const { return {0.0, 0.0, Width.getValue(), Heig void DrawViewImage::replaceImageIncluded(std::string newImageFile) { - // Base::Console().Message("DVI::replaceImageIncluded(%s)\n", newImageFile.c_str()); + // Base::Console().message("DVI::replaceImageIncluded(%s)\n", newImageFile.c_str()); if (newImageFile.empty()) { return; } @@ -104,7 +104,7 @@ void DrawViewImage::replaceImageIncluded(std::string newImageFile) void DrawViewImage::setupObject() { - // Base::Console().Message("DVI::setupObject()\n"); + // Base::Console().message("DVI::setupObject()\n"); replaceImageIncluded(ImageFile.getValue()); } diff --git a/src/Mod/TechDraw/App/DrawViewMulti.cpp b/src/Mod/TechDraw/App/DrawViewMulti.cpp index 5f80098291..3bebdbd4bc 100644 --- a/src/Mod/TechDraw/App/DrawViewMulti.cpp +++ b/src/Mod/TechDraw/App/DrawViewMulti.cpp @@ -76,7 +76,7 @@ short DrawViewMulti::mustExecute() const void DrawViewMulti::onChanged(const App::Property* prop) { if (!isRestoring()) { - //Base::Console().Message("TRACE - DVM::onChanged(%s) - %s\n", prop->getName(), Label.getValue()); + //Base::Console().message("TRACE - DVM::onChanged(%s) - %s\n", prop->getName(), Label.getValue()); if (prop == &Sources) { const std::vector& links = Sources.getValues(); if (!links.empty()) { @@ -96,7 +96,7 @@ App::DocumentObjectExecReturn *DrawViewMulti::execute() const std::vector& links = Sources.getValues(); if (links.empty()) { - Base::Console().Log("INFO - DVM::execute - No Sources - creation?\n"); + Base::Console().log("INFO - DVM::execute - No Sources - creation?\n"); return DrawView::execute(); } diff --git a/src/Mod/TechDraw/App/DrawViewPart.cpp b/src/Mod/TechDraw/App/DrawViewPart.cpp index 00175978c3..abc3157730 100644 --- a/src/Mod/TechDraw/App/DrawViewPart.cpp +++ b/src/Mod/TechDraw/App/DrawViewPart.cpp @@ -158,11 +158,11 @@ DrawViewPart::~DrawViewPart() { //don't delete this object while it still has dependent threads running if (m_hlrFuture.isRunning()) { - Base::Console().Message("%s is waiting for HLR to finish\n", Label.getValue()); + Base::Console().message("%s is waiting for HLR to finish\n", Label.getValue()); m_hlrFuture.waitForFinished(); } if (m_faceFuture.isRunning()) { - Base::Console().Message("%s is waiting for face finding to finish\n", Label.getValue()); + Base::Console().message("%s is waiting for face finding to finish\n", Label.getValue()); m_faceFuture.waitForFinished(); } removeAllReferencesFromGeom(); @@ -172,7 +172,7 @@ DrawViewPart::~DrawViewPart() //! XSource property lists TopoDS_Shape DrawViewPart::getSourceShape(bool fuse, bool allow2d) const { -// Base::Console().Message("DVP::getSourceShape()\n"); +// Base::Console().message("DVP::getSourceShape()\n"); const std::vector& links = getAllSources(); if (links.empty()) { return {}; @@ -194,7 +194,7 @@ TopoDS_Shape DrawViewPart::getShapeForDetail() const //! combine the regular links and xlinks into a single list std::vector DrawViewPart::getAllSources() const { - // Base::Console().Message("DVP::getAllSources()\n"); + // Base::Console().message("DVP::getAllSources()\n"); std::vector links = Source.getValues(); std::vector xLinks = XSource.getValues(); @@ -209,7 +209,7 @@ std::vector DrawViewPart::getAllSources() const //! add them directly to the geometry without going through HLR void DrawViewPart::addPoints() { -// Base::Console().Message("DVP::addPoints()\n"); +// Base::Console().message("DVP::addPoints()\n"); // get all the 2d shapes in the sources, then pick through them for vertices. std::vector shapesAll = ShapeExtractor::getShapes2d(getAllSources()); for (auto& shape : shapesAll) { @@ -227,7 +227,7 @@ void DrawViewPart::addPoints() App::DocumentObjectExecReturn* DrawViewPart::execute() { - // Base::Console().Message("DVP::execute() - %s\n", getNameInDocument()); + // Base::Console().message("DVP::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { return DrawView::execute(); } @@ -238,7 +238,7 @@ App::DocumentObjectExecReturn* DrawViewPart::execute() TopoDS_Shape shape = getSourceShape(); if (shape.IsNull()) { - Base::Console().Message("DVP::execute - %s - Source shape is Null.\n", getNameInDocument()); + Base::Console().message("DVP::execute - %s - Source shape is Null.\n", getNameInDocument()); return DrawView::execute(); } @@ -278,12 +278,12 @@ void DrawViewPart::onChanged(const App::Property* prop) // Otherwise bad things will happen because there'll be a normalization for direction calculations later. Base::Vector3d dir = Direction.getValue(); if (DrawUtil::fpCompare(dir.Length(), 0.0)) { - Base::Console().Warning("%s Direction is null. Using (0, -1, 0).\n", Label.getValue()); + Base::Console().warning("%s Direction is null. Using (0, -1, 0).\n", Label.getValue()); Direction.setValue(Base::Vector3d(0.0, -1.0, 0.0)); } Base::Vector3d xdir = XDirection.getValue(); if (DrawUtil::fpCompare(xdir.Length(), 0.0)) { - Base::Console().Warning("%s XDirection is null. Using (1, 0, 0).\n", Label.getValue()); + Base::Console().warning("%s XDirection is null. Using (1, 0, 0).\n", Label.getValue()); XDirection.setValue(Base::Vector3d(1.0, 0.0, 0.0)); } @@ -399,7 +399,7 @@ void DrawViewPart::onHlrFinished() } if (!hasGeometry()) { - Base::Console().Error("TechDraw did not retrieve any geometry for %s/%s\n", + Base::Console().error("TechDraw did not retrieve any geometry for %s/%s\n", getNameInDocument(), Label.getValue()); } @@ -437,7 +437,7 @@ void DrawViewPart::onHlrFinished() } catch (Standard_Failure& e) { waitingForFaces(false); - Base::Console().Error("DVP::partExec - %s - extractFaces failed - %s **\n", + Base::Console().error("DVP::partExec - %s - extractFaces failed - %s **\n", getNameInDocument(), e.GetMessageString()); throw Base::RuntimeError("DVP::onHlrFinished - error extracting faces"); } @@ -511,7 +511,7 @@ void DrawViewPart::extractFaces() geometryObject->getVisibleFaceEdges(SmoothVisible.getValue(), SeamVisible.getValue()); if (goEdges.empty()) { - // Base::Console().Message("DVP::extractFaces - %s - no face edges available!\n", getNameInDocument()); //debug + // Base::Console().message("DVP::extractFaces - %s - no face edges available!\n", getNameInDocument()); //debug return; } @@ -530,7 +530,7 @@ void DrawViewPart::findFacesNew(const std::vector &goEdges) if (cleanEdges.empty() && closedEdges.empty()) { //how does this happen? something wrong somewhere - // Base::Console().Message("DVP::findFacesNew - no clean or closed wires\n"); //debug + // Base::Console().message("DVP::findFacesNew - no clean or closed wires\n"); //debug return; } @@ -561,7 +561,7 @@ void DrawViewPart::findFacesNew(const std::vector &goEdges) } if (sortedWires.empty()) { - Base::Console().Warning( + Base::Console().warning( "DVP::findFacesNew - %s - Can't make faces from projected edges\n", getNameInDocument()); } @@ -684,7 +684,7 @@ void DrawViewPart::findFacesOld(const std::vector &goEdges) EdgeWalker eWalker; sortedWires = eWalker.execute(newEdges); if (sortedWires.empty()) { - Base::Console().Warning( + Base::Console().warning( "DVP::findFacesOld - %s -Can't make faces from projected edges\n", getNameInDocument()); return; @@ -707,7 +707,7 @@ void DrawViewPart::findFacesOld(const std::vector &goEdges) //continue processing after extractFaces thread completes void DrawViewPart::onFacesFinished() { - // Base::Console().Message("DVP::onFacesFinished() - %s\n", getNameInDocument()); + // Base::Console().message("DVP::onFacesFinished() - %s\n", getNameInDocument()); waitingForFaces(false); QObject::disconnect(connectFaceWatcher); showProgressMessage(getNameInDocument(), "has finished extracting faces"); @@ -794,7 +794,7 @@ const std::vector DrawViewPart::getVertexGeometry() const //! TechDraw vertex names run from 0 to n-1 TechDraw::VertexPtr DrawViewPart::getVertex(std::string vertexName) const { - // Base::Console().Message("DVP::getVertex(%s)\n", vertexName.c_str()); + // Base::Console().message("DVP::getVertex(%s)\n", vertexName.c_str()); auto vertexIndex = DrawUtil::getIndexFromName(vertexName); auto vertex = getProjVertexByIndex(vertexIndex); return vertex; @@ -949,7 +949,7 @@ double DrawViewPart::getBoxY() const QRectF DrawViewPart::getRect() const { - // Base::Console().Message("DVP::getRect() - %s\n", getNameInDocument()); + // Base::Console().message("DVP::getRect() - %s\n", getNameInDocument()); double x = getBoxX(); double y = getBoxY(); return QRectF(0.0, 0.0, x, y); @@ -987,7 +987,7 @@ TopoDS_Shape DrawViewPart::getEdgeCompound() const // used in calculating the length of a section line double DrawViewPart::getSizeAlongVector(Base::Vector3d alignmentVector) { - // Base::Console().Message("DVP::GetSizeAlongVector(%s)\n", DrawUtil::formatVector(alignmentVector).c_str()); + // Base::Console().message("DVP::GetSizeAlongVector(%s)\n", DrawUtil::formatVector(alignmentVector).c_str()); double alignmentAngle = atan2(alignmentVector.y, alignmentVector.x) * -1.0; gp_Ax2 OXYZ;//shape has already been projected and we will rotate around Z if (getEdgeCompound().IsNull()) { @@ -1006,7 +1006,7 @@ double DrawViewPart::getSizeAlongVector(Base::Vector3d alignmentVector) //used to project a pt (ex SectionOrigin) onto paper plane Base::Vector3d DrawViewPart::projectPoint(const Base::Vector3d& pt, bool invert) const { - // Base::Console().Message("DVP::projectPoint(%s, %d\n", + // Base::Console().message("DVP::projectPoint(%s, %d\n", // DrawUtil::formatVector(pt).c_str(), invert); Base::Vector3d stdOrg(0.0, 0.0, 0.0); gp_Ax2 viewAxis = getProjectionCS(stdOrg); @@ -1064,7 +1064,7 @@ bool DrawViewPart::hasGeometry() const //in the derived view. gp_Ax2 DrawViewPart::localVectorToCS(const Base::Vector3d localUnit) const { - // Base::Console().Message("DVP::localVectorToCS(%s)\n", DU::formatVector((localUnit)).c_str()); + // Base::Console().message("DVP::localVectorToCS(%s)\n", DU::formatVector((localUnit)).c_str()); double angle = atan2(localUnit.y, localUnit.x);//radians gp_Ax1 rotateAxisDir(gp_Pnt(0.0, 0.0, 0.0), getProjectionCS().Direction()); gp_Vec gOldX = getProjectionCS().XDirection(); @@ -1084,14 +1084,14 @@ gp_Ax2 DrawViewPart::localVectorToCS(const Base::Vector3d localUnit) const Base::Vector3d DrawViewPart::localVectorToDirection(const Base::Vector3d localUnit) const { - // Base::Console().Message("DVP::localVectorToDirection() - localUnit: %s\n", DrawUtil::formatVector(localUnit).c_str()); + // Base::Console().message("DVP::localVectorToDirection() - localUnit: %s\n", DrawUtil::formatVector(localUnit).c_str()); gp_Ax2 cs = localVectorToCS(localUnit); return Base::convertTo(cs.Direction()); } gp_Ax2 DrawViewPart::getProjectionCS(const Base::Vector3d pt) const { - // Base::Console().Message("DVP::getProjectionCS() - %s - %s\n", getNameInDocument(), Label.getValue()); + // Base::Console().message("DVP::getProjectionCS() - %s - %s\n", getNameInDocument(), Label.getValue()); Base::Vector3d direction = Direction.getValue(); gp_Dir gDir(direction.x, direction.y, direction.z); Base::Vector3d xDir = getXDirection(); @@ -1102,14 +1102,14 @@ gp_Ax2 DrawViewPart::getProjectionCS(const Base::Vector3d pt) const viewAxis = gp_Ax2(gOrg, gDir, gXDir); } catch (...) { - Base::Console().Warning("DVP - %s - failed to create projection CS\n", getNameInDocument()); + Base::Console().warning("DVP - %s - failed to create projection CS\n", getNameInDocument()); } return viewAxis; } gp_Ax2 DrawViewPart::getRotatedCS(const Base::Vector3d basePoint) const { - // Base::Console().Message("DVP::getRotatedCS() - %s - %s\n", getNameInDocument(), Label.getValue()); + // Base::Console().message("DVP::getRotatedCS() - %s - %s\n", getNameInDocument(), Label.getValue()); gp_Ax2 unrotated = getProjectionCS(basePoint); gp_Ax1 rotationAxis(Base::convertTo(basePoint), unrotated.Direction()); double angleRad = Base::toRadians(Rotation.getValue()); @@ -1122,7 +1122,7 @@ gp_Ax2 DrawViewPart::getViewAxis(const Base::Vector3d& pt, const Base::Vector3d& { (void)direction; (void)flip; - Base::Console().Message("DVP::getViewAxis - deprecated. Use getProjectionCS.\n"); + Base::Console().message("DVP::getViewAxis - deprecated. Use getProjectionCS.\n"); return getProjectionCS(pt); } @@ -1198,7 +1198,7 @@ bool DrawViewPart::newFaceFinder() //! hatches, geomhatches, dimensions, ... void DrawViewPart::unsetupObject() { -// Base::Console().Message("DVP::unsetupObject()\n"); +// Base::Console().message("DVP::unsetupObject()\n"); nowUnsetting = true; App::Document* doc = getDocument(); std::string docName = doc->getName(); @@ -1256,7 +1256,7 @@ void DrawViewPart::unsetupObject() bool DrawViewPart::checkXDirection() const { - // Base::Console().Message("DVP::checkXDirection()\n"); + // Base::Console().message("DVP::checkXDirection()\n"); Base::Vector3d xDir = XDirection.getValue(); if (DrawUtil::fpCompare(xDir.Length(), 0.0)) { return false; @@ -1266,7 +1266,7 @@ bool DrawViewPart::checkXDirection() const Base::Vector3d DrawViewPart::getXDirection() const { - // Base::Console().Message("DVP::getXDirection() - %s\n", Label.getValue()); + // Base::Console().message("DVP::getXDirection() - %s\n", Label.getValue()); Base::Vector3d result(1.0, 0.0, 0.0);//default X App::Property* prop = getPropertyByName("XDirection"); if (prop) {//have an XDirection property @@ -1329,7 +1329,7 @@ void DrawViewPart::spin(double angle) std::pair DrawViewPart::getDirsFromFront(ProjDirection viewType) { - // Base::Console().Message("DVP::getDirsFromFront(%s)\n", viewType.c_str()); + // Base::Console().message("DVP::getDirsFromFront(%s)\n", viewType.c_str()); std::pair result; Base::Vector3d projDir, rotVec; @@ -1461,7 +1461,7 @@ void DrawViewPart::removeReferenceVertex(std::string tag) //! remove reference vertexes from the view geometry void DrawViewPart::removeAllReferencesFromGeom() { - // Base::Console().Message("DVP::removeAllReferencesFromGeom()\n"); + // Base::Console().message("DVP::removeAllReferencesFromGeom()\n"); if (!m_referenceVerts.empty()) { std::vector gVerts = getVertexGeometry(); std::vector newVerts; @@ -1476,7 +1476,7 @@ void DrawViewPart::removeAllReferencesFromGeom() void DrawViewPart::resetReferenceVerts() { - // Base::Console().Message("DVP::resetReferenceVerts() %s\n", getNameInDocument()); + // Base::Console().message("DVP::resetReferenceVerts() %s\n", getNameInDocument()); removeAllReferencesFromGeom(); addReferencesToGeom(); } @@ -1544,11 +1544,11 @@ bool DrawViewPart::isCenterLine(const std::string& element) void DrawViewPart::dumpVerts(std::string text) { if (!geometryObject) { - Base::Console().Message("no verts to dump yet\n"); + Base::Console().message("no verts to dump yet\n"); return; } std::vector gVerts = getVertexGeometry(); - Base::Console().Message("%s - dumping %d vertGeoms\n", text.c_str(), gVerts.size()); + Base::Console().message("%s - dumping %d vertGeoms\n", text.c_str(), gVerts.size()); for (auto& gv : gVerts) { gv->dump(); } @@ -1557,7 +1557,7 @@ void DrawViewPart::dumpVerts(std::string text) void DrawViewPart::dumpCosVerts(std::string text) { std::vector cVerts = CosmeticVertexes.getValues(); - Base::Console().Message("%s - dumping %d CosmeticVertexes\n", text.c_str(), cVerts.size()); + Base::Console().message("%s - dumping %d CosmeticVertexes\n", text.c_str(), cVerts.size()); for (auto& cv : cVerts) { cv->dump("a CV"); } @@ -1566,7 +1566,7 @@ void DrawViewPart::dumpCosVerts(std::string text) void DrawViewPart::dumpCosEdges(std::string text) { std::vector cEdges = CosmeticEdges.getValues(); - Base::Console().Message("%s - dumping %d CosmeticEdge\n", text.c_str(), cEdges.size()); + Base::Console().message("%s - dumping %d CosmeticEdge\n", text.c_str(), cEdges.size()); for (auto& ce : cEdges) { ce->dump("a CE"); } diff --git a/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp b/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp index b5859cbf9f..f8969f92ea 100644 --- a/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp @@ -620,7 +620,7 @@ PyObject* DrawViewPartPy::getCosmeticEdge(PyObject *args) PyObject* DrawViewPartPy::getCosmeticEdgeBySelection(PyObject *args) { -// Base::Console().Message("DVPPI::getCosmeticEdgeBySelection()\n"); +// Base::Console().message("DVPPI::getCosmeticEdgeBySelection()\n"); char* name; if (!PyArg_ParseTuple(args, "s", &name)) { return nullptr; @@ -640,7 +640,7 @@ PyObject* DrawViewPartPy::getCosmeticEdgeBySelection(PyObject *args) PyObject* DrawViewPartPy::removeCosmeticEdge(PyObject *args) { -// Base::Console().Message("DVPPI::removeCosmeticEdge()\n"); +// Base::Console().message("DVPPI::removeCosmeticEdge()\n"); char* tag; if (!PyArg_ParseTuple(args, "s", &tag)) { return nullptr; @@ -656,7 +656,7 @@ PyObject* DrawViewPartPy::removeCosmeticEdge(PyObject *args) PyObject* DrawViewPartPy::makeCenterLine(PyObject *args) { -// Base::Console().Message("DVPPI::makeCenterLine()\n"); +// Base::Console().message("DVPPI::makeCenterLine()\n"); PyObject* pSubs; CenterLine::Mode mode = CenterLine::Mode::VERTICAL; std::vector subs; @@ -719,7 +719,7 @@ PyObject* DrawViewPartPy::getCenterLine(PyObject *args) PyObject* DrawViewPartPy::getCenterLineBySelection(PyObject *args) { -// Base::Console().Message("DVPPI::getCenterLineBySelection()\n"); +// Base::Console().message("DVPPI::getCenterLineBySelection()\n"); char* tag; if (!PyArg_ParseTuple(args, "s", &tag)) { return nullptr; @@ -738,7 +738,7 @@ PyObject* DrawViewPartPy::getCenterLineBySelection(PyObject *args) PyObject* DrawViewPartPy::removeCenterLine(PyObject *args) { -// Base::Console().Message("DVPPI::removeCenterLine()\n"); +// Base::Console().message("DVPPI::removeCenterLine()\n"); char* tag; if (!PyArg_ParseTuple(args, "s", &tag)) { return nullptr; @@ -754,7 +754,7 @@ PyObject* DrawViewPartPy::removeCenterLine(PyObject *args) PyObject* DrawViewPartPy::formatGeometricEdge(PyObject *args) { -// Base::Console().Message("DVPPI::formatGeometricEdge()\n"); +// Base::Console().message("DVPPI::formatGeometricEdge()\n"); int idx = -1; int style = Qt::SolidLine; Base::Color color = LineFormat::getDefEdgeColor(); diff --git a/src/Mod/TechDraw/App/DrawViewSection.cpp b/src/Mod/TechDraw/App/DrawViewSection.cpp index 8f6e5dd597..c7404766db 100644 --- a/src/Mod/TechDraw/App/DrawViewSection.cpp +++ b/src/Mod/TechDraw/App/DrawViewSection.cpp @@ -389,7 +389,7 @@ TopoDS_Shape DrawViewSection::getShapeToCut() } } else { - Base::Console().Message("DVS::getShapeToCut - base is weird\n"); + Base::Console().message("DVS::getShapeToCut - base is weird\n"); return {}; } return shapeToCut; @@ -427,7 +427,7 @@ App::DocumentObjectExecReturn* DrawViewSection::execute() Base::Vector3d orgPnt = SectionOrigin.getValue(); if (!isReallyInBox(gp_Pnt(orgPnt.x, orgPnt.y, orgPnt.z), centerBox)) { - Base::Console().Warning("DVS: SectionOrigin doesn't intersect part in %s\n", + Base::Console().warning("DVS: SectionOrigin doesn't intersect part in %s\n", getNameInDocument()); } @@ -496,7 +496,7 @@ void DrawViewSection::sectionExec(TopoDS_Shape& baseShape) waitingForCut(true); } catch (...) { - Base::Console().Message("DVS::sectionExec - failed to make section cut"); + Base::Console().message("DVS::sectionExec - failed to make section cut"); return; } } @@ -528,7 +528,7 @@ void DrawViewSection::makeSectionCut(const TopoDS_Shape& baseShape) const TopoDS_Solid& s = TopoDS::Solid(expl.Current()); FCBRepAlgoAPI_Cut mkCut(s, m_cuttingTool); if (!mkCut.IsDone()) { - Base::Console().Warning("DVS: Section cut has failed in %s\n", getNameInDocument()); + Base::Console().warning("DVS: Section cut has failed in %s\n", getNameInDocument()); continue; } builder.Add(cutPieces, mkCut.Shape()); @@ -558,7 +558,7 @@ void DrawViewSection::makeSectionCut(const TopoDS_Shape& baseShape) testBox.SetGap(0.0); if (testBox.IsVoid()) {// prism & input don't intersect. rawShape is // garbage, don't bother. - Base::Console().Warning("DVS::makeSectionCut - prism & input don't intersect - %s\n", + Base::Console().warning("DVS::makeSectionCut - prism & input don't intersect - %s\n", Label.getValue()); return; } @@ -599,7 +599,7 @@ TopoDS_Shape DrawViewSection::prepareShape(const TopoDS_Shape& rawShape, double } } catch (Standard_Failure& e1) { - Base::Console().Warning("DVS::prepareShape - failed to build shape %s - %s **\n", + Base::Console().warning("DVS::prepareShape - failed to build shape %s - %s **\n", getNameInDocument(), e1.GetMessageString()); } @@ -724,7 +724,7 @@ TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shap { if (shape.IsNull()) { // this shouldn't happen - Base::Console().Warning( + Base::Console().warning( "DrawViewSection::findSectionPlaneInter - %s - input shape is Null\n", getNameInDocument()); return {}; @@ -786,7 +786,7 @@ TopoDS_Compound DrawViewSection::mapToPage(const TopoDS_Shape& shapeToAlign) // stdZ); // project the faces in the shapeToAlign, build new faces from the resulting // wires and combine everything into a compound of faces - // Base::Console().Message("DVS::mapToPage() - shapeToAlign.null: %d\n", + // Base::Console().message("DVS::mapToPage() - shapeToAlign.null: %d\n", // shapeToAlign.IsNull()); if (debugSection()) { BRepTools::Write(shapeToAlign, "DVSShapeToAlign.brep");// debug @@ -849,7 +849,7 @@ TopoDS_Compound DrawViewSection::mapToPage(const TopoDS_Shape& shapeToAlign) // this may or may not be significant. In the offset or noparallel // strategies, a profile segment that is parallel to the SectionNormal // will not generate a face. - Base::Console().Log("DVS::mapToPage - %s - section face has no valid wires.\n", + Base::Console().log("DVS::mapToPage - %s - section face has no valid wires.\n", getNameInDocument()); continue; } @@ -900,7 +900,7 @@ TopoDS_Shape DrawViewSection::makeFaceFromWires(std::vector& inWire } if (!mkFace.IsDone()) { - Base::Console().Warning("DVS::makeFaceFromWires - %s - failed to make section face.\n", + Base::Console().warning("DVS::makeFaceFromWires - %s - failed to make section face.\n", getNameInDocument()); return {}; } @@ -918,7 +918,7 @@ TopoDS_Shape DrawViewSection::makeFaceFromWires(std::vector& inWire // turn OCC section faces into TD geometry std::vector DrawViewSection::makeTDSectionFaces(const TopoDS_Compound& topoDSFaces) { - // Base::Console().Message("DVS::makeTDSectionFaces()\n"); + // Base::Console().message("DVS::makeTDSectionFaces()\n"); std::vector tdSectionFaces; TopExp_Explorer sectionExpl(topoDSFaces, TopAbs_FACE); for (; sectionExpl.More(); sectionExpl.Next()) { @@ -976,7 +976,7 @@ Base::Vector3d DrawViewSection::getSectionDirectionOnBaseView() // find the points and directions to make the change point marks. ChangePointVector DrawViewSection::getChangePointsFromSectionLine() { - // Base::Console().Message("Dvs::getChangePointsFromSectionLine()\n"); + // Base::Console().message("Dvs::getChangePointsFromSectionLine()\n"); ChangePointVector result; std::vector allPoints; auto* baseDvp = freecad_cast(BaseView.getValue()); @@ -1151,7 +1151,7 @@ gp_Ax2 DrawViewSection::getSectionCS() const sectionCS = gp_Ax2(gOrigin, gNormal, gXDir); } catch (...) { - Base::Console().Error("DVS::getSectionCS - %s - failed to create section CS\n", + Base::Console().error("DVS::getSectionCS - %s - failed to create section CS\n", getNameInDocument()); } return sectionCS; @@ -1291,7 +1291,7 @@ void DrawViewSection::makeLineSets() std::string fileSpec = PatIncluded.getValue(); Base::FileInfo fi(fileSpec); if (!fi.isReadable()) { - Base::Console().Message("%s can not read hatch file: %s\n", + Base::Console().message("%s can not read hatch file: %s\n", getNameInDocument(), fileSpec.c_str()); return; diff --git a/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp b/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp index e7ab9d3da6..36bd382ffd 100644 --- a/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp +++ b/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp @@ -163,7 +163,7 @@ std::string DrawViewSpreadsheet::getSheetImage() std::string sColStart, sColEnd; if (boost::regex_search(scellstart, what, re)) { if (what.size() < 3) { - Base::Console().Error("%s - start cell (%s) is invalid\n", getNameInDocument(), + Base::Console().error("%s - start cell (%s) is invalid\n", getNameInDocument(), CellStart.getValue()); return std::string(); } @@ -175,7 +175,7 @@ std::string DrawViewSpreadsheet::getSheetImage() iRowStart = std::stoi(rowPart); } catch (...) { - Base::Console().Error("%s - start cell (%s) invalid row\n", + Base::Console().error("%s - start cell (%s) invalid row\n", getNameInDocument(), rowPart.c_str()); return std::string(); } @@ -183,7 +183,7 @@ std::string DrawViewSpreadsheet::getSheetImage() if (boost::regex_search(scellend, what, re)) { if (what.size() < 3) { - Base::Console().Error("%s - end cell (%s) is invalid\n", getNameInDocument(), CellEnd.getValue()); + Base::Console().error("%s - end cell (%s) is invalid\n", getNameInDocument(), CellEnd.getValue()); } else { colPart = what[1]; sColEnd = colPart; @@ -192,7 +192,7 @@ std::string DrawViewSpreadsheet::getSheetImage() iRowEnd = std::stoi(rowPart); } catch (...) { - Base::Console().Error("%s - end cell (%s) invalid row\n", + Base::Console().error("%s - end cell (%s) invalid row\n", getNameInDocument(), rowPart.c_str()); return std::string(); } @@ -204,7 +204,7 @@ std::string DrawViewSpreadsheet::getSheetImage() //validate range start column in sheet's available columns int iAvailColStart = colInList(availcolumns, sColStart); if (iAvailColStart < 0) { //not found range start column in availcolumns list - Base::Console().Error("DVS - %s - start Column (%s) is invalid\n", + Base::Console().error("DVS - %s - start Column (%s) is invalid\n", getNameInDocument(), sColStart.c_str()); return std::string(); } @@ -212,7 +212,7 @@ std::string DrawViewSpreadsheet::getSheetImage() //validate range end column in sheet's available columns int iAvailColEnd = colInList(availcolumns, sColEnd); if (iAvailColEnd < 0) { - Base::Console().Error("DVS - %s - end Column (%s) is invalid\n", + Base::Console().error("DVS - %s - end Column (%s) is invalid\n", getNameInDocument(), sColEnd.c_str()); return std::string(); } @@ -220,7 +220,7 @@ std::string DrawViewSpreadsheet::getSheetImage() //check for logical range if ( (iAvailColStart > iAvailColEnd) || (iRowStart > iRowEnd) ) { - Base::Console().Error("%s - cell range is illogical\n", getNameInDocument()); + Base::Console().error("%s - cell range is illogical\n", getNameInDocument()); return std::string(); } @@ -286,7 +286,7 @@ std::string DrawViewSpreadsheet::getSheetImage() DrawUtil::encodeXmlSpecialChars(temp); field << temp; } else { - Base::Console().Error("DVSS: Unknown property type\n"); + Base::Console().error("DVSS: Unknown property type\n"); } celltext = field.str(); } diff --git a/src/Mod/TechDraw/App/DrawViewSymbol.cpp b/src/Mod/TechDraw/App/DrawViewSymbol.cpp index 56727ea298..66752c7d20 100644 --- a/src/Mod/TechDraw/App/DrawViewSymbol.cpp +++ b/src/Mod/TechDraw/App/DrawViewSymbol.cpp @@ -196,9 +196,9 @@ bool DrawViewSymbol::loadQDomDocument(QDomDocument& symbolDocument) bool rc = symbolDocument.setContent(qba, nsProcess, &errorMsg, &errorLine, &errorCol); if (!rc) { //invalid SVG message - Base::Console().Warning("DrawViewSymbol - %s - SVG for Symbol is not valid. See log.\n", + Base::Console().warning("DrawViewSymbol - %s - SVG for Symbol is not valid. See log.\n", getNameInDocument()); - Base::Console().Log("DrawViewSymbol - %s - len: %d rc: %d error: %s line: %d col: %d\n", + Base::Console().log("DrawViewSymbol - %s - len: %d rc: %d error: %s line: %d col: %d\n", getNameInDocument(), strlen(symbol), rc, qPrintable(errorMsg), errorLine, errorCol); } @@ -207,9 +207,9 @@ bool DrawViewSymbol::loadQDomDocument(QDomDocument& symbolDocument) QDomDocument::ParseResult rc = symbolDocument.setContent(qba); // Use the default ParseOptions if (!rc) { //invalid SVG message - Base::Console().Warning("DrawViewSymbol - %s - SVG for Symbol is not valid. See log.\n", + Base::Console().warning("DrawViewSymbol - %s - SVG for Symbol is not valid. See log.\n", getNameInDocument()); - Base::Console().Log("DrawViewSymbol - %s - len: %d error: %s line: %d col: %d\n", + Base::Console().log("DrawViewSymbol - %s - len: %d error: %s line: %d col: %d\n", getNameInDocument(), strlen(symbol), qPrintable(rc.errorMessage), rc.errorLine, rc.errorColumn); } diff --git a/src/Mod/TechDraw/App/DrawWeldSymbol.cpp b/src/Mod/TechDraw/App/DrawWeldSymbol.cpp index d6e98175f3..fe50e74475 100644 --- a/src/Mod/TechDraw/App/DrawWeldSymbol.cpp +++ b/src/Mod/TechDraw/App/DrawWeldSymbol.cpp @@ -62,11 +62,11 @@ DrawWeldSymbol::DrawWeldSymbol() //but if this is a restore of an existing DWS, the tiles will loaded elsewhere void DrawWeldSymbol::onSettingDocument() { -// Base::Console().Message("DWS::onSettingDocument() - doc: %s\n", getDocument()->getName()); +// Base::Console().message("DWS::onSettingDocument() - doc: %s\n", getDocument()->getName()); App::Document* doc = getDocument(); if (doc->testStatus(App::Document::Status::Restoring)) { -// Base::Console().Message("DWS::onSettingDocument() - restoring!\n"); +// Base::Console().message("DWS::onSettingDocument() - restoring!\n"); return; } @@ -113,7 +113,7 @@ short DrawWeldSymbol::mustExecute() const App::DocumentObjectExecReturn *DrawWeldSymbol::execute() { -// Base::Console().Message("DWS::execute()\n"); +// Base::Console().message("DWS::execute()\n"); if (!keepUpdated()) { return DrawView::execute(); } @@ -124,7 +124,7 @@ App::DocumentObjectExecReturn *DrawWeldSymbol::execute() std::vector DrawWeldSymbol::getTiles() const { -// Base::Console().Message("DWS::getTiles()\n"); +// Base::Console().message("DWS::getTiles()\n"); std::vector result; std::vector tiles = getInList(); diff --git a/src/Mod/TechDraw/App/EdgeWalker.cpp b/src/Mod/TechDraw/App/EdgeWalker.cpp index 3d3f1f4891..57e438e659 100644 --- a/src/Mod/TechDraw/App/EdgeWalker.cpp +++ b/src/Mod/TechDraw/App/EdgeWalker.cpp @@ -68,13 +68,13 @@ void edgeVisitor::next_edge(Edge e) void edgeVisitor::begin_face() { -// Base::Console().Message("EV::begin_face()\n"); +// Base::Console().message("EV::begin_face()\n"); wireEdges.clear(); } void edgeVisitor::end_face() { -// Base::Console().Message("EV::end_face()\n"); +// Base::Console().message("EV::end_face()\n"); graphWires.push_back(wireEdges); } @@ -103,7 +103,7 @@ EdgeWalker::~EdgeWalker() //loads a list of unique edges into the traversal mechanism bool EdgeWalker::loadEdges(std::vector& edges) { -// Base::Console().Message("EW::loadEdges(we) - WEdgesIn: %d\n", edges.size()); +// Base::Console().message("EW::loadEdges(we) - WEdgesIn: %d\n", edges.size()); int idx = 0; for (auto& e: edges) { std::pair p; @@ -119,7 +119,7 @@ bool EdgeWalker::loadEdges(std::vector& edges) bool EdgeWalker::loadEdges(std::vector edges) { -// Base::Console().Message("EW::loadEdges(TopoDS) - edges: %d\n", edges.size()); +// Base::Console().message("EW::loadEdges(TopoDS) - edges: %d\n", edges.size()); if (edges.empty()) { throw Base::ValueError("EdgeWalker has no edges to load\n"); } @@ -146,7 +146,7 @@ bool EdgeWalker::setSize(std::size_t size) bool EdgeWalker::prepare() { - //Base::Console().Message("TRACE - EW::prepare()\n"); + //Base::Console().message("TRACE - EW::prepare()\n"); // Initialize the interior edge index property_map::type e_index = get(edge_index, m_g); graph_traits::edges_size_type edge_count = 0; @@ -183,14 +183,14 @@ std::vector EdgeWalker::execute(std::vector edgeList, ewWireList EdgeWalker::getResult() { - //Base::Console().Message("TRACE - EW::getResult()\n"); + //Base::Console().message("TRACE - EW::getResult()\n"); // Return value is a list of many wires each of which is a list of many WE return m_eV.getResult(); } std::vector EdgeWalker::getResultWires() { - //Base::Console().Message("TRACE - EW::getResultWires()\n"); + //Base::Console().message("TRACE - EW::getResultWires()\n"); std::vector fw; ewWireList result = m_eV.getResult(); if (result.wires.empty()) { @@ -213,7 +213,7 @@ std::vector EdgeWalker::getResultWires() std::vector EdgeWalker::getResultNoDups() { - //Base::Console().Message("TRACE - EW::getResultNoDups()\n"); + //Base::Console().message("TRACE - EW::getResultNoDups()\n"); std::vector fw; ewWireList result = m_eV.getResult(); if (result.wires.empty()) { @@ -240,7 +240,7 @@ std::vector EdgeWalker::getResultNoDups() //! make a clean wire with sorted, oriented, connected, etc edges TopoDS_Wire EdgeWalker::makeCleanWire(std::vector edges, double tol) { - //Base::Console().Message("TRACE - EW::makeCleanWire()\n"); + //Base::Console().message("TRACE - EW::makeCleanWire()\n"); TopoDS_Wire result; BRepBuilderAPI_MakeWire mkWire; ShapeFix_ShapeTolerance sTol; @@ -269,7 +269,7 @@ TopoDS_Wire EdgeWalker::makeCleanWire(std::vector edges, double tol std::vector EdgeWalker:: makeUniqueVList(std::vector edges) { -// Base::Console().Message("TRACE - EW::makeUniqueVList() - edgesIn: %d\n", edges.size()); +// Base::Console().message("TRACE - EW::makeUniqueVList() - edgesIn: %d\n", edges.size()); std::vector uniqueVert; for(auto& e:edges) { Base::Vector3d v1 = DrawUtil::vertex2Vector(TopExp::FirstVertex(e)); @@ -293,7 +293,7 @@ std::vector EdgeWalker:: makeUniqueVList(std::vector uniqueVert.push_back(TopExp::LastVertex(e)); } } -// Base::Console().Message("EW::makeUniqueVList - verts out: %d\n", uniqueVert.size()); +// Base::Console().message("EW::makeUniqueVList - verts out: %d\n", uniqueVert.size()); return uniqueVert; } @@ -301,7 +301,7 @@ std::vector EdgeWalker:: makeUniqueVList(std::vector std::vector EdgeWalker::makeWalkerEdges(std::vector edges, std::vector verts) { -// Base::Console().Message("TRACE - EW::makeWalkerEdges() - edges: %d verts: %d\n", edges.size(), verts.size()); +// Base::Console().message("TRACE - EW::makeWalkerEdges() - edges: %d verts: %d\n", edges.size(), verts.size()); m_saveInEdges = edges; std::vector walkerEdges; for (const auto& e:edges) { @@ -323,13 +323,13 @@ std::vector EdgeWalker::makeWalkerEdges(std::vector edg walkerEdges.push_back(we); } - //Base::Console().Message("TRACE - EW::makeWalkerEdges - returns we: %d\n", walkerEdges.size()); + //Base::Console().message("TRACE - EW::makeWalkerEdges - returns we: %d\n", walkerEdges.size()); return walkerEdges; } size_t EdgeWalker::findUniqueVert(TopoDS_Vertex vx, std::vector &uniqueVert) { -// Base::Console().Message("TRACE - EW::findUniqueVert()\n"); +// Base::Console().message("TRACE - EW::findUniqueVert()\n"); std::size_t idx = 0; Base::Vector3d vx3d = DrawUtil::vertex2Vector(vx); for(auto& v : uniqueVert) { @@ -352,7 +352,7 @@ std::vector EdgeWalker::sortStrip(std::vector fw, bool } std::vector sortedWires = sortWiresBySize(closedWires, false); //biggest 1st if (sortedWires.empty()) { - Base::Console().Message("EW::sortStrip - no sorted Wires!\n"); + Base::Console().message("EW::sortStrip - no sorted Wires!\n"); return sortedWires; } @@ -366,7 +366,7 @@ std::vector EdgeWalker::sortStrip(std::vector fw, bool // sort (closed) wires in order of enclosed area std::vector EdgeWalker::sortWiresBySize(std::vector& w, bool ascend) { - //Base::Console().Message("TRACE - EW::sortWiresBySize()\n"); + //Base::Console().message("TRACE - EW::sortWiresBySize()\n"); std::vector wires = w; std::sort(wires.begin(), wires.end(), EdgeWalker::wireCompare); if (ascend) { @@ -386,7 +386,7 @@ std::vector EdgeWalker::sortWiresBySize(std::vector& w std::vector EdgeWalker::makeEmbedding(const std::vector edges, const std::vector uniqueVList) { -// Base::Console().Message("TRACE - EW::makeEmbedding(edges: %d, verts: %d)\n", +// Base::Console().message("TRACE - EW::makeEmbedding(edges: %d, verts: %d)\n", // edges.size(), uniqueVList.size()); std::vector result; @@ -425,7 +425,7 @@ std::vector EdgeWalker::makeEmbedding(const std::vector //! get incidence row as edge indices for v'th vertex std::vector EdgeWalker::getEmbeddingRowIx(int v) { -// //Base::Console().Message("TRACE - EW::getEmbeddingRowIx(%d)\n", v); +// //Base::Console().message("TRACE - EW::getEmbeddingRowIx(%d)\n", v); std::vector result; embedItem ei = m_embedding[v]; for (auto& ii: ei.incidenceList) { @@ -437,7 +437,7 @@ std::vector EdgeWalker::getEmbeddingRowIx(int v) //! get incidence row as edgeDescriptors for v'th vertex std::vector EdgeWalker::getEmbeddingRow(int v) { -// //Base::Console().Message("TRACE - EW::getEmbeddingRow(%d)\n", v); +// //Base::Console().message("TRACE - EW::getEmbeddingRow(%d)\n", v); std::vector result; embedItem ei = m_embedding[v]; for (auto& ii: ei.incidenceList) { @@ -564,7 +564,7 @@ std::string embedItem::dump() std::vector embedItem::sortIncidenceList (std::vector &list, bool ascend) { - //Base::Console().Message("TRACE - eI::sortIncidenceList()\n"); + //Base::Console().message("TRACE - eI::sortIncidenceList()\n"); std::vector< incidenceItem > tempList = list; std::sort(tempList.begin(), tempList.end(), incidenceItem::iiCompare); if (ascend) { diff --git a/src/Mod/TechDraw/App/Geometry.cpp b/src/Mod/TechDraw/App/Geometry.cpp index 3023677532..493d48914c 100644 --- a/src/Mod/TechDraw/App/Geometry.cpp +++ b/src/Mod/TechDraw/App/Geometry.cpp @@ -292,7 +292,7 @@ std::vector BaseGeom::findEndPoints() result.emplace_back(p.X(), p.Y(), p.Z()); } else { //TODO: this should throw something - Base::Console().Message("Geometry::findEndPoints - OCC edge not found\n"); + Base::Console().message("Geometry::findEndPoints - OCC edge not found\n"); throw Base::RuntimeError("no OCC edge in Geometry::findEndPoints"); } return result; @@ -306,7 +306,7 @@ Base::Vector3d BaseGeom::getStartPoint() return verts[0]; } else { //TODO: this should throw something - Base::Console().Message("Geometry::getStartPoint - start point not found!\n"); + Base::Console().message("Geometry::getStartPoint - start point not found!\n"); Base::Vector3d badResult(0.0, 0.0, 0.0); return badResult; } @@ -319,7 +319,7 @@ Base::Vector3d BaseGeom::getEndPoint() if (verts.size() != 2) { //TODO: this should throw something - Base::Console().Message("Geometry::getEndPoint - end point not found!\n"); + Base::Console().message("Geometry::getEndPoint - end point not found!\n"); Base::Vector3d badResult(0.0, 0.0, 0.0); return badResult; } @@ -433,7 +433,7 @@ bool BaseGeom::closed() // return a BaseGeom similar to this, but inverted with respect to Y axis BaseGeomPtr BaseGeom::inverted() { -// Base::Console().Message("BG::inverted()\n"); +// Base::Console().message("BG::inverted()\n"); TopoDS_Shape invertedShape = ShapeUtils::invertGeometry(occEdge); TopoDS_Edge invertedEdge = TopoDS::Edge(invertedShape); return baseFactory(invertedEdge); @@ -462,7 +462,7 @@ std::string BaseGeom::geomTypeName() BaseGeomPtr BaseGeom::baseFactory(TopoDS_Edge edge, bool isCosmetic) { if (edge.IsNull()) { - Base::Console().Message("BG::baseFactory - input edge is NULL \n"); + Base::Console().message("BG::baseFactory - input edge is NULL \n"); } //weed out rubbish edges before making geometry if (!isCosmetic && !validateEdge(edge)) { @@ -529,18 +529,18 @@ BaseGeomPtr BaseGeom::baseFactory(TopoDS_Edge edge, bool isCosmetic) } } } else { -// Base::Console().Message("Geom::baseFactory - circEdge is Null\n"); +// Base::Console().message("Geom::baseFactory - circEdge is Null\n"); result = bspline; } break; } catch (const Standard_Failure& e) { - Base::Console().Log("Geom::baseFactory - OCC error - %s - while making spline\n", + Base::Console().log("Geom::baseFactory - OCC error - %s - while making spline\n", e.GetMessageString()); break; } catch (...) { - Base::Console().Log("Geom::baseFactory - unknown error occurred while making spline\n"); + Base::Console().log("Geom::baseFactory - unknown error occurred while making spline\n"); break; } break; } // end bspline case @@ -577,7 +577,7 @@ TopoDS_Edge BaseGeom::completeEdge(const TopoDS_Edge &edge) { } } catch (Standard_Failure &e) { - Base::Console().Error("BaseGeom::completeEdge OCC error: %s\n", e.GetMessageString()); + Base::Console().error("BaseGeom::completeEdge OCC error: %s\n", e.GetMessageString()); } return TopoDS_Edge(); @@ -621,7 +621,7 @@ std::vector BaseGeom::intersection(TechDraw::BaseGeomPtr geom2) TopoShape BaseGeom::asTopoShape(double scale) { -// Base::Console().Message("BG::asTopoShape(%.3f) - dump: %s\n", scale, dump().c_str()); +// Base::Console().message("BG::asTopoShape(%.3f) - dump: %s\n", scale, dump().c_str()); TopoDS_Shape unscaledShape = ShapeUtils::scaleShape(getOCCEdge(), 1.0 / scale); TopoDS_Edge unscaledEdge = TopoDS::Edge(unscaledShape); return unscaledEdge; @@ -655,7 +655,7 @@ Ellipse::Ellipse(Base::Vector3d c, double mnr, double mjr) GC_MakeEllipse me(gp_Ax2(gp_Pnt(c.x, c.y, c.z), gp_Dir(0.0, 0.0, 1.0)), major, minor); if (!me.IsDone()) { - Base::Console().Message("G:Ellipse - failed to make Ellipse\n"); + Base::Console().message("G:Ellipse - failed to make Ellipse\n"); } const Handle(Geom_Ellipse) gEllipse = me.Value(); BRepBuilderAPI_MakeEdge mkEdge(gEllipse, 0.0, 2 * std::numbers::pi); @@ -683,7 +683,7 @@ AOE::AOE(const TopoDS_Edge &e) : Ellipse(e) a = v3.DotCross(v1, v2); } catch (const Standard_Failure& e) { - Base::Console().Error("Geom::AOE::AOE - OCC error - %s - while making AOE in ctor\n", + Base::Console().error("Geom::AOE::AOE - OCC error - %s - while making AOE in ctor\n", e.GetMessageString()); } @@ -1298,7 +1298,7 @@ Vertex::Vertex(double x, double y) Vertex::Vertex(Base::Vector3d v) : Vertex(v.x, v.y) { -// Base::Console().Message("V::V(%s)\n", +// Base::Console().message("V::V(%s)\n", // DrawUtil::formatVector(v).c_str()); } @@ -1372,7 +1372,7 @@ void Vertex::Restore(Base::XMLReader &reader) void Vertex::dump(const char* title) { - Base::Console().Message("TD::Vertex - %s - point: %s vis: %d cosmetic: %d cosLink: %d cosTag: %s\n", + Base::Console().message("TD::Vertex - %s - point: %s vis: %d cosmetic: %d cosLink: %d cosTag: %s\n", title, DrawUtil::formatVector(pnt).c_str(), hlrVisible, cosmetic, cosmeticLink, cosmeticTag.c_str()); } @@ -1452,7 +1452,7 @@ BaseGeomPtrVector GeometryUtils::chainGeoms(BaseGeomPtrVector geoms) TopoDS_Edge GeometryUtils::edgeFromGeneric(TechDraw::GenericPtr g) { -// Base::Console().Message("GU::edgeFromGeneric()\n"); +// Base::Console().message("GU::edgeFromGeneric()\n"); //TODO: note that this isn't quite right as g can be a polyline! //sb points.first, points.last //and intermediates should be added to Point @@ -1571,7 +1571,7 @@ bool GeometryUtils::getCircleParms(const TopoDS_Edge& occEdge, double& radius, B return true; } catch (Standard_Failure& err) { - Base::Console().Message("Geo::getCircleParms - failed to make a circle\n"); + Base::Console().message("Geo::getCircleParms - failed to make a circle\n"); } return false; @@ -1756,7 +1756,7 @@ TopoDS_Face GeometryUtils::makePerforatedFace(FacePtr bigCheese, const std::vec faceShape = Part::FaceMakerCheese::makeFace(cheeseIngredients); } catch (const Standard_Failure&) { - Base::Console().Warning("Area - could not make holes in face\n"); + Base::Console().warning("Area - could not make holes in face\n"); return flippedFace; } diff --git a/src/Mod/TechDraw/App/GeometryMatcher.cpp b/src/Mod/TechDraw/App/GeometryMatcher.cpp index 0f7d26badd..4002f4151c 100644 --- a/src/Mod/TechDraw/App/GeometryMatcher.cpp +++ b/src/Mod/TechDraw/App/GeometryMatcher.cpp @@ -160,7 +160,7 @@ bool GeometryMatcher::compareLines(const TopoDS_Edge& edge1, const TopoDS_Edge& // how does the edge that was NOT null in compareEdges become null here? // should not happen, but does! if (edge1.IsNull() || edge2.IsNull()) { - // Base::Console().Message("GM::compareLine - an input edge is null\n"); + // Base::Console().message("GM::compareLine - an input edge is null\n"); return false; } return compareEndPoints(edge1, edge2); @@ -232,7 +232,7 @@ bool GeometryMatcher::compareBSplines(const TopoDS_Edge& edge1, const TopoDS_Edg circleEdge2 = GeometryUtils::asCircle(edge2, isArc2); } catch (Base::RuntimeError&) { - Base::Console().Error("GeometryMatcher failed to make circles from splines\n"); + Base::Console().error("GeometryMatcher failed to make circles from splines\n"); return false; } if (!isArc1 && !isArc2) { diff --git a/src/Mod/TechDraw/App/GeometryObject.cpp b/src/Mod/TechDraw/App/GeometryObject.cpp index 021cb13534..eeb6e192d3 100644 --- a/src/Mod/TechDraw/App/GeometryObject.cpp +++ b/src/Mod/TechDraw/App/GeometryObject.cpp @@ -162,7 +162,7 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, const gp_Ax2& vie brep_hlr->Hide(); } catch (const Standard_Failure& e) { - Base::Console().Error("GO::projectShape - OCC error - %s - while projecting shape\n", + Base::Console().error("GO::projectShape - OCC error - %s - while projecting shape\n", e.GetMessageString()); throw Base::RuntimeError("GeometryObject::projectShape - OCC error"); } @@ -250,7 +250,7 @@ void GeometryObject::projectShape(const TopoDS_Shape& inShape, const gp_Ax2& vie //convert the hlr output into TD Geometry void GeometryObject::makeTDGeometry() { -// Base::Console().Message("GO::makeTDGeometry()\n"); +// Base::Console().message("GO::makeTDGeometry()\n"); extractGeometry(EdgeClass::HARD, //always show the hard&outline visible lines true); extractGeometry(EdgeClass::OUTLINE, @@ -289,7 +289,7 @@ void GeometryObject::makeTDGeometry() //!set up a hidden line remover and project a shape with it void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, const gp_Ax2& viewAxis) { -// Base::Console().Message("GO::projectShapeWithPolygonAlgo()\n"); +// Base::Console().message("GO::projectShapeWithPolygonAlgo()\n"); // Clear previous Geometry clear(); @@ -329,7 +329,7 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, cons brep_hlrPoly->Update(); } catch (const Standard_Failure& e) { - Base::Console().Error( + Base::Console().error( "GO::projectShapeWithPolygonAlgo - OCC error - %s - while projecting shape\n", e.GetMessageString()); throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error"); @@ -377,7 +377,7 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, cons hidOutline =ShapeUtils::invertGeometry(hidOutline); } catch (const Standard_Failure& e) { - Base::Console().Error( + Base::Console().error( "GO::projectShapeWithPolygonAlgo - OCC error - %s - while extracting edges\n", e.GetMessageString()); throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error occurred " @@ -397,7 +397,7 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, cons //TODO: allow use of perspective projector TopoDS_Shape GeometryObject::projectSimpleShape(const TopoDS_Shape& shape, const gp_Ax2& CS) { - // Base::Console().Message("GO::()\n"); + // Base::Console().message("GO::()\n"); if (shape.IsNull()) { throw Base::ValueError("GO::projectSimpleShape - input shape is NULL"); } @@ -431,7 +431,7 @@ TopoDS_Shape GeometryObject::simpleProjection(const TopoDS_Shape& shape, const g TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape& face, const gp_Ax2& CS) { - // Base::Console().Message("GO::projectFace()\n"); + // Base::Console().message("GO::projectFace()\n"); if (face.IsNull()) { throw Base::ValueError("GO::projectFace - input Face is NULL"); } @@ -454,7 +454,7 @@ TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape& face, const gp_Ax2& //!add edges meeting filter criteria for category, visibility void GeometryObject::extractGeometry(EdgeClass category, bool hlrVisible) { - // Base::Console().Message("GO::extractGeometry(%d, %d)\n", category, hlrVisible); + // Base::Console().message("GO::extractGeometry(%d, %d)\n", category, hlrVisible); TopoDS_Shape filtEdges; if (hlrVisible) { switch (category) { @@ -474,7 +474,7 @@ void GeometryObject::extractGeometry(EdgeClass category, bool hlrVisible) filtEdges = visIso; break; default: - Base::Console().Warning( + Base::Console().warning( "GeometryObject::ExtractGeometry - unsupported hlrVisible EdgeClass: %d\n", static_cast(category)); return; @@ -498,7 +498,7 @@ void GeometryObject::extractGeometry(EdgeClass category, bool hlrVisible) filtEdges = hidIso; break; default: - Base::Console().Warning( + Base::Console().warning( "GeometryObject::ExtractGeometry - unsupported hidden EdgeClass: %d\n", static_cast(category)); return; @@ -512,7 +512,7 @@ void GeometryObject::extractGeometry(EdgeClass category, bool hlrVisible) void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, EdgeClass category, bool hlrVisible) { -// Base::Console().Message("GO::addGeomFromCompound(%d, %d)\n", category, hlrVisible); +// Base::Console().message("GO::addGeomFromCompound(%d, %d)\n", category, hlrVisible); if (edgeCompound.IsNull()) { return; // There is no OpenCascade Geometry to be calculated } @@ -669,7 +669,7 @@ int GeometryObject::addCosmeticVertex(Base::Vector3d pos, std::string tagString) // insertGeomForCE(ce) int GeometryObject::addCosmeticEdge(CosmeticEdge* ce) { - // Base::Console().Message("GO::addCosmeticEdge(%X) 0\n", ce); + // Base::Console().message("GO::addCosmeticEdge(%X) 0\n", ce); double scale = m_parent->getScale(); TechDraw::BaseGeomPtr e = ce->scaledGeometry(scale); e->setCosmetic(true); @@ -684,7 +684,7 @@ int GeometryObject::addCosmeticEdge(CosmeticEdge* ce) //this should be made obsolete and the variant with tag used instead int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end) { - // Base::Console().Message("GO::addCosmeticEdge() 1 - deprec?\n"); + // Base::Console().message("GO::addCosmeticEdge() 1 - deprec?\n"); gp_Pnt gp1(start.x, start.y, start.z); gp_Pnt gp2(end.x, end.y, end.z); TopoDS_Edge occEdge = BRepBuilderAPI_MakeEdge(gp1, gp2); @@ -700,7 +700,7 @@ int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end) int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end, std::string tagString) { - // Base::Console().Message("GO::addCosmeticEdge() 2\n"); + // Base::Console().message("GO::addCosmeticEdge() 2\n"); gp_Pnt gp1(start.x, start.y, start.z); gp_Pnt gp2(end.x, end.y, end.z); TopoDS_Edge occEdge = BRepBuilderAPI_MakeEdge(gp1, gp2); @@ -716,7 +716,7 @@ int GeometryObject::addCosmeticEdge(Base::Vector3d start, Base::Vector3d end, st int GeometryObject::addCosmeticEdge(TechDraw::BaseGeomPtr base, std::string tagString) { - // Base::Console().Message("GO::addCosmeticEdge(%X, %s) 3\n", base, tagString.c_str()); + // Base::Console().message("GO::addCosmeticEdge(%X, %s) 3\n", base, tagString.c_str()); base->setCosmetic(true); base->setHlrVisible(true); base->source(SourceType::COSMETICEDGE); @@ -730,7 +730,7 @@ int GeometryObject::addCosmeticEdge(TechDraw::BaseGeomPtr base, std::string tagS int GeometryObject::addCenterLine(TechDraw::BaseGeomPtr base, std::string tag) // int s, int si) { - // Base::Console().Message("GO::addCenterLine()\n"); + // Base::Console().message("GO::addCenterLine()\n"); base->setCosmetic(true); base->setCosmeticTag(tag); base->source(SourceType::CENTERLINE); @@ -802,7 +802,7 @@ bool GeometryObject::isWithinArc(double theta, double first, double last, bool c //note bbx is scaled Base::BoundBox3d GeometryObject::calcBoundingBox() const { - // Base::Console().Message("GO::calcBoundingBox() - edges: %d\n", edgeGeom.size()); + // Base::Console().message("GO::calcBoundingBox() - edges: %d\n", edgeGeom.size()); Bnd_Box testBox; testBox.SetGap(0.0); if (!edgeGeom.empty()) { diff --git a/src/Mod/TechDraw/App/HatchLine.cpp b/src/Mod/TechDraw/App/HatchLine.cpp index c5a6b33975..b155943208 100644 --- a/src/Mod/TechDraw/App/HatchLine.cpp +++ b/src/Mod/TechDraw/App/HatchLine.cpp @@ -230,7 +230,7 @@ void PATLineSpec::load(std::string& lineSpec) { std::vector values = split(lineSpec); if (values.size() < 5) { - Base::Console().Message( "PATLineSpec::load(%s) invalid entry in pattern\n", lineSpec.c_str() ); + Base::Console().message( "PATLineSpec::load(%s) invalid entry in pattern\n", lineSpec.c_str() ); return; } m_angle = values[0]; @@ -256,7 +256,7 @@ std::vector PATLineSpec::split(std::string line) result.push_back(std::stod(cell)); } catch (const std::invalid_argument& ia) { - Base::Console().Warning("Invalid number in cell: %s (%s) \n", cell.c_str(), ia.what()); + Base::Console().warning("Invalid number in cell: %s (%s) \n", cell.c_str(), ia.what()); result.push_back(0.0); } } @@ -265,17 +265,17 @@ std::vector PATLineSpec::split(std::string line) void PATLineSpec::dump(const char* title) { - Base::Console().Message( "DUMP: %s\n", title); - Base::Console().Message( "Angle: %.3f\n", m_angle); - Base::Console().Message( "Origin: %s\n", DrawUtil::formatVector(m_origin).c_str()); - Base::Console().Message( "Offset: %.3f\n", m_offset); - Base::Console().Message( "Interval: %.3f\n", m_interval); + Base::Console().message( "DUMP: %s\n", title); + Base::Console().message( "Angle: %.3f\n", m_angle); + Base::Console().message( "Origin: %s\n", DrawUtil::formatVector(m_origin).c_str()); + Base::Console().message( "Offset: %.3f\n", m_offset); + Base::Console().message( "Interval: %.3f\n", m_interval); // std::stringstream ss; // for (auto& d: m_dashParms) { // ss << d << ", "; // } // ss << "end"; -// Base::Console().Message( "DashSpec: %s\n", ss.str().c_str()); +// Base::Console().message( "DashSpec: %s\n", ss.str().c_str()); m_dashParms.dump("dashspec"); } @@ -287,7 +287,7 @@ std::vector PATLineSpec::getSpecsForPattern(std::string& parmFile, Base::ifstream inFile; inFile.open(fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message("Cannot open input file.\n"); + Base::Console().message("Cannot open input file.\n"); return std::vector(); } @@ -309,7 +309,7 @@ std::vector PATLineSpec::getSpecsForPattern(std::string& parmFile, bool PATLineSpec::findPatternStart(std::ifstream& inFile, std::string& parmName) { -// Base::Console().Message("HL::findPatternStart() - parmName: %s\n", parmName.c_str()); +// Base::Console().message("HL::findPatternStart() - parmName: %s\n", parmName.c_str()); while (inFile.good() ){ std::string line; std::getline(inFile, line); @@ -364,7 +364,7 @@ std::vector PATLineSpec::getPatternList(std::string& parmFile) Base::ifstream inFile; inFile.open (fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message( "Cannot open input file.\n"); + Base::Console().message( "Cannot open input file.\n"); return result; } @@ -457,7 +457,7 @@ void DashSpec::dump(const char* title) for (auto& p: m_parms) { ss << p << ", "; } - Base::Console().Message("DUMP - DashSpec - %s\n", ss.str().c_str()); + Base::Console().message("DUMP - DashSpec - %s\n", ss.str().c_str()); } diff --git a/src/Mod/TechDraw/App/LandmarkDimension.cpp b/src/Mod/TechDraw/App/LandmarkDimension.cpp index c82bcedc25..fbe292531c 100644 --- a/src/Mod/TechDraw/App/LandmarkDimension.cpp +++ b/src/Mod/TechDraw/App/LandmarkDimension.cpp @@ -87,7 +87,7 @@ short LandmarkDimension::mustExecute() const App::DocumentObjectExecReturn *LandmarkDimension::execute() { - // Base::Console().Message("LD::execute() - %s\n", getNameInDocument()); + // Base::Console().message("LD::execute() - %s\n", getNameInDocument()); if (!okToProceed()) { return App::DocumentObject::StdReturn; } @@ -96,7 +96,7 @@ App::DocumentObjectExecReturn *LandmarkDimension::execute() References2D.setValue(dvp); std::vector features = References3D.getValues(); - // Base::Console().Message("LD::execute - features: %d\n", features.size()); + // Base::Console().message("LD::execute - features: %d\n", features.size()); //if distance, required size = 2 //if angle, required size = 3; //not implemented yet unsigned int requiredSize = 2; @@ -127,7 +127,7 @@ App::DocumentObjectExecReturn *LandmarkDimension::execute() index++; } } - // Base::Console().Message("LD::execute - front: %s back: %s\n", + // Base::Console().message("LD::execute - front: %s back: %s\n", // DrawUtil::formatVector(points.front()).c_str(), // DrawUtil::formatVector(points.back()).c_str()); setLinearPoints(points.front(), points.back()); diff --git a/src/Mod/TechDraw/App/LineFormat.cpp b/src/Mod/TechDraw/App/LineFormat.cpp index 107ef127a8..f1fc7e9a7a 100644 --- a/src/Mod/TechDraw/App/LineFormat.cpp +++ b/src/Mod/TechDraw/App/LineFormat.cpp @@ -84,8 +84,8 @@ LineFormat::LineFormat(const int style, void LineFormat::dump(const char* title) { - Base::Console().Message("LF::dump - %s \n", title); - Base::Console().Message("LF::dump - %s \n", toString().c_str()); + Base::Console().message("LF::dump - %s \n", title); + Base::Console().message("LF::dump - %s \n", toString().c_str()); } std::string LineFormat::toString() const diff --git a/src/Mod/TechDraw/App/LineGenerator.cpp b/src/Mod/TechDraw/App/LineGenerator.cpp index e5a7bd0387..ca767c406b 100644 --- a/src/Mod/TechDraw/App/LineGenerator.cpp +++ b/src/Mod/TechDraw/App/LineGenerator.cpp @@ -90,7 +90,7 @@ QPen LineGenerator::getBestPen(size_t isoNumber, Qt::PenStyle qtStyle, double wi //! 1-15 and ANSI lines are 1-4(?) The line width is the nominal width in mm. QPen LineGenerator::getLinePen(size_t lineNumber, double nominalLineWidth) { -// Base::Console().Message("LG::getLinePen(%d, %.3f)\n", +// Base::Console().message("LG::getLinePen(%d, %.3f)\n", // lineNumber, nominalLineWidth); QPen linePen; linePen.setWidthF(nominalLineWidth); @@ -219,7 +219,7 @@ std::map LineGenerator::loadElements() Base::FileInfo fi(parmFile); Base::ifstream inFile(fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message( "Cannot open line element def file: %s\n", parmFile.c_str()); + Base::Console().message( "Cannot open line element def file: %s\n", parmFile.c_str()); return result; } std::string line; @@ -245,7 +245,7 @@ std::vector< std::vector > LineGenerator::getLineDefinitions() Base::FileInfo fi(Preferences::currentLineDefFile()); Base::ifstream inFile(fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message( "Cannot open line def file: %s\n", fi.filePath().c_str()); + Base::Console().message( "Cannot open line def file: %s\n", fi.filePath().c_str()); return lineDefs; } @@ -309,7 +309,7 @@ std::vector LineGenerator::getLineDescriptions() Base::FileInfo fi(Preferences::currentLineDefFile()); Base::ifstream inFile(fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message( "Cannot open line def file: %s\n", fi.filePath().c_str()); + Base::Console().message( "Cannot open line def file: %s\n", fi.filePath().c_str()); return lineDescs; } diff --git a/src/Mod/TechDraw/App/LineGroup.cpp b/src/Mod/TechDraw/App/LineGroup.cpp index 22f43147ad..ea2bded890 100644 --- a/src/Mod/TechDraw/App/LineGroup.cpp +++ b/src/Mod/TechDraw/App/LineGroup.cpp @@ -93,12 +93,12 @@ void LineGroup::setWeight(std::string s, double weight) void LineGroup::dump(const char* title) { - Base::Console().Message( "DUMP: %s\n", title); - Base::Console().Message( "Name: %s\n", m_name.c_str()); - Base::Console().Message( "Thin: %.3f\n", m_thin); - Base::Console().Message( "Graphic: %.3f\n", m_graphic); - Base::Console().Message( "Thick: %.3f\n", m_thick); - Base::Console().Message( "Extra: %.3f\n", m_extra); + Base::Console().message( "DUMP: %s\n", title); + Base::Console().message( "Name: %s\n", m_name.c_str()); + Base::Console().message( "Thin: %.3f\n", m_thin); + Base::Console().message( "Graphic: %.3f\n", m_graphic); + Base::Console().message( "Thick: %.3f\n", m_thick); + Base::Console().message( "Extra: %.3f\n", m_extra); } //static support function: split comma separated string of values into vector of numbers @@ -119,7 +119,7 @@ std::vector LineGroup::split(std::string line) result.push_back(std::stod(cell)); } catch (const std::invalid_argument& ia) { - Base::Console().Warning("Invalid number in cell: %s (%s) \n", cell.c_str(), ia.what()); + Base::Console().warning("Invalid number in cell: %s (%s) \n", cell.c_str(), ia.what()); result.push_back(0.0); } } @@ -133,7 +133,7 @@ std::string LineGroup::getRecordFromFile(std::string parmFile, int groupNumber) Base::FileInfo fi(parmFile); Base::ifstream inFile(fi, std::ifstream::in); if(!inFile.is_open()) { - Base::Console().Message( "Cannot open LineGroup file: %s\n", parmFile.c_str()); + Base::Console().message( "Cannot open LineGroup file: %s\n", parmFile.c_str()); return record; } // parse file to get the groupNumber'th line @@ -151,7 +151,7 @@ std::string LineGroup::getRecordFromFile(std::string parmFile, int groupNumber) } } //endwhile // nothing was found - Base::Console().Error("LineGroup: the LineGroup file has only %s entries but entry number %s is set\n" + Base::Console().error("LineGroup: the LineGroup file has only %s entries but entry number %s is set\n" , std::to_string(counter).c_str() , std::to_string(groupNumber).c_str()); return std::string(); // return an empty string @@ -168,7 +168,7 @@ LineGroup* LineGroup::lineGroupFactory(int groupNumber) std::vector values = LineGroup::split(lgRecord); if (values.size() < 4) { - Base::Console().Error( "LineGroup::invalid entry in %s\n", lgFileName.c_str() ); + Base::Console().error( "LineGroup::invalid entry in %s\n", lgFileName.c_str() ); } else { lg->setWeight("Thin", values[0]); lg->setWeight("Graphic", values[1]); @@ -204,7 +204,7 @@ std::string LineGroup::getGroupNamesFromFile(std::string FileName) Base::FileInfo fi(FileName); Base::ifstream inFile(fi, std::ifstream::in); if (!inFile.is_open()) { - Base::Console().Message("Cannot open LineGroup file: %s\n", FileName.c_str()); + Base::Console().message("Cannot open LineGroup file: %s\n", FileName.c_str()); return record; } // parse the file @@ -223,7 +223,7 @@ std::string LineGroup::getGroupNamesFromFile(std::string FileName) } } //endwhile if (record.empty()) { - Base::Console().Message("LineGroup error: no group found in file %s\n", FileName.c_str()); + Base::Console().message("LineGroup error: no group found in file %s\n", FileName.c_str()); } return record; } diff --git a/src/Mod/TechDraw/App/Preferences.cpp b/src/Mod/TechDraw/App/Preferences.cpp index 49299e5e58..f65a583042 100644 --- a/src/Mod/TechDraw/App/Preferences.cpp +++ b/src/Mod/TechDraw/App/Preferences.cpp @@ -203,7 +203,7 @@ QString Preferences::defaultTemplate() QString templateFileName = QString::fromStdString(prefFileName); Base::FileInfo fi(prefFileName); if (!fi.isReadable()) { - Base::Console().Warning("Template File: %s is not readable\n", prefFileName.c_str()); + Base::Console().warning("Template File: %s is not readable\n", prefFileName.c_str()); templateFileName = QString::fromStdString(defaultFileName); } return templateFileName; @@ -219,7 +219,7 @@ QString Preferences::defaultTemplateDir() QString templateDir = QString::fromStdString(prefTemplateDir); Base::FileInfo fi(prefTemplateDir); if (!fi.isReadable()) { - Base::Console().Warning("Template Directory: %s is not readable\n", + Base::Console().warning("Template Directory: %s is not readable\n", prefTemplateDir.c_str()); templateDir = QString::fromStdString(defaultDir); } @@ -236,7 +236,7 @@ std::string Preferences::lineGroupFile() } Base::FileInfo fi(lgFileName); if (!fi.isReadable()) { - Base::Console().Warning("Line Group File: %s is not readable\n", lgFileName.c_str()); + Base::Console().warning("Line Group File: %s is not readable\n", lgFileName.c_str()); lgFileName = defaultFileName; } return lgFileName; @@ -278,7 +278,7 @@ QString Preferences::defaultSymbolDir() QString symbolDir = QString::fromStdString(prefSymbolDir); Base::FileInfo fi(prefSymbolDir); if (!fi.isReadable()) { - Base::Console().Warning("Symbol Directory: %s is not readable\n", + Base::Console().warning("Symbol Directory: %s is not readable\n", prefSymbolDir.c_str()); symbolDir = QString::fromStdString(defaultDir); } @@ -295,7 +295,7 @@ std::string Preferences::svgFile() } Base::FileInfo fi(prefHatchFile); if (!fi.isReadable()) { - Base::Console().Warning("Svg Hatch File: %s is not readable\n", prefHatchFile.c_str()); + Base::Console().warning("Svg Hatch File: %s is not readable\n", prefHatchFile.c_str()); prefHatchFile = defaultFileName; } return prefHatchFile; @@ -311,7 +311,7 @@ std::string Preferences::patFile() } Base::FileInfo fi(prefHatchFile); if (!fi.isReadable()) { - Base::Console().Warning("Pat Hatch File: %s is not readable\n", prefHatchFile.c_str()); + Base::Console().warning("Pat Hatch File: %s is not readable\n", prefHatchFile.c_str()); prefHatchFile = defaultFileName; } @@ -328,7 +328,7 @@ std::string Preferences::bitmapFill() } Base::FileInfo fi(prefBitmapFile); if (!fi.isReadable()) { - Base::Console().Warning("Bitmap Fill File: %s is not readable\n", prefBitmapFile.c_str()); + Base::Console().warning("Bitmap Fill File: %s is not readable\n", prefBitmapFile.c_str()); prefBitmapFile = defaultFileName; } return prefBitmapFile; @@ -373,7 +373,7 @@ bool Preferences::monochrome() //! set monochrome display on/off void Preferences::monochrome(bool state) { - Base::Console().Message("Pref::useLightText - set to %d\n", state); + Base::Console().message("Pref::useLightText - set to %d\n", state); getPreferenceGroup("Colors")->SetBool("Monochrome", state); } @@ -465,7 +465,7 @@ int Preferences::lineStandard() // this message will appear many times if the parameter is invalid. int parameterValue = getPreferenceGroup("Standards")->GetInt("LineStandard", 1); if (parameterValue < 0) { - Base::Console().Warning(qPrintable(QApplication::translate( + Base::Console().warning(qPrintable(QApplication::translate( "Preferences", "The LineStandard parameter is invalid. Using zero instead.", nullptr))); return 0; } diff --git a/src/Mod/TechDraw/App/PropertyCenterLineList.cpp b/src/Mod/TechDraw/App/PropertyCenterLineList.cpp index e1e99217aa..94141bc5fa 100644 --- a/src/Mod/TechDraw/App/PropertyCenterLineList.cpp +++ b/src/Mod/TechDraw/App/PropertyCenterLineList.cpp @@ -157,7 +157,7 @@ void PropertyCenterLineList::Restore(Base::XMLReader &reader) newG->Restore(reader); if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().Error("CenterLine \"%s\" within a PropertyCenterLineList was subject to a partial restore.\n", reader.localName()); + Base::Console().error("CenterLine \"%s\" within a PropertyCenterLineList was subject to a partial restore.\n", reader.localName()); if(isOrderRelevant()) { // Pushes the best try by the CenterLine class values.push_back(newG); diff --git a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp index b264b6dd44..c02ef0f36e 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp +++ b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp @@ -67,7 +67,7 @@ int PropertyCosmeticEdgeList::getSize() const //_lValueList is not const. so why do we pass a const parameter? void PropertyCosmeticEdgeList::setValue(CosmeticEdge* lValue) { -// Base::Console().Message("PCEL::setValue() - current values: %d lValue: %s\n", _lValueList.size(), lValue ? "valid" : "null"); +// Base::Console().message("PCEL::setValue() - current values: %d lValue: %s\n", _lValueList.size(), lValue ? "valid" : "null"); if (lValue) { aboutToSetValue(); _lValueList.resize(1); @@ -78,7 +78,7 @@ void PropertyCosmeticEdgeList::setValue(CosmeticEdge* lValue) void PropertyCosmeticEdgeList::setValues(const std::vector& lValue) { -// Base::Console().Message("PCEL::seValues() - in values: %d current values: %d\n", lValue.size(), _lValueList.size()); +// Base::Console().message("PCEL::seValues() - in values: %d current values: %d\n", lValue.size(), _lValueList.size()); aboutToSetValue(); _lValueList.resize(lValue.size()); if (!lValue.empty()) { @@ -161,7 +161,7 @@ void PropertyCosmeticEdgeList::Restore(Base::XMLReader &reader) newG->Restore(reader); if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().Error("CosmeticEdge \"%s\" within a PropertyCosmeticEdgeList was subject to a partial restore.\n", reader.localName()); + Base::Console().error("CosmeticEdge \"%s\" within a PropertyCosmeticEdgeList was subject to a partial restore.\n", reader.localName()); if(isOrderRelevant()) { // Pushes the best try by the CosmeticEdge class values.push_back(newG); diff --git a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp index 451c0f3322..08d27e07c5 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp +++ b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp @@ -159,7 +159,7 @@ void PropertyCosmeticVertexList::Restore(Base::XMLReader &reader) newG->Restore(reader); if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().Error("CosmeticVertex \"%s\" within a PropertyCosmeticVertexList was subject to a partial restore.\n", reader.localName()); + Base::Console().error("CosmeticVertex \"%s\" within a PropertyCosmeticVertexList was subject to a partial restore.\n", reader.localName()); if(isOrderRelevant()) { // Pushes the best try by the CosmeticVertex class values.push_back(newG); diff --git a/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp b/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp index 76daf0a951..e7c6644fb2 100644 --- a/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp +++ b/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp @@ -171,7 +171,7 @@ void PropertyGeomFormatList::Restore(Base::XMLReader &reader) newG->Restore(reader); if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().Error("GeomFormat \"%s\" within a PropertyGeomFormatList was subject to a partial restore.\n", reader.localName()); + Base::Console().error("GeomFormat \"%s\" within a PropertyGeomFormatList was subject to a partial restore.\n", reader.localName()); if(isOrderRelevant()) { // Pushes the best try by the GeomFormat class values.push_back(newG); diff --git a/src/Mod/TechDraw/App/ShapeExtractor.cpp b/src/Mod/TechDraw/App/ShapeExtractor.cpp index 48f46dffff..c50f8d81cf 100644 --- a/src/Mod/TechDraw/App/ShapeExtractor.cpp +++ b/src/Mod/TechDraw/App/ShapeExtractor.cpp @@ -248,7 +248,7 @@ std::vector ShapeExtractor::getXShapes(const App::Link* xLink) } xSourceShapes.push_back(shape); } else { - Base::Console().Message("SE::getXShapes - no shape from getXShape\n"); + Base::Console().message("SE::getXShapes - no shape from getXShape\n"); } } } else { @@ -297,7 +297,7 @@ TopoDS_Shape ShapeExtractor::getShapeFromXLink(const App::Link* xLink) } } catch (...) { - Base::Console().Error("ShapeExtractor failed to retrieve shape from %s\n", xLink->getNameInDocument()); + Base::Console().error("ShapeExtractor failed to retrieve shape from %s\n", xLink->getNameInDocument()); return TopoDS_Shape(); } if (checkShape(linkedObject, ts.getShape())) { @@ -361,7 +361,7 @@ TopoDS_Shape ShapeExtractor::getShapesFused(const std::vectorgetNameInDocument()); return false; diff --git a/src/Mod/TechDraw/App/ShapeUtils.cpp b/src/Mod/TechDraw/App/ShapeUtils.cpp index c5586ab14f..e9ccc22472 100644 --- a/src/Mod/TechDraw/App/ShapeUtils.cpp +++ b/src/Mod/TechDraw/App/ShapeUtils.cpp @@ -83,7 +83,7 @@ using DU = DrawUtil; gp_Ax2 ShapeUtils::getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, const bool flip) { - // Base::Console().Message("GO::getViewAxis() - 1 - use only with getLegacyX\n"); + // Base::Console().message("GO::getViewAxis() - 1 - use only with getLegacyX\n"); (void)flip; gp_Ax2 viewAxis; gp_Pnt inputCenter(origin.x, origin.y, origin.z); @@ -113,7 +113,7 @@ gp_Ax2 ShapeUtils::getViewAxis(const Base::Vector3d origin, const Base::Vector3d gp_Ax2 ShapeUtils::getViewAxis(const Base::Vector3d origin, const Base::Vector3d& direction, const Base::Vector3d& xAxis, const bool flip) { - // Base::Console().Message("GO::getViewAxis() - 2\n"); + // Base::Console().message("GO::getViewAxis() - 2\n"); (void)flip; gp_Pnt inputCenter(origin.x, origin.y, origin.z); return gp_Ax2(inputCenter, @@ -126,7 +126,7 @@ gp_Ax2 ShapeUtils::getViewAxis(const Base::Vector3d origin, const Base::Vector3d gp_Ax2 ShapeUtils::legacyViewAxis1(const Base::Vector3d origin, const Base::Vector3d& direction, const bool flip) { - // Base::Console().Message("GO::legacyViewAxis1()\n"); + // Base::Console().message("GO::legacyViewAxis1()\n"); gp_Pnt inputCenter(origin.x, origin.y, origin.z); Base::Vector3d stdZ(0.0, 0.0, 1.0); Base::Vector3d stdOrg(0.0, 0.0, 0.0); @@ -180,7 +180,7 @@ gp_Pnt ShapeUtils::findCentroid(const TopoDS_Shape& shape) //! Returns the centroid of shape, as viewed according to direction gp_Pnt ShapeUtils::findCentroid(const TopoDS_Shape& shape, const Base::Vector3d& direction) { - // Base::Console().Message("GO::findCentroid() - 1\n"); + // Base::Console().message("GO::findCentroid() - 1\n"); Base::Vector3d origin(0.0, 0.0, 0.0); gp_Ax2 viewAxis = getViewAxis(origin, direction); return findCentroid(shape, viewAxis); @@ -189,7 +189,7 @@ gp_Pnt ShapeUtils::findCentroid(const TopoDS_Shape& shape, const Base::Vector3d& //! Returns the centroid of shape, as viewed according to direction gp_Pnt ShapeUtils::findCentroid(const TopoDS_Shape& shape, const gp_Ax2& viewAxis) { - // Base::Console().Message("GO::findCentroid() - 2\n"); + // Base::Console().message("GO::findCentroid() - 2\n"); gp_Trsf tempTransform; tempTransform.SetTransformation(viewAxis); @@ -212,14 +212,14 @@ gp_Pnt ShapeUtils::findCentroid(const TopoDS_Shape& shape, const gp_Ax2& viewAxi Base::Vector3d ShapeUtils::findCentroidVec(const TopoDS_Shape& shape, const Base::Vector3d& direction) { - // Base::Console().Message("GO::findCentroidVec() - 1\n"); + // Base::Console().message("GO::findCentroidVec() - 1\n"); gp_Pnt p = ShapeUtils::findCentroid(shape, direction); return Base::Vector3d(p.X(), p.Y(), p.Z()); } Base::Vector3d ShapeUtils::findCentroidVec(const TopoDS_Shape& shape, const gp_Ax2& cs) { - // Base::Console().Message("GO::findCentroidVec() - 2\n"); + // Base::Console().message("GO::findCentroidVec() - 2\n"); gp_Pnt p = ShapeUtils::findCentroid(shape, cs); return Base::Vector3d(p.X(), p.Y(), p.Z()); } diff --git a/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp b/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp index 8353303525..ec0172c29e 100644 --- a/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp +++ b/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp @@ -93,7 +93,7 @@ void loadTechDrawResource() QString fontFile = QString::fromStdString(fontDir + font); int rc = QFontDatabase::addApplicationFont(fontFile); if (rc < 0) { - Base::Console().Warning( + Base::Console().warning( "TechDraw failed to load font file: %d from: %s\n", rc, qPrintable(fontFile)); } } @@ -121,7 +121,7 @@ PyMOD_INIT_FUNC(TechDrawGui) } PyObject* mod = TechDrawGui::initModule(); - Base::Console().Log("Loading TechDrawGui module... done\n"); + Base::Console().log("Loading TechDrawGui module... done\n"); // instantiating the commands CreateTechDrawCommands(); diff --git a/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp b/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp index ff6e890d86..af59c2f0b3 100644 --- a/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp +++ b/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp @@ -92,7 +92,7 @@ private: str += " "; if (msg) {str += msg;} else {str += "No OCCT Exception Message";} - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } catch (const Base::Exception &e) { @@ -100,7 +100,7 @@ private: str += "FreeCAD exception thrown ("; str += e.what(); str += ")"; - e.ReportException(); + e.reportException(); throw Py::RuntimeError(str); } catch (const std::exception &e) { @@ -108,7 +108,7 @@ private: str += "C++ exception thrown ("; str += e.what(); str += ")"; - Base::Console().Error("%s\n", str.c_str()); + Base::Console().error("%s\n", str.c_str()); throw Py::RuntimeError(str); } return Py::None(); //only here to prevent warning re no return value diff --git a/src/Mod/TechDraw/Gui/Command.cpp b/src/Mod/TechDraw/Gui/Command.cpp index fe54d0df88..507df68de5 100644 --- a/src/Mod/TechDraw/Gui/Command.cpp +++ b/src/Mod/TechDraw/Gui/Command.cpp @@ -731,7 +731,7 @@ CmdTechDrawSectionGroup::CmdTechDrawSectionGroup() : Command("TechDraw_SectionGr void CmdTechDrawSectionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::SectionGrp - activated(%d)\n", iMsg); + // Base::Console().message("CMD::SectionGrp - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -749,7 +749,7 @@ void CmdTechDrawSectionGroup::activated(int iMsg) execComplexSection(this); break; default: - Base::Console().Message("CMD::SectionGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::SectionGrp - invalid iMsg: %d\n", iMsg); }; } diff --git a/src/Mod/TechDraw/Gui/CommandAnnotate.cpp b/src/Mod/TechDraw/Gui/CommandAnnotate.cpp index ff85579ace..0e9b173265 100644 --- a/src/Mod/TechDraw/Gui/CommandAnnotate.cpp +++ b/src/Mod/TechDraw/Gui/CommandAnnotate.cpp @@ -212,7 +212,7 @@ CmdTechDrawCosmeticVertexGroup::CmdTechDrawCosmeticVertexGroup() void CmdTechDrawCosmeticVertexGroup::activated(int iMsg) { -// Base::Console().Message("CMD::CosmeticVertexGroup - activated(%d)\n", iMsg); +// Base::Console().message("CMD::CosmeticVertexGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -233,7 +233,7 @@ void CmdTechDrawCosmeticVertexGroup::activated(int iMsg) execQuadrants(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; updateActive(); Gui::Selection().clearSelection(); @@ -305,7 +305,7 @@ bool CmdTechDrawCosmeticVertexGroup::isActive() void execCosmeticVertex(Gui::Command* cmd) { -// Base::Console().Message("execCosmeticVertex()\n"); +// Base::Console().message("execCosmeticVertex()\n"); TechDraw::DrawPage* page = DrawGuiUtil::findPage(cmd); if (!page) { return; @@ -329,7 +329,7 @@ void execCosmeticVertex(Gui::Command* cmd) void execMidpoints(Gui::Command* cmd) { -// Base::Console().Message("execMidpoints()\n"); +// Base::Console().message("execMidpoints()\n"); TechDraw::DrawViewPart * dvp = nullptr; std::vector selectedEdges = CommandHelpers::getSelectedSubElements(cmd, dvp, "Edge"); @@ -356,7 +356,7 @@ void execMidpoints(Gui::Command* cmd) void execQuadrants(Gui::Command* cmd) { -// Base::Console().Message("execQuadrants()\n"); +// Base::Console().message("execQuadrants()\n"); TechDraw::DrawViewPart* dvp = nullptr; std::vector selectedEdges = CommandHelpers::getSelectedSubElements(cmd, dvp, "Edge"); @@ -423,7 +423,7 @@ void CmdTechDrawCosmeticVertex::activated(int iMsg) TechDraw::DrawViewPart* baseFeat = nullptr; baseFeat = dynamic_cast((*shapes.begin())); if (!baseFeat) { - Base::Console().Message("CMD::CosmeticVertex - 1st shape is not DVP. WTF?\n"); + Base::Console().message("CMD::CosmeticVertex - 1st shape is not DVP. WTF?\n"); return; } @@ -588,7 +588,7 @@ CmdTechDrawCenterLineGroup::CmdTechDrawCenterLineGroup() void CmdTechDrawCenterLineGroup::activated(int iMsg) { -// Base::Console().Message("CMD::CenterLineGroup - activated(%d)\n", iMsg); +// Base::Console().message("CMD::CenterLineGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -609,7 +609,7 @@ void CmdTechDrawCenterLineGroup::activated(int iMsg) exec2PointCenterLine(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1348,18 +1348,18 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) } else if (source == SourceType::CENTERLINE) { cl2Delete.push_back(tag); } else { - Base::Console().Message( + Base::Console().message( "CMD::CosmeticEraser - edge: %d is confused - source: %d\n", idx, static_cast(source)); } } } else if (geomType == "Vertex") { TechDraw::VertexPtr tdv = objFeat->getProjVertexByIndex(idx); if (!tdv) - Base::Console().Message("CMD::eraser - geom: %d not found!\n", idx); + Base::Console().message("CMD::eraser - geom: %d not found!\n", idx); std::string delTag = tdv->getCosmeticTag(); if (delTag.empty()) - Base::Console().Warning("Vertex%d is not cosmetic! Can not erase.\n", idx); + Base::Console().warning("Vertex%d is not cosmetic! Can not erase.\n", idx); cv2Delete.push_back(delTag); } else { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), diff --git a/src/Mod/TechDraw/Gui/CommandCreateDims.cpp b/src/Mod/TechDraw/Gui/CommandCreateDims.cpp index f41011cfd3..f86bbe92cb 100644 --- a/src/Mod/TechDraw/Gui/CommandCreateDims.cpp +++ b/src/Mod/TechDraw/Gui/CommandCreateDims.cpp @@ -427,7 +427,7 @@ public: void mouseReleaseEvent(QMouseEvent* event) override { - // Base::Console().Warning("mouseReleaseEvent TH\n"); + // Base::Console().warning("mouseReleaseEvent TH\n"); if (event->button() == Qt::RightButton) { if (!dims.empty()) { Gui::Selection().clearSelection(); @@ -446,7 +446,7 @@ public: if (removedRef.hasGeometry()) { finalize = false; - //Base::Console().Warning("RmvSelection \n"); + //Base::Console().warning("RmvSelection \n"); // Remove the reference from the vector ReferenceVector& selVector = getSelectionVector(removedRef); selVector.erase(std::remove(selVector.begin(), selVector.end(), removedRef), selVector.end()); @@ -463,7 +463,7 @@ public: if (addedRef.hasGeometry()) { finalize = false; - //Base::Console().Warning("AddSelection\n"); + //Base::Console().warning("AddSelection\n"); //add the geometry to its type vector. Temporarily if not selAllowed if (addedRef.getSubName() == "") { // Behavior deactivated for now because I found it annoying. @@ -510,7 +510,7 @@ public: void onSelectionChanged(const Gui::SelectionChanges& msg) override { - //Base::Console().Warning("onSelectionChanged %d - --%s--\n", (int)msg.Type, msg.pSubName); + //Base::Console().warning("onSelectionChanged %d - --%s--\n", (int)msg.Type, msg.pSubName); if (msg.Type == Gui::SelectionChanges::ClrSelection) { //clearAndRestartCommand(); @@ -526,13 +526,13 @@ public: } /*if (msg.Type == Gui::SelectionChanges::SetPreselect) { - Base::Console().Warning("SetPreselect\n"); + Base::Console().warning("SetPreselect\n"); std::string geomName = DrawUtil::getGeomTypeFromName(msg.pSubName); edgeOrPointPreselected = geomName == "Edge" || geomName == "Vertex"; return; } else if (msg.Type == Gui::SelectionChanges::RmvPreselect) { - Base::Console().Warning("RmvPreselect\n"); + Base::Console().warning("RmvPreselect\n"); edgeOrPointPreselected = false; return; }*/ @@ -633,7 +633,7 @@ protected: void finalizeCommand() { - //Base::Console().Warning("finalizeCommand \n"); + //Base::Console().warning("finalizeCommand \n"); finishDimensionMove(); @@ -752,7 +752,7 @@ protected: bool makeAppropriateDimension() { bool selAllowed = false; - //Base::Console().Warning("makeAppropriateDimension %d %d %d %d %d %d\n", selPoints.size(), selLine.size(), selCircleArc.size(), selEllipseArc.size(), selSplineAndCo.size(), selFaces.size()); + //Base::Console().warning("makeAppropriateDimension %d %d %d %d %d %d\n", selPoints.size(), selLine.size(), selCircleArc.size(), selEllipseArc.size(), selSplineAndCo.size(), selFaces.size()); GeomSelectionSizes selection(selPoints.size(), selLine.size(), selCircleArc.size(), selEllipseArc.size(), selSplineAndCo.size(), selFaces.size()); if (selection.hasFaces()) { @@ -1971,7 +1971,7 @@ CmdTechDrawExtentGroup::CmdTechDrawExtentGroup() void CmdTechDrawExtentGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtentGrp - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtentGrp - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), @@ -1990,7 +1990,7 @@ void CmdTechDrawExtentGroup::activated(int iMsg) execExtent(this, "DistanceY"); break; default: - Base::Console().Message("CMD::ExtGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::ExtGrp - invalid iMsg: %d\n", iMsg); }; } diff --git a/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp b/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp index 97c7ed3439..5c6b4299ea 100644 --- a/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp +++ b/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp @@ -323,7 +323,7 @@ CmdTechDrawExtensionInsertPrefixGroup::CmdTechDrawExtensionInsertPrefixGroup() void CmdTechDrawExtensionInsertPrefixGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -347,7 +347,7 @@ void CmdTechDrawExtensionInsertPrefixGroup::activated(int iMsg) execRemovePrefixChar(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -546,7 +546,7 @@ CmdTechDrawExtensionIncreaseDecreaseGroup::CmdTechDrawExtensionIncreaseDecreaseG void CmdTechDrawExtensionIncreaseDecreaseGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -564,7 +564,7 @@ void CmdTechDrawExtensionIncreaseDecreaseGroup::activated(int iMsg) execIncreaseDecreaseDecimal(this, -1); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -806,7 +806,7 @@ void CmdTechDrawExtensionPosObliqueChainDimension::activated(int iMsg) { Q_UNUSED(iMsg); execPosObliqueChainDimension(this); - ///Base::Console().Message("TechDraw_ExtensionPosObliqueChainDimension started\n"); + ///Base::Console().message("TechDraw_ExtensionPosObliqueChainDimension started\n"); } bool CmdTechDrawExtensionPosObliqueChainDimension::isActive() @@ -838,7 +838,7 @@ CmdTechDrawExtensionPosChainDimensionGroup::CmdTechDrawExtensionPosChainDimensio void CmdTechDrawExtensionPosChainDimensionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionPosChainDimensionGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionPosChainDimensionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -859,7 +859,7 @@ void CmdTechDrawExtensionPosChainDimensionGroup::activated(int iMsg) execPosObliqueChainDimension(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1133,7 +1133,7 @@ void CmdTechDrawExtensionCascadeObliqueDimension::activated(int iMsg) { Q_UNUSED(iMsg); execCascadeObliqueDimension(this); - ///Base::Console().Message("TechDraw_ExtensionPosObliqueChainDimension started\n"); + ///Base::Console().message("TechDraw_ExtensionPosObliqueChainDimension started\n"); } bool CmdTechDrawExtensionCascadeObliqueDimension::isActive() @@ -1166,7 +1166,7 @@ CmdTechDrawExtensionCascadeDimensionGroup::CmdTechDrawExtensionCascadeDimensionG void CmdTechDrawExtensionCascadeDimensionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1187,7 +1187,7 @@ void CmdTechDrawExtensionCascadeDimensionGroup::activated(int iMsg) execCascadeObliqueDimension(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1542,7 +1542,7 @@ CmdTechDrawExtensionCreateChainDimensionGroup::CmdTechDrawExtensionCreateChainDi void CmdTechDrawExtensionCreateChainDimensionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1563,7 +1563,7 @@ void CmdTechDrawExtensionCreateChainDimensionGroup::activated(int iMsg) execCreateObliqueChainDimension(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1935,7 +1935,7 @@ CmdTechDrawExtensionCreateCoordDimensionGroup::CmdTechDrawExtensionCreateCoordDi void CmdTechDrawExtensionCreateCoordDimensionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1956,7 +1956,7 @@ void CmdTechDrawExtensionCreateCoordDimensionGroup::activated(int iMsg) execCreateObliqueCoordDimension(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -2192,7 +2192,7 @@ CmdTechDrawExtensionChamferDimensionGroup::CmdTechDrawExtensionChamferDimensionG void CmdTechDrawExtensionChamferDimensionGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -2210,7 +2210,7 @@ void CmdTechDrawExtensionChamferDimensionGroup::activated(int iMsg) execCreateVertChamferDimension(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } diff --git a/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp b/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp index cd78167175..01e6446265 100644 --- a/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp +++ b/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp @@ -183,7 +183,7 @@ void CmdTechDrawExtensionHoleCircle::activated(int iMsg) { Q_UNUSED(iMsg); execHoleCircle(this); - //Base::Console().Message("HoleCircle started\n"); + //Base::Console().message("HoleCircle started\n"); } bool CmdTechDrawExtensionHoleCircle::isActive() @@ -307,7 +307,7 @@ void CmdTechDrawExtensionCircleCenterLinesGroup::activated(int iMsg) execHoleCircle(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -612,7 +612,7 @@ CmdTechDrawExtensionThreadsGroup::CmdTechDrawExtensionThreadsGroup() void CmdTechDrawExtensionThreadsGroup::activated(int iMsg) { - // Base::Console().Message("CMD::TechDrawExtensionThreadsGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::TechDrawExtensionThreadsGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -636,7 +636,7 @@ void CmdTechDrawExtensionThreadsGroup::activated(int iMsg) execThreadBoltBottom(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -851,7 +851,7 @@ CmdTechDrawExtensionVertexAtIntersection::CmdTechDrawExtensionVertexAtIntersecti void CmdTechDrawExtensionVertexAtIntersection::activated(int iMsg) { Q_UNUSED(iMsg); - //Base::Console().Message("VertexAtIntersection started\n"); + //Base::Console().message("VertexAtIntersection started\n"); std::vector selection; TechDraw::DrawViewPart* objFeat{nullptr}; if (!_checkSel(this, selection, objFeat, QT_TRANSLATE_NOOP("Command","TechDraw Cosmetic Intersection Vertex(es)"))) { @@ -953,7 +953,7 @@ CmdTechDrawExtensionDrawCosmArc::CmdTechDrawExtensionDrawCosmArc() void CmdTechDrawExtensionDrawCosmArc::activated(int iMsg) { Q_UNUSED(iMsg); - //Base::Console().Message("Cosmetic Arc started\n"); + //Base::Console().message("Cosmetic Arc started\n"); execDrawCosmArc(this); } @@ -1016,7 +1016,7 @@ CmdTechDrawExtensionDrawCosmCircle::CmdTechDrawExtensionDrawCosmCircle() void CmdTechDrawExtensionDrawCosmCircle::activated(int iMsg) { Q_UNUSED(iMsg); - //Base::Console().Message("Cosmetic Circle started\n"); + //Base::Console().message("Cosmetic Circle started\n"); execDrawCosmCircle(this); } @@ -1081,7 +1081,7 @@ CmdTechDrawExtensionDrawCosmCircle3Points::CmdTechDrawExtensionDrawCosmCircle3Po void CmdTechDrawExtensionDrawCosmCircle3Points::activated(int iMsg) { Q_UNUSED(iMsg); - //Base::Console().Message("Cosmetic Circle 3 Points started\n"); + //Base::Console().message("Cosmetic Circle 3 Points started\n"); execDrawCosmCircle3Points(this); } @@ -1115,7 +1115,7 @@ CmdTechDrawExtensionDrawCirclesGroup::CmdTechDrawExtensionDrawCirclesGroup() void CmdTechDrawExtensionDrawCirclesGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionDrawCirclesGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionDrawCirclesGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1136,7 +1136,7 @@ void CmdTechDrawExtensionDrawCirclesGroup::activated(int iMsg) execDrawCosmCircle3Points(this); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1364,7 +1364,7 @@ CmdTechDrawExtensionLinePPGroup::CmdTechDrawExtensionLinePPGroup() void CmdTechDrawExtensionLinePPGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1382,7 +1382,7 @@ void CmdTechDrawExtensionLinePPGroup::activated(int iMsg) execLineParallelPerpendicular(this, false); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } @@ -1603,7 +1603,7 @@ void CmdTechDrawExtensionExtendLine::activated(int iMsg) { Q_UNUSED(iMsg); execExtendShortenLine(this, true); - ///Base::Console().Message("ExtendLine started\n"); + ///Base::Console().message("ExtendLine started\n"); } bool CmdTechDrawExtensionExtendLine::isActive() @@ -1638,7 +1638,7 @@ void CmdTechDrawExtensionShortenLine::activated(int iMsg) { Q_UNUSED(iMsg); execExtendShortenLine(this, false); - ///Base::Console().Message("ShortenLine started\n"); + ///Base::Console().message("ShortenLine started\n"); } bool CmdTechDrawExtensionShortenLine::isActive() @@ -1670,7 +1670,7 @@ CmdTechDrawExtendShortenLineGroup::CmdTechDrawExtendShortenLineGroup() void CmdTechDrawExtendShortenLineGroup::activated(int iMsg) { - // Base::Console().Message("CMD::ExtendShortenLineGroup - activated(%d)\n", iMsg); + // Base::Console().message("CMD::ExtendShortenLineGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), @@ -1688,7 +1688,7 @@ void CmdTechDrawExtendShortenLineGroup::activated(int iMsg) execExtendShortenLine(this, false); break; default: - Base::Console().Message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); + Base::Console().message("CMD::CVGrp - invalid iMsg: %d\n", iMsg); }; } diff --git a/src/Mod/TechDraw/Gui/CommandStack.cpp b/src/Mod/TechDraw/Gui/CommandStack.cpp index 31b3c0b6e7..c6a9f50e9a 100644 --- a/src/Mod/TechDraw/Gui/CommandStack.cpp +++ b/src/Mod/TechDraw/Gui/CommandStack.cpp @@ -93,7 +93,7 @@ void CmdTechDrawStackGroup::activated(int iMsg) execStackDown(this); break; default: - Base::Console().Message("CMD::StackGrp - invalid iMsg: %d\n",iMsg); + Base::Console().message("CMD::StackGrp - invalid iMsg: %d\n",iMsg); }; } diff --git a/src/Mod/TechDraw/Gui/DimensionValidators.cpp b/src/Mod/TechDraw/Gui/DimensionValidators.cpp index ab3f776c7b..3fcc6a4641 100644 --- a/src/Mod/TechDraw/Gui/DimensionValidators.cpp +++ b/src/Mod/TechDraw/Gui/DimensionValidators.cpp @@ -491,7 +491,7 @@ DimensionGeometry TechDraw::isValidSingleFace3d(DrawViewPart* dvp, const Referen TopoDS_Shape refShape = ref.getGeometry(); if (refShape.IsNull() || refShape.ShapeType() != TopAbs_FACE) { - Base::Console().Warning("Geometry for reference is not a face.\n"); + Base::Console().warning("Geometry for reference is not a face.\n"); return DimensionGeometry::isInvalid; } diff --git a/src/Mod/TechDraw/Gui/DlgPageChooser.cpp b/src/Mod/TechDraw/Gui/DlgPageChooser.cpp index 0480a86ab9..60a2918b7e 100644 --- a/src/Mod/TechDraw/Gui/DlgPageChooser.cpp +++ b/src/Mod/TechDraw/Gui/DlgPageChooser.cpp @@ -103,7 +103,7 @@ std::string DlgPageChooser::getSelection() const void DlgPageChooser::accept() { if (ui->lwPages->selectedItems().empty()) { - Base::Console().Message("Page Chooser: no page was selected\n"); + Base::Console().message("Page Chooser: no page was selected\n"); } QDialog::accept(); } diff --git a/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp b/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp index 2de7bfa48a..7d9b4dc759 100644 --- a/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp +++ b/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp @@ -219,7 +219,7 @@ void DrawGuiUtil::loadLineGroupChoices(QComboBox* combo) QIcon DrawGuiUtil::iconForLine(size_t lineNumber, TechDraw::LineGenerator* generator) { - // Base::Console().Message("DGU::iconForLine(lineNumber: %d)\n", lineNumber); + // Base::Console().message("DGU::iconForLine(lineNumber: %d)\n", lineNumber); constexpr int iconSize {64}; constexpr int borderSize {4}; constexpr double iconLineWeight {1.0}; @@ -443,7 +443,7 @@ bool DrawGuiUtil::isDraftObject(App::DocumentObject* obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); result = false; } } @@ -474,7 +474,7 @@ bool DrawGuiUtil::isArchObject(App::DocumentObject* obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); result = false; } } @@ -505,7 +505,7 @@ bool DrawGuiUtil::isArchSection(App::DocumentObject* obj) } catch (Py::Exception&) { Base::PyException e; // extract the Python error text - e.ReportException(); + e.reportException(); result = false; } } @@ -565,24 +565,24 @@ bool DrawGuiUtil::needView(Gui::Command* cmd, bool partOnly) void DrawGuiUtil::dumpRectF(const char* text, const QRectF& r) { - Base::Console().Message("DUMP - dumpRectF - %s\n", text); + Base::Console().message("DUMP - dumpRectF - %s\n", text); double left = r.left(); double right = r.right(); double top = r.top(); double bottom = r.bottom(); - Base::Console().Message("Extents: L: %.3f, R: %.3f, T: %.3f, B: %.3f\n", + Base::Console().message("Extents: L: %.3f, R: %.3f, T: %.3f, B: %.3f\n", left, right, top, bottom); - Base::Console().Message("Size: W: %.3f H: %.3f\n", r.width(), r.height()); - Base::Console().Message("Centre: (%.3f, %.3f)\n", r.center().x(), r.center().y()); + Base::Console().message("Size: W: %.3f H: %.3f\n", r.width(), r.height()); + Base::Console().message("Centre: (%.3f, %.3f)\n", r.center().x(), r.center().y()); } void DrawGuiUtil::dumpPointF(const char* text, const QPointF& p) { - Base::Console().Message("DUMP - dumpPointF - %s\n", text); - Base::Console().Message("Point: (%.3f, %.3f)\n", p.x(), p.y()); + Base::Console().message("DUMP - dumpPointF - %s\n", text); + Base::Console().message("Point: (%.3f, %.3f)\n", p.x(), p.y()); } std::pair DrawGuiUtil::get3DDirAndRot() @@ -647,7 +647,7 @@ std::pair DrawGuiUtil::getProjDirFromFace(App::D auto ts = Part::Feature::getShape(obj, faceName.c_str(), true); if (ts.IsNull() || ts.ShapeType() != TopAbs_FACE) { - Base::Console().Warning("getProjDirFromFace(%s) is not a Face\n", faceName.c_str()); + Base::Console().warning("getProjDirFromFace(%s) is not a Face\n", faceName.c_str()); return dirs; } @@ -813,7 +813,7 @@ void DrawGuiUtil::rotateToAlign(const QGIVertex* p1, const QGIVertex* p2, const { QGIViewPart* view = static_cast(p1->parentItem()); if(view != static_cast(p2->parentItem())) { - Base::Console().Error("Vertexes have to be from the same view!"); + Base::Console().error("Vertexes have to be from the same view!"); } Base::Vector2d oldDirection = p2->vector2dBetweenPoints(p1); diff --git a/src/Mod/TechDraw/Gui/Grabber3d.cpp b/src/Mod/TechDraw/Gui/Grabber3d.cpp index d370c70bfb..f63a4095f8 100644 --- a/src/Mod/TechDraw/Gui/Grabber3d.cpp +++ b/src/Mod/TechDraw/Gui/Grabber3d.cpp @@ -37,22 +37,22 @@ void Grabber3d::quickView(View3DInventor* view3d, const QColor bgColor, QImage &image) { -// Base::Console().Message("G3d::quickView()); +// Base::Console().message("G3d::quickView()); if (!Gui::getMainWindow()) { //this should already be checked in the caller - Base::Console().Warning("G3d::quickView - no Main Window - returning\n"); + Base::Console().warning("G3d::quickView - no Main Window - returning\n"); return; } if (!view3d) { //this should also already be checked in the caller - Base::Console().Warning("G3d::quickView - no 3D view for ActiveView - returning\n"); + Base::Console().warning("G3d::quickView - no 3D view for ActiveView - returning\n"); return; } View3DInventorViewer* viewer = view3d->getViewer(); if (!viewer) { - Base::Console().Warning("G3d::quickView - could not create viewer - returning\n"); + Base::Console().warning("G3d::quickView - could not create viewer - returning\n"); return; } diff --git a/src/Mod/TechDraw/Gui/MDIViewPage.cpp b/src/Mod/TechDraw/Gui/MDIViewPage.cpp index 9fc4e8593e..9344c82ee0 100644 --- a/src/Mod/TechDraw/Gui/MDIViewPage.cpp +++ b/src/Mod/TechDraw/Gui/MDIViewPage.cpp @@ -143,7 +143,7 @@ void MDIViewPage::setDocumentName(const std::string& name) { m_documentName = na void MDIViewPage::closeEvent(QCloseEvent* event) { - // Base::Console().Message("MDIVP::closeEvent()\n"); + // Base::Console().message("MDIVP::closeEvent()\n"); MDIView::closeEvent(event); if (!event->isAccepted()) { return; @@ -432,7 +432,7 @@ PyObject* MDIViewPage::getPyObject() void MDIViewPage::contextMenuEvent(QContextMenuEvent* event) { - // Base::Console().Message("MDIVP::contextMenuEvent() - reason: %d\n", event->reason()); + // Base::Console().message("MDIVP::contextMenuEvent() - reason: %d\n", event->reason()); if (isContextualMenuEnabled) { QMenu menu; menu.addAction(m_toggleFrameAction); diff --git a/src/Mod/TechDraw/Gui/PATPathMaker.cpp b/src/Mod/TechDraw/Gui/PATPathMaker.cpp index 076d297492..b17c949734 100644 --- a/src/Mod/TechDraw/Gui/PATPathMaker.cpp +++ b/src/Mod/TechDraw/Gui/PATPathMaker.cpp @@ -64,7 +64,7 @@ void PATPathMaker::lineSetToFillItems(LineSet& ls) m_fillItems.push_back(fillItem); if (m_segCount > m_maxSeg) { - Base::Console().Warning("PAT segment count exceeded: %ld\n", m_segCount); + Base::Console().warning("PAT segment count exceeded: %ld\n", m_segCount); break; } } @@ -155,7 +155,7 @@ QPainterPath PATPathMaker::dashedPPath(const std::vector dashPattern, co while (travel < lineLength) { bool stop = false; if (m_segCount > 10000) { - Base::Console().Warning("PAT segment count exceeded: %ld\n", m_segCount); + Base::Console().warning("PAT segment count exceeded: %ld\n", m_segCount); break; } diff --git a/src/Mod/TechDraw/Gui/PagePrinter.cpp b/src/Mod/TechDraw/Gui/PagePrinter.cpp index 024cdee61e..a2efc27f11 100644 --- a/src/Mod/TechDraw/Gui/PagePrinter.cpp +++ b/src/Mod/TechDraw/Gui/PagePrinter.cpp @@ -343,7 +343,7 @@ void PagePrinter::print(ViewProviderPage* vpPage, QPrinter* printer) void PagePrinter::printPdf(ViewProviderPage* vpPage, const std::string& file) { if (file.empty()) { - Base::Console().Warning("PagePrinter - no file specified\n"); + Base::Console().warning("PagePrinter - no file specified\n"); return; } @@ -398,7 +398,7 @@ void PagePrinter::printPdf(ViewProviderPage* vpPage, const std::string& file) void PagePrinter::saveSVG(ViewProviderPage* vpPage, const std::string& file) { if (file.empty()) { - Base::Console().Warning("PagePrinter - no file specified\n"); + Base::Console().warning("PagePrinter - no file specified\n"); return; } auto filespec = Base::Tools::escapeEncodeFilename(file); diff --git a/src/Mod/TechDraw/Gui/PathBuilder.cpp b/src/Mod/TechDraw/Gui/PathBuilder.cpp index 11e26758b3..44c2f202c5 100644 --- a/src/Mod/TechDraw/Gui/PathBuilder.cpp +++ b/src/Mod/TechDraw/Gui/PathBuilder.cpp @@ -123,7 +123,7 @@ QPainterPath PathBuilder::geomToPainterPath(BaseGeomPtr baseGeom, double rot) co Rez::guiX(geom->pnts[0].x), Rez::guiX(geom->pnts[0].y)); } else {//can only handle lines, quads, cubes - Base::Console().Error("Bad pole count (%d) for BezierSegment\n", geom->poles); + Base::Console().error("Bad pole count (%d) for BezierSegment\n", geom->poles); auto itBez = geom->pnts.begin() + 1; for (; itBez != geom->pnts.end(); itBez++) { path.lineTo(Rez::guiX((*itBez).x), @@ -149,7 +149,7 @@ QPainterPath PathBuilder::geomToPainterPath(BaseGeomPtr baseGeom, double rot) co Rez::guiX(geom->pnts[3].x), Rez::guiX(geom->pnts[3].y)); } else {//can only handle lines, quads, cubes - Base::Console().Error("Bad pole count (%d) for BezierSegment\n", geom->poles); + Base::Console().error("Bad pole count (%d) for BezierSegment\n", geom->poles); auto itBez = geom->pnts.begin() + 1; for (; itBez != geom->pnts.end(); itBez++) { path.lineTo(Rez::guiX((*itBez).x), @@ -184,7 +184,7 @@ QPainterPath PathBuilder::geomToPainterPath(BaseGeomPtr baseGeom, double rot) co Rez::guiX(it->pnts[0].x), Rez::guiX(it->pnts[0].y)); } else {//can only handle lines, quads, cubes - Base::Console().Error( + Base::Console().error( "Bad pole count (%d) for BezierSegment of B-spline geometry\n", it->poles); path.lineTo(it->pnts[1].x, it->pnts[1].y);//show something for debugging @@ -213,7 +213,7 @@ QPainterPath PathBuilder::geomToPainterPath(BaseGeomPtr baseGeom, double rot) co Rez::guiX(it->pnts[3].x), Rez::guiX(it->pnts[3].y)); } else { - Base::Console().Error( + Base::Console().error( "Bad pole count (%d) for BezierSegment of B-spline geometry\n", it->poles); path.lineTo(it->pnts[1].x, it->pnts[1].y);//show something for debugging @@ -242,7 +242,7 @@ QPainterPath PathBuilder::geomToPainterPath(BaseGeomPtr baseGeom, double rot) co } } break; default: { - Base::Console().Error("Error - geomToPainterPath - UNKNOWN geomType: %d\n", + Base::Console().error("Error - geomToPainterPath - UNKNOWN geomType: %d\n", static_cast(baseGeom->getGeomType())); } break; }//sb end of switch diff --git a/src/Mod/TechDraw/Gui/PreferencesGui.cpp b/src/Mod/TechDraw/Gui/PreferencesGui.cpp index 2fd2ac9c0f..77080c40ca 100644 --- a/src/Mod/TechDraw/Gui/PreferencesGui.cpp +++ b/src/Mod/TechDraw/Gui/PreferencesGui.cpp @@ -185,7 +185,7 @@ QString PreferencesGui::weldingDirectory() QString qSymbolDir = QString::fromUtf8(symbolDir.c_str()); Base::FileInfo fi(symbolDir); if (!fi.isReadable()) { - Base::Console().Warning("Welding Directory: %s is not readable\n", symbolDir.c_str()); + Base::Console().warning("Welding Directory: %s is not readable\n", symbolDir.c_str()); qSymbolDir = QString::fromUtf8(defaultDir.c_str()); } return qSymbolDir; diff --git a/src/Mod/TechDraw/Gui/QGCustomText.cpp b/src/Mod/TechDraw/Gui/QGCustomText.cpp index 016c4db2cf..b40693a2e2 100644 --- a/src/Mod/TechDraw/Gui/QGCustomText.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomText.cpp @@ -114,7 +114,7 @@ double QGCustomText::getWidth() } QVariant QGCustomText::itemChange(GraphicsItemChange change, const QVariant &value) { -// Base::Console().Message("QGCT::itemChange - this: %X change: %d\n", this, change); +// Base::Console().message("QGCT::itemChange - this: %X change: %d\n", this, change); if (change == ItemSelectedHasChanged && scene()) { if(isSelected()) { setPrettySel(); diff --git a/src/Mod/TechDraw/Gui/QGEPath.cpp b/src/Mod/TechDraw/Gui/QGEPath.cpp index 26aa18299e..5c89dea90e 100644 --- a/src/Mod/TechDraw/Gui/QGEPath.cpp +++ b/src/Mod/TechDraw/Gui/QGEPath.cpp @@ -52,13 +52,13 @@ using DGU = DrawGuiUtil; QGMarker::QGMarker(int idx) : QGIVertex(idx), m_dragging(false) { -// Base::Console().Message("QGMarker::QGMarker(%d)\n", idx); +// Base::Console().message("QGMarker::QGMarker(%d)\n", idx); setFlag(QGraphicsItem::ItemIsMovable, true); } void QGMarker::mousePressEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGMarker::mousePressEvent() - focustype: %d\n", +// Base::Console().message("QGMarker::mousePressEvent() - focustype: %d\n", // scene()->focusItem()->type() - QGraphicsItem::UserType); if (event->button() == Qt::RightButton) { //we're done @@ -97,7 +97,7 @@ void QGMarker::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) void QGMarker::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGMarker::mouseDoubleClickEvent(%d)\n", getProjIndex()); +// Base::Console().message("QGMarker::mouseDoubleClickEvent(%d)\n", getProjIndex()); if (event->button() == Qt::RightButton) { //we're done // we are finished our edit session Q_EMIT endEdit(); @@ -109,7 +109,7 @@ void QGMarker::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event) void QGMarker::keyPressEvent(QKeyEvent * event) { -// Base::Console().Message("QGMarker::keyPressEvent(%d)\n", getProjIndex()); +// Base::Console().message("QGMarker::keyPressEvent(%d)\n", getProjIndex()); if (event->key() == Qt::Key_Escape) { m_dragging = false; Q_EMIT endEdit(); @@ -160,7 +160,7 @@ QGEPath::QGEPath() : QVariant QGEPath::itemChange(GraphicsItemChange change, const QVariant &value) { -// Base::Console().Message("QGEP::itemChange(%d) - type: %d\n", change, type() - QGraphicsItem::UserType); +// Base::Console().message("QGEP::itemChange(%d) - type: %d\n", change, type() - QGraphicsItem::UserType); if (change == ItemSelectedHasChanged && scene()) { if(isSelected()) { Q_EMIT selected(true); @@ -205,7 +205,7 @@ void QGEPath::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) //! this begins an edit session for a path described by pathPoints. void QGEPath::startPathEdit(const std::vector& pathPoints) { -// Base::Console().Message("QGEPath::startPathEdit()\n"); +// Base::Console().message("QGEPath::startPathEdit()\n"); inEdit(true); m_ghostPoints = pathPoints; showMarkers(m_ghostPoints); @@ -213,13 +213,13 @@ void QGEPath::startPathEdit(const std::vector& pathPoints) void QGEPath::showMarkers(const std::vector& points) { -// Base::Console().Message("QGEPath::showMarkers()\n"); +// Base::Console().message("QGEPath::showMarkers()\n"); if (!inEdit()) { return; } if (points.empty()) { - Base::Console().Message("QGEP::showMarkers - no deltas\n"); + Base::Console().message("QGEP::showMarkers - no deltas\n"); return; } @@ -262,7 +262,7 @@ void QGEPath::showMarkers(const std::vector& points) void QGEPath::clearMarkers() { -// Base::Console().Message("QGEPath::clearMarkers()\n"); +// Base::Console().message("QGEPath::clearMarkers()\n"); if (m_markers.empty()) { return; } @@ -282,7 +282,7 @@ void QGEPath::clearMarkers() // end of node marker drag void QGEPath::onDragFinished(QPointF dragEndPos, int markerIndex) { -// Base::Console().Message("QGEPath::onDragFinished(%s, %d)\n", +// Base::Console().message("QGEPath::onDragFinished(%s, %d)\n", // TechDraw::DrawUtil::formatVector(dragEndPos).c_str(), // markerIndex); if ((int) m_ghostPoints.size() > markerIndex) { @@ -304,13 +304,13 @@ void QGEPath::onDoubleClick(QPointF pos, int markerIndex) { Q_UNUSED(pos); Q_UNUSED(markerIndex); -// Base::Console().Message("QGEPath::onDoubleClick()\n"); +// Base::Console().message("QGEPath::onDoubleClick()\n"); onEndEdit(); } void QGEPath::onEndEdit() { -// Base::Console().Message("QGEPath::onEndEdit()\n"); +// Base::Console().message("QGEPath::onEndEdit()\n"); if (m_ghost) { scene()->removeItem(m_ghost); //stop ghost from messing up brect } @@ -324,7 +324,7 @@ void QGEPath::onEndEdit() //announce points editing is finished void QGEPath::updateParent() { -// Base::Console().Message("QGEPath::updateParent() - inEdit: %d pts: %d\n", inEdit(), m_ghostPoints.size()); +// Base::Console().message("QGEPath::updateParent() - inEdit: %d pts: %d\n", inEdit(), m_ghostPoints.size()); // dumpGhostPoints("QGEP::updateParent"); QPointF attach = m_ghostPoints.front(); if (!inEdit()) { @@ -335,7 +335,7 @@ void QGEPath::updateParent() //! the ghost is the red line drawn when creating or editing the points void QGEPath::drawGhost() { -// Base::Console().Message("QGEPath::drawGhost()\n"); +// Base::Console().message("QGEPath::drawGhost()\n"); if (!m_ghost->scene()) { m_ghost->setParentItem(this); } @@ -381,7 +381,7 @@ void QGEPath::dumpGhostPoints(const char* text) { int idb = 0; for (auto& d: m_ghostPoints) { - Base::Console().Message("%s - point: %d %s\n", text, + Base::Console().message("%s - point: %d %s\n", text, idb, TechDraw::DrawUtil::formatVector(d).c_str()); idb++; } @@ -391,7 +391,7 @@ void QGEPath::dumpMarkerPos(const char* text) { int idb = 0; for (auto& m: m_markers) { - Base::Console().Message("QGEP - %s - markerPos: %d %s\n", text, + Base::Console().message("QGEP - %s - markerPos: %d %s\n", text, idb, TechDraw::DrawUtil::formatVector(m->pos()).c_str()); idb++; } diff --git a/src/Mod/TechDraw/Gui/QGIArrow.cpp b/src/Mod/TechDraw/Gui/QGIArrow.cpp index 1c82859f61..1b38f98074 100644 --- a/src/Mod/TechDraw/Gui/QGIArrow.cpp +++ b/src/Mod/TechDraw/Gui/QGIArrow.cpp @@ -315,7 +315,7 @@ double QGIArrow::getOverlapAdjust(ArrowType style, double size) // ex for fork and tick, adjustment sb zero. 0.25 is good for filled triangle, 0.1 for open arrow. // open circle sb = radius // NOTE: this may need to be adjusted to account for line thickness too. -// Base::Console().Message("QGIA::getOverlapAdjust(%d, %.3f) \n", style, size); +// Base::Console().message("QGIA::getOverlapAdjust(%d, %.3f) \n", style, size); switch(style) { case ArrowType::FILLED_ARROW: return 0.50 * size; diff --git a/src/Mod/TechDraw/Gui/QGIBreakLine.cpp b/src/Mod/TechDraw/Gui/QGIBreakLine.cpp index 32a0629029..9f04ed3a27 100644 --- a/src/Mod/TechDraw/Gui/QGIBreakLine.cpp +++ b/src/Mod/TechDraw/Gui/QGIBreakLine.cpp @@ -129,7 +129,7 @@ void QGIBreakLine::drawLargeZigZag() // start needs to be Rez'd and +Y up QPainterPath QGIBreakLine::makeHorizontalZigZag(Base::Vector3d start) const { - // Base::Console().Message("QGIBL::makeHorizontalZigZag(%s)\n", DU::formatVector(start).c_str()); + // Base::Console().message("QGIBL::makeHorizontalZigZag(%s)\n", DU::formatVector(start).c_str()); QPainterPath pPath; double step = (m_right - m_left) / segments; Base::Vector3d xOffset = Base::Vector3d(step, 0.0, 0.0); // 1/2 wave length @@ -150,7 +150,7 @@ QPainterPath QGIBreakLine::makeHorizontalZigZag(Base::Vector3d start) const QPainterPath QGIBreakLine::makeVerticalZigZag(Base::Vector3d start) const { - // Base::Console().Message("QGIBL::makeVerticalZigZag(%s)\n", DU::formatVector(start).c_str()); + // Base::Console().message("QGIBL::makeVerticalZigZag(%s)\n", DU::formatVector(start).c_str()); QPainterPath pPath; double step = (m_top - m_bottom) / segments; Base::Vector3d xOffset = Base::Vector3d(zigzagWidth, 0.0, 0.0); // amplitude @@ -209,7 +209,7 @@ QPainterPath QGIBreakLine::pathFromPoints(Base::Vector3d start, Base::Vector3d e void QGIBreakLine::setBounds(double left, double top, double right, double bottom) { - // Base::Console().Message("QGIBL::setBounds(%.3f, %.3f, %.3f, %.3f\n", left, top, right, bottom); + // Base::Console().message("QGIBL::setBounds(%.3f, %.3f, %.3f, %.3f\n", left, top, right, bottom); m_left = left; m_right = right; m_top = top; diff --git a/src/Mod/TechDraw/Gui/QGIDatumLabel.cpp b/src/Mod/TechDraw/Gui/QGIDatumLabel.cpp index 811da80a8f..176f1491e6 100644 --- a/src/Mod/TechDraw/Gui/QGIDatumLabel.cpp +++ b/src/Mod/TechDraw/Gui/QGIDatumLabel.cpp @@ -259,7 +259,7 @@ void QGIDatumLabel::mousePressEvent(QGraphicsSceneMouseEvent* event) void QGIDatumLabel::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { - // Base::Console().Message("QGIDL::mouseReleaseEvent()\n"); + // Base::Console().message("QGIDL::mouseReleaseEvent()\n"); m_ctrl = false; if (m_dragState == DragState::Dragging) { m_dragState = DragState::NoDrag; @@ -530,7 +530,7 @@ double QGIDatumLabel::getTolAdjust() void QGIDatumLabel::setPrettySel() { - // Base::Console().Message("QGIDL::setPrettySel()\n"); + // Base::Console().message("QGIDL::setPrettySel()\n"); m_dimText->setPrettySel(); m_tolTextOver->setPrettySel(); m_tolTextUnder->setPrettySel(); @@ -541,7 +541,7 @@ void QGIDatumLabel::setPrettySel() void QGIDatumLabel::setPrettyPre() { - // Base::Console().Message("QGIDL::setPrettyPre()\n"); + // Base::Console().message("QGIDL::setPrettyPre()\n"); m_dimText->setPrettyPre(); m_tolTextOver->setPrettyPre(); m_tolTextUnder->setPrettyPre(); @@ -552,7 +552,7 @@ void QGIDatumLabel::setPrettyPre() void QGIDatumLabel::setPrettyNormal() { - // Base::Console().Message("QGIDL::setPrettyNormal()\n"); + // Base::Console().message("QGIDL::setPrettyNormal()\n"); m_dimText->setPrettyNormal(); m_tolTextOver->setPrettyNormal(); m_tolTextUnder->setPrettyNormal(); @@ -563,7 +563,7 @@ void QGIDatumLabel::setPrettyNormal() void QGIDatumLabel::setColor(QColor color) { - // Base::Console().Message("QGIDL::setColor(%s)\n", qPrintable(c.name())); + // Base::Console().message("QGIDL::setColor(%s)\n", qPrintable(c.name())); m_colNormal = color; m_dimText->setColor(m_colNormal); m_tolTextOver->setColor(m_colNormal); diff --git a/src/Mod/TechDraw/Gui/QGIDecoration.cpp b/src/Mod/TechDraw/Gui/QGIDecoration.cpp index 98717bb881..fcf00bc731 100644 --- a/src/Mod/TechDraw/Gui/QGIDecoration.cpp +++ b/src/Mod/TechDraw/Gui/QGIDecoration.cpp @@ -118,7 +118,7 @@ void QGIDecoration::makeMark(Base::Vector3d v) void QGIDecoration::mousePressEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGID::mousePressEvent() - %s\n", getViewName()); +// Base::Console().message("QGID::mousePressEvent() - %s\n", getViewName()); m_dragState = DragState::DragStarted; QGraphicsItem::mousePressEvent(event); @@ -134,7 +134,7 @@ void QGIDecoration::mouseMoveEvent(QGraphicsSceneMouseEvent * event) void QGIDecoration::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGID::mouseReleaseEvent() - %s\n", getViewName()); +// Base::Console().message("QGID::mouseReleaseEvent() - %s\n", getViewName()); if (m_dragState == DragState::Dragging) { onDragFinished(); } diff --git a/src/Mod/TechDraw/Gui/QGIEdge.cpp b/src/Mod/TechDraw/Gui/QGIEdge.cpp index ef198f2520..dabdf7b85b 100644 --- a/src/Mod/TechDraw/Gui/QGIEdge.cpp +++ b/src/Mod/TechDraw/Gui/QGIEdge.cpp @@ -60,7 +60,6 @@ QGIEdge::QGIEdge(int index) : // not FreeCAD cosmetic lines void QGIEdge::setCosmetic(bool state) { -// Base::Console().Message("QGIE::setCosmetic(%d)\n", state); isCosmetic = state; if (state) { setWidth(0.0); @@ -69,15 +68,9 @@ void QGIEdge::setCosmetic(bool state) void QGIEdge::setHiddenEdge(bool b) { isHiddenEdge = b; - if (b) { - m_pen.setStyle(getHiddenStyle()); - } else { - m_pen.setStyle(Qt::SolidLine); - } } void QGIEdge::setPrettyNormal() { -// Base::Console().Message("QGIE::setPrettyNormal()\n"); if (isHiddenEdge) { m_pen.setColor(getHiddenColor()); return; @@ -91,14 +84,6 @@ QColor QGIEdge::getHiddenColor() return PreferencesGui::getAccessibleQColor(fcColor.asValue()); } -Qt::PenStyle QGIEdge::getHiddenStyle() -{ - //Qt::PenStyle - NoPen, Solid, Dashed, ... - //Preferences::General - Solid, Dashed - // Dashed lines should use ISO Line #2 instead of Qt::DashedLine - Qt::PenStyle hidStyle = static_cast (Preferences::getPreferenceGroup("General")->GetInt("HiddenLine", 0) + 1); - return hidStyle; -} double QGIEdge::getEdgeFuzz() const { @@ -123,16 +108,17 @@ QPainterPath QGIEdge::shape() const void QGIEdge::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) { Q_UNUSED(event) - QGIView *parent = dynamic_cast(parentItem()); + auto* parent = dynamic_cast(parentItem()); if (parent && parent->getViewObject() && parent->getViewObject()->isDerivedFrom()) { - TechDraw::DrawViewPart *baseFeat = static_cast(parent->getViewObject()); + auto* baseFeat = static_cast(parent->getViewObject()); std::vector edgeName(1, DrawUtil::makeGeomName("Edge", getProjIndex())); Gui::Control().showDialog(new TaskDlgLineDecor(baseFeat, edgeName)); } } -void QGIEdge::setLinePen(QPen linePen) +void QGIEdge::setLinePen(const QPen& linePen) { m_pen = linePen; } + diff --git a/src/Mod/TechDraw/Gui/QGIEdge.h b/src/Mod/TechDraw/Gui/QGIEdge.h index 2d662a1e26..543458ce19 100644 --- a/src/Mod/TechDraw/Gui/QGIEdge.h +++ b/src/Mod/TechDraw/Gui/QGIEdge.h @@ -47,14 +47,14 @@ public: void setCosmetic(bool state); void setHiddenEdge(bool b); - bool getHiddenEdge() { return(isHiddenEdge); } + bool getHiddenEdge() const { return(isHiddenEdge); } void setSmoothEdge(bool b) { isSmoothEdge = b; } - bool getSmoothEdge() { return(isSmoothEdge); } + bool getSmoothEdge() const { return(isSmoothEdge); } void setPrettyNormal() override; double getEdgeFuzz() const; - void setLinePen(QPen isoPen); + void setLinePen(const QPen& isoPen); void setSource(TechDraw::SourceType source) { m_source = source; } TechDraw::SourceType getSource() const { return m_source;} @@ -65,15 +65,15 @@ protected: bool multiselectEligible() override { return true; } + QColor getHiddenColor(); + +private: int projIndex; //index of edge in Projection. must exist. bool isCosmetic; bool isHiddenEdge; bool isSmoothEdge; - QColor getHiddenColor(); - Qt::PenStyle getHiddenStyle(); -private: TechDraw::SourceType m_source{TechDraw::SourceType::GEOMETRY}; }; diff --git a/src/Mod/TechDraw/Gui/QGIFace.cpp b/src/Mod/TechDraw/Gui/QGIFace.cpp index e2785dd8fb..480737e0ed 100644 --- a/src/Mod/TechDraw/Gui/QGIFace.cpp +++ b/src/Mod/TechDraw/Gui/QGIFace.cpp @@ -104,7 +104,7 @@ QColor QGIFace::getDefaultFillColor() /// redraw this face void QGIFace::draw() { -// Base::Console().Message("QGIF::draw - pen style: %d\n", m_pen.style()); +// Base::Console().message("QGIF::draw - pen style: %d\n", m_pen.style()); m_svgHatchArea->hide(); m_imageSvgHatchArea->hide(); @@ -148,7 +148,7 @@ void QGIFace::draw() /// show the face style & colour in normal configuration void QGIFace::setPrettyNormal() { -// Base::Console().Message("QGIF::setPrettyNormal() - hatched: %d\n", isHatched()); +// Base::Console().message("QGIF::setPrettyNormal() - hatched: %d\n", isHatched()); if (isHatched() && (m_mode == FillMode::BitmapFill) ) { //hatch with bitmap fill m_brush.setStyle(Qt::TexturePattern); @@ -161,21 +161,21 @@ void QGIFace::setPrettyNormal() { /// show the face style & colour in preselect configuration void QGIFace::setPrettyPre() { -// Base::Console().Message("QGIF::setPrettyPre()\n"); +// Base::Console().message("QGIF::setPrettyPre()\n"); m_brush.setStyle(Qt::SolidPattern); QGIPrimPath::setPrettyPre(); } /// show the face style & colour in selected configuration void QGIFace::setPrettySel() { -// Base::Console().Message("QGIF::setPrettySel()\n"); +// Base::Console().message("QGIF::setPrettySel()\n"); m_brush.setStyle(Qt::SolidPattern); QGIPrimPath::setPrettySel(); } /// show or hide the edges of this face. Usually just for debugging void QGIFace::setDrawEdges(bool state) { -// Base::Console().Message("QGIF::setDrawEdges(%d)\n", b); +// Base::Console().message("QGIF::setDrawEdges(%d)\n", b); if (state) { setStyle(Qt::DashLine); } else { @@ -194,7 +194,7 @@ void QGIFace::loadSvgHatch(std::string fileSpec) QString qfs(QString::fromUtf8(fileSpec.data(), fileSpec.size())); QFile file(qfs); if (!file.open(QFile::ReadOnly | QFile::Text)) { - Base::Console().Error("QGIFace could not read %s\n", fileSpec.c_str()); + Base::Console().error("QGIFace could not read %s\n", fileSpec.c_str()); return; } m_svgXML = file.readAll(); @@ -287,7 +287,7 @@ void QGIFace::makeMark(double x, double y) // NOLINT readability-identifier-len /// make an array of svg tiles to cover this face void QGIFace::buildSvgHatch() { -// Base::Console().Message("QGIF::buildSvgHatch() - offset: %s\n", DrawUtil::formatVector(getHatchOffset()).c_str()); +// Base::Console().message("QGIF::buildSvgHatch() - offset: %s\n", DrawUtil::formatVector(getHatchOffset()).c_str()); double wTile = SVGSIZEW * m_fillScale; double hTile = SVGSIZEH * m_fillScale; double faceWidth = path().boundingRect().width(); @@ -306,7 +306,7 @@ void QGIFace::buildSvgHatch() QByteArray after = QString::fromStdString(SVGCOLPREFIX + m_svgCol).toUtf8(); QByteArray colorXML = m_svgXML.replace(before, after); if (!m_sharedRender->load(colorXML)) { - Base::Console().Message("QGIF::buildSvgHatch - failed to load svg string\n"); + Base::Console().message("QGIF::buildSvgHatch - failed to load svg string\n"); return; } long int tileCount = 0; @@ -320,7 +320,7 @@ void QGIFace::buildSvgHatch() -overlayWidth + ih*hTile + getHatchOffset().y); tileCount++; if (tileCount > m_maxTile) { - Base::Console().Warning("SVG tile count exceeded: %ld. Change hatch scale or raise limit.\n", tileCount); + Base::Console().warning("SVG tile count exceeded: %ld. Change hatch scale or raise limit.\n", tileCount); break; } } @@ -359,7 +359,7 @@ void QGIFace::buildPixHatch() // don't really understand. // render svg tile onto a QImage if (!m_sharedRender->load(colorXML)) { - Base::Console().Message("QGIF::buildSvgHatch - failed to load svg string\n"); + Base::Console().message("QGIF::buildSvgHatch - failed to load svg string\n"); return; } @@ -367,7 +367,7 @@ void QGIFace::buildPixHatch() svgImage.fill(Qt::transparent); QPainter painter(&svgImage); if (svgImage.isNull()) { - Base::Console().Error("QGIF::buildPixHatch - svgImage is null\n"); + Base::Console().error("QGIF::buildPixHatch - svgImage is null\n"); return; } @@ -377,7 +377,7 @@ void QGIFace::buildPixHatch() QPixmap tilePixmap(round(wTile), round(hTile)); tilePixmap = QPixmap::fromImage(svgImage); if (tilePixmap.isNull()) { - Base::Console().Error("QGIF::buildPixHatch - tilePixmap is null\n"); + Base::Console().error("QGIF::buildPixHatch - tilePixmap is null\n"); return; } @@ -403,7 +403,7 @@ void QGIFace::buildPixHatch() QRectF(0, 0, wTile, hTile)); //source rect tileCount++; if (tileCount > m_maxTile) { - Base::Console().Warning("Pixmap tile count exceeded: %ld\n",tileCount); + Base::Console().warning("Pixmap tile count exceeded: %ld\n",tileCount); break; } } @@ -457,7 +457,7 @@ QPixmap QGIFace::textureFromBitmap(std::string fileSpec) const QString qfs(QString::fromUtf8(fileSpec.data(), fileSpec.size())); QFile file(qfs); if (!file.open(QFile::ReadOnly)) { - Base::Console().Error("QGIFace could not read %s\n", fileSpec.c_str()); + Base::Console().error("QGIFace could not read %s\n", fileSpec.c_str()); return pix; } QByteArray bytes = file.readAll(); diff --git a/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp b/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp index 8077026d6c..71620938ff 100644 --- a/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp +++ b/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp @@ -58,7 +58,7 @@ QGIGhostHighlight::~QGIGhostHighlight() void QGIGhostHighlight::mousePressEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGIGhostHighlight::mousePress() - %X\n", this); +// Base::Console().message("QGIGhostHighlight::mousePress() - %X\n", this); if ( (event->button() == Qt::LeftButton) && (flags() & QGraphicsItem::ItemIsMovable) ) { m_dragging = true; @@ -69,7 +69,7 @@ void QGIGhostHighlight::mousePressEvent(QGraphicsSceneMouseEvent * event) void QGIGhostHighlight::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { -// Base::Console().Message("QGIGhostHighlight::mouseRelease() - pos: %s scenePos: %s\n", +// Base::Console().message("QGIGhostHighlight::mouseRelease() - pos: %s scenePos: %s\n", // DrawUtil::formatVector(pos()).c_str(), // DrawUtil::formatVector(mapToScene(pos())).c_str()); if (m_dragging) { diff --git a/src/Mod/TechDraw/Gui/QGIHighlight.cpp b/src/Mod/TechDraw/Gui/QGIHighlight.cpp index 2195fd08ff..a2886b657c 100644 --- a/src/Mod/TechDraw/Gui/QGIHighlight.cpp +++ b/src/Mod/TechDraw/Gui/QGIHighlight.cpp @@ -66,7 +66,7 @@ QGIHighlight::~QGIHighlight() void QGIHighlight::onDragFinished() { -// Base::Console().Message("QGIH::onDragFinished - pos: %s\n", +// Base::Console().message("QGIH::onDragFinished - pos: %s\n", // DrawUtil::formatVector(pos()).c_str()); QGraphicsItem* parent = parentItem(); auto qgivp = dynamic_cast(parent); diff --git a/src/Mod/TechDraw/Gui/QGILeaderLine.cpp b/src/Mod/TechDraw/Gui/QGILeaderLine.cpp index e222b120a7..923a17e29d 100644 --- a/src/Mod/TechDraw/Gui/QGILeaderLine.cpp +++ b/src/Mod/TechDraw/Gui/QGILeaderLine.cpp @@ -109,7 +109,7 @@ QGILeaderLine::QGILeaderLine() void QGILeaderLine::setLeaderFeature(TechDraw::DrawLeaderLine* feat) { - // Base::Console().Message("QGILL::setLeaderFeature()\n"); + // Base::Console().message("QGILL::setLeaderFeature()\n"); setViewFeature(static_cast(feat)); float x = Rez::guiX(feat->X.getValue()); @@ -124,7 +124,7 @@ void QGILeaderLine::setLeaderFeature(TechDraw::DrawLeaderLine* feat) QVariant QGILeaderLine::itemChange(GraphicsItemChange change, const QVariant& value) { - // Base::Console().Message("QGILL::itemChange(%d)\n", change); + // Base::Console().message("QGILL::itemChange(%d)\n", change); if (change == ItemSelectedHasChanged && scene()) { if (isSelected()) { setPrettySel(); @@ -168,7 +168,7 @@ void QGILeaderLine::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) void QGILeaderLine::hoverEnterEvent(QGraphicsSceneHoverEvent* event) { - // Base::Console().Message("QGILL::hoverEnter() - selected; %d\n", isSelected()); + // Base::Console().message("QGILL::hoverEnter() - selected; %d\n", isSelected()); m_hasHover = true; if (!isSelected()) { setPrettyPre(); @@ -178,7 +178,7 @@ void QGILeaderLine::hoverEnterEvent(QGraphicsSceneHoverEvent* event) void QGILeaderLine::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) { - // Base::Console().Message("QGILL::hoverLeave() - selected; %d\n", isSelected()); + // Base::Console().message("QGILL::hoverLeave() - selected; %d\n", isSelected()); m_hasHover = false; if (!isSelected()) { setPrettyNormal(); @@ -188,7 +188,7 @@ void QGILeaderLine::hoverLeaveEvent(QGraphicsSceneHoverEvent* event) void QGILeaderLine::setNormalColorAll() { - // Base::Console().Message("QGILL::setNormalColorAll - normal color: %s\n", qPrintable(getNormalColor().name())); + // Base::Console().message("QGILL::setNormalColorAll - normal color: %s\n", qPrintable(getNormalColor().name())); QColor qc = prefNormalColor(); m_line->setNormalColor(qc); m_editPath->setNormalColor(qc); @@ -200,7 +200,7 @@ void QGILeaderLine::setNormalColorAll() void QGILeaderLine::setPrettyNormal() { - // Base::Console().Message("QGILL::setPrettyNormal()\n"); + // Base::Console().message("QGILL::setPrettyNormal()\n"); m_line->setPrettyNormal(); m_arrow1->setPrettyNormal(); m_arrow2->setPrettyNormal(); @@ -208,7 +208,7 @@ void QGILeaderLine::setPrettyNormal() void QGILeaderLine::setPrettyPre() { - // Base::Console().Message("QGILL::setPrettyPre()\n"); + // Base::Console().message("QGILL::setPrettyPre()\n"); m_line->setPrettyPre(); m_arrow1->setPrettyPre(); m_arrow2->setPrettyPre(); @@ -216,7 +216,7 @@ void QGILeaderLine::setPrettyPre() void QGILeaderLine::setPrettySel() { - // Base::Console().Message("QGILL::setPrettySel()\n"); + // Base::Console().message("QGILL::setPrettySel()\n"); m_line->setPrettySel(); m_arrow1->setPrettySel(); m_arrow2->setPrettySel(); @@ -225,7 +225,7 @@ void QGILeaderLine::setPrettySel() void QGILeaderLine::closeEdit() { - // Base::Console().Message("QGIL::closeEdit()\n"); + // Base::Console().message("QGIL::closeEdit()\n"); if (m_editPath) { m_editPath->onEndEdit();//tell QEPath that edit session ended } @@ -236,7 +236,7 @@ void QGILeaderLine::closeEdit() //! signaled from QEPath void QGILeaderLine::onLineEditFinished(QPointF tipDisplace, std::vector scenePoints) { - // Base::Console().Message("QGILL::onLineEditFinished(%s, %d)\n", + // Base::Console().message("QGILL::onLineEditFinished(%s, %d)\n", // TechDraw::DrawUtil::formatVector(tipDisplace).c_str(), // scenePoints.size()); @@ -299,7 +299,7 @@ void QGILeaderLine::startPathEdit() void QGILeaderLine::saveState() { - // Base::Console().Message("QGILL::saveState()\n"); + // Base::Console().message("QGILL::saveState()\n"); auto featLeader = getLeaderFeature(); if (featLeader) { m_savePoints = featLeader->WayPoints.getValues(); @@ -310,7 +310,7 @@ void QGILeaderLine::saveState() void QGILeaderLine::restoreState() { - // Base::Console().Message("QGILL::restoreState()\n"); + // Base::Console().message("QGILL::restoreState()\n"); auto featLeader = getLeaderFeature(); if (featLeader) { featLeader->WayPoints.setValues(m_savePoints); @@ -324,11 +324,11 @@ void QGILeaderLine::restoreState() void QGILeaderLine::updateView(bool update) { - // Base::Console().Message("QGILL::updateView()\n"); + // Base::Console().message("QGILL::updateView()\n"); Q_UNUSED(update); auto featLeader(dynamic_cast(getViewObject())); if (!featLeader) { - Base::Console().Warning("QGILL::updateView - no feature!\n"); + Base::Console().warning("QGILL::updateView - no feature!\n"); return; } @@ -391,7 +391,7 @@ void QGILeaderLine::draw() std::vector qPoints = getWayPointsFromFeature(); if (qPoints.empty() ) { - Base::Console().Message("QGILL::draw - no points\n"); + Base::Console().message("QGILL::draw - no points\n"); return; } @@ -416,7 +416,7 @@ QPainterPath QGILeaderLine::makeLeaderPath(std::vector qPoints) QPainterPath result; DrawLeaderLine* featLeader = getLeaderFeature(); if (!featLeader) { - // Base::Console().Message("QGILL::makeLeaderPath - featLeader is nullptr\n"); + // Base::Console().message("QGILL::makeLeaderPath - featLeader is nullptr\n"); return result; } @@ -466,7 +466,7 @@ QPointF QGILeaderLine::getAttachFromFeature() { TechDraw::DrawLeaderLine* featLeader = getLeaderFeature(); if (!featLeader) { - // Base::Console().Message("QGIL::getAttachFromLeader - no feature\n"); + // Base::Console().message("QGIL::getAttachFromLeader - no feature\n"); return {}; } double x = Rez::guiX(featLeader->X.getValue()); @@ -479,7 +479,7 @@ std::vector QGILeaderLine::getWayPointsFromFeature() { DrawLeaderLine* featLeader = getLeaderFeature(); if (!featLeader) { - // Base::Console().Message("QGILL::getWayPointsFromFeature - featLeader is nullptr\n"); + // Base::Console().message("QGILL::getWayPointsFromFeature - featLeader is nullptr\n"); return {}; } @@ -505,7 +505,7 @@ std::vector QGILeaderLine::getWayPointsFromFeature() } if (qPoints.empty()) { - Base::Console().Warning("QGILeaderLine::getWayPointsFromFeature - no points\n"); + Base::Console().warning("QGILeaderLine::getWayPointsFromFeature - no points\n"); } return qPoints; } @@ -602,7 +602,7 @@ Base::Vector3d QGILeaderLine::getAttachPoint() void QGILeaderLine::abandonEdit() { - // Base::Console().Message("QGIL::abandonEdit()\n"); + // Base::Console().message("QGIL::abandonEdit()\n"); m_editPath->clearMarkers(); m_editPath->hide(); restoreState(); @@ -629,7 +629,7 @@ double QGILeaderLine::getEdgeFuzz() const QColor QGILeaderLine::prefNormalColor() { - // Base::Console().Message("QGILL::getNormalColor()\n"); + // Base::Console().message("QGILL::getNormalColor()\n"); setNormalColor(PreferencesGui::leaderQColor()); auto vp = freecad_cast(getViewProvider(getViewObject())); diff --git a/src/Mod/TechDraw/Gui/QGIPrimPath.cpp b/src/Mod/TechDraw/Gui/QGIPrimPath.cpp index 6bee0cf657..50f6113b90 100644 --- a/src/Mod/TechDraw/Gui/QGIPrimPath.cpp +++ b/src/Mod/TechDraw/Gui/QGIPrimPath.cpp @@ -175,14 +175,14 @@ QColor QGIPrimPath::getSelectColor() void QGIPrimPath::setWidth(double w) { -// Base::Console().Message("QGIPP::setWidth(%.3f)\n", w); +// Base::Console().message("QGIPP::setWidth(%.3f)\n", w); m_pen.setWidthF(w); } void QGIPrimPath::setStyle(Qt::PenStyle s) { // TODO: edge lines for faces are drawn with setStyle(Qt::NoPen) and trigger this message. -// Base::Console().Warning("QGIPP::setStyle(Qt: %d) is deprecated. Use setLinePen instead\n", s); +// Base::Console().warning("QGIPP::setStyle(Qt: %d) is deprecated. Use setLinePen instead\n", s); m_styleNormal = s; m_pen.setStyle(s); } @@ -190,7 +190,7 @@ void QGIPrimPath::setStyle(Qt::PenStyle s) void QGIPrimPath::setStyle(int s) { // TODO: edge lines for faces are drawn with setStyle(Qt::NoPen) and trigger this message. -// Base::Console().Warning("QGIPP::setStyle(int: %d) is deprecated. Use setLinePen instead\n", s); +// Base::Console().warning("QGIPP::setStyle(int: %d) is deprecated. Use setLinePen instead\n", s); m_styleNormal = static_cast(s); m_pen.setStyle(m_styleNormal); } diff --git a/src/Mod/TechDraw/Gui/QGIProjGroup.cpp b/src/Mod/TechDraw/Gui/QGIProjGroup.cpp index 3d9b6ab3f8..5c5259bf9e 100644 --- a/src/Mod/TechDraw/Gui/QGIProjGroup.cpp +++ b/src/Mod/TechDraw/Gui/QGIProjGroup.cpp @@ -195,12 +195,12 @@ QGIView * QGIProjGroup::getAnchorQItem() const //QGIPG does not rotate. Only individual views rotate void QGIProjGroup::rotateView() { - Base::Console().Warning("QGIPG: Projection Groups do not rotate. Change ignored\n"); + Base::Console().warning("QGIPG: Projection Groups do not rotate. Change ignored\n"); } void QGIProjGroup::drawBorder() { //QGIProjGroup does not have a border! -// Base::Console().Message("TRACE - QGIProjGroup::drawBorder - doing nothing!!\n"); +// Base::Console().message("TRACE - QGIProjGroup::drawBorder - doing nothing!!\n"); } diff --git a/src/Mod/TechDraw/Gui/QGIRichAnno.cpp b/src/Mod/TechDraw/Gui/QGIRichAnno.cpp index 482a4174d1..80b83787f3 100644 --- a/src/Mod/TechDraw/Gui/QGIRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/QGIRichAnno.cpp @@ -83,7 +83,7 @@ QGIRichAnno::QGIRichAnno() : void QGIRichAnno::updateView(bool update) { -// Base::Console().Message("QGIRA::updateView() - %s\n", getViewName()); +// Base::Console().message("QGIRA::updateView() - %s\n", getViewName()); Q_UNUSED(update); auto annoFeat( dynamic_cast(getViewObject()) ); if (!annoFeat) { @@ -122,19 +122,19 @@ void QGIRichAnno::drawBorder() void QGIRichAnno::draw() { -// Base::Console().Log("QGIRA::draw() - %s - parent: %X\n", getFeature()->getNameInDocument(), parentItem()); +// Base::Console().log("QGIRA::draw() - %s - parent: %X\n", getFeature()->getNameInDocument(), parentItem()); if (!isVisible()) -// Base::Console().Message("QGIRA::draw - not visible\n"); +// Base::Console().message("QGIRA::draw - not visible\n"); return; TechDraw::DrawRichAnno* annoFeat = getFeature(); if (!annoFeat) -// Base::Console().Message("QGIRA::draw - no feature\n"); +// Base::Console().message("QGIRA::draw - no feature\n"); return; auto vp = static_cast(getViewProvider(getFeature())); if (!vp) { -// Base::Console().Message("QGIRA::draw - no viewprovider\n"); +// Base::Console().message("QGIRA::draw - no viewprovider\n"); return; } @@ -145,7 +145,7 @@ void QGIRichAnno::draw() void QGIRichAnno::setTextItem() { -// Base::Console().Message("QGIRA::setTextItem() - %s - exportingSvg: %d\n", getViewName(), getExportingSvg()); +// Base::Console().message("QGIRA::setTextItem() - %s - exportingSvg: %d\n", getViewName(), getExportingSvg()); TechDraw::DrawRichAnno* annoFeat = getFeature(); // convert the text size diff --git a/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp b/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp index f098cbf208..5844424b2d 100644 --- a/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp +++ b/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp @@ -248,7 +248,7 @@ void QGISVGTemplate::createClickHandles() QFile file(templateFilename); if (!file.open(QIODevice::ReadOnly)) { - Base::Console().Error( + Base::Console().error( "QGISVGTemplate::createClickHandles - error opening template file %s\n", svgTemplate->PageResult.getValue()); return; @@ -256,7 +256,7 @@ void QGISVGTemplate::createClickHandles() QDomDocument templateDocument; if (!templateDocument.setContent(&file)) { - Base::Console().Message("QGISVGTemplate::createClickHandles - xml loading error\n"); + Base::Console().message("QGISVGTemplate::createClickHandles - xml loading error\n"); return; } file.close(); diff --git a/src/Mod/TechDraw/Gui/QGISectionLine.cpp b/src/Mod/TechDraw/Gui/QGISectionLine.cpp index 57c4b316af..68a66ea1a8 100644 --- a/src/Mod/TechDraw/Gui/QGISectionLine.cpp +++ b/src/Mod/TechDraw/Gui/QGISectionLine.cpp @@ -321,7 +321,7 @@ void QGISectionLine::extensionEndsISO() void QGISectionLine::makeChangePointMarks() { -// Base::Console().Message("QGISL::makeChangePointMarks()\n"); +// Base::Console().message("QGISL::makeChangePointMarks()\n"); double segmentLength = 0.50 * QGIArrow::getPrefArrowSize(); QPen cPointPen; //TODO: this should really be 2.0 * thickLineWidth, but we only have one diff --git a/src/Mod/TechDraw/Gui/QGITile.cpp b/src/Mod/TechDraw/Gui/QGITile.cpp index a2a02d1684..52cac650ca 100644 --- a/src/Mod/TechDraw/Gui/QGITile.cpp +++ b/src/Mod/TechDraw/Gui/QGITile.cpp @@ -107,7 +107,7 @@ void QGITile::makeSymbol() return; } if (!m_qgSvg->load(&qba)) { - Base::Console().Error("Error - Could not load SVG renderer with **%s**\n", qPrintable(m_svgPath)); + Base::Console().error("Error - Could not load SVG renderer with **%s**\n", qPrintable(m_svgPath)); return; } m_qgSvg->setScale(getSymbolFactor()); diff --git a/src/Mod/TechDraw/Gui/QGIView.cpp b/src/Mod/TechDraw/Gui/QGIView.cpp index 1730222d95..8bd5cf7472 100644 --- a/src/Mod/TechDraw/Gui/QGIView.cpp +++ b/src/Mod/TechDraw/Gui/QGIView.cpp @@ -162,7 +162,7 @@ void QGIView::alignTo(QGraphicsItem*item, const QString &alignment) QVariant QGIView::itemChange(GraphicsItemChange change, const QVariant &value) { - // Base::Console().Message("QGIV::itemChange(%d)\n", change); + // Base::Console().message("QGIV::itemChange(%d)\n", change); if(change == ItemPositionChange && scene()) { QPointF newPos = value.toPointF(); //position within parent! @@ -448,7 +448,7 @@ void QGIView::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) void QGIView::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { - // Base::Console().Message("QGIV::hoverEnterEvent()\n"); + // Base::Console().message("QGIV::hoverEnterEvent()\n"); Q_UNUSED(event); // TODO don't like this but only solution at the minute (MLP) if (isSelected()) { @@ -474,7 +474,7 @@ void QGIView::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) //sets position in /Gui(graphics), not /App void QGIView::setPosition(qreal xPos, qreal yPos) { - // Base::Console().Message("QGIV::setPosition(%.3f, %.3f) (gui)\n", x, y); + // Base::Console().message("QGIV::setPosition(%.3f, %.3f) (gui)\n", x, y); double newX = xPos; double newY = -yPos; double oldX = pos().x(); @@ -503,7 +503,7 @@ QGIViewClip* QGIView::getClipGroup() void QGIView::updateView(bool forceUpdate) { - // Base::Console().Message("QGIV::updateView() - %s\n", getViewObject()->getNameInDocument()); + // Base::Console().message("QGIV::updateView() - %s\n", getViewObject()->getNameInDocument()); //allow/prevent dragging if (getViewObject()->isLocked()) { @@ -584,7 +584,7 @@ void QGIView::toggleCache(bool state) void QGIView::draw() { - // Base::Console().Message("QGIV::draw()\n"); + // Base::Console().message("QGIV::draw()\n"); double xFeat, yFeat; if (getViewObject()) { xFeat = Rez::guiX(getViewObject()->X.getValue()); @@ -603,7 +603,7 @@ void QGIView::draw() void QGIView::drawCaption() { - // Base::Console().Message("QGIV::drawCaption()\n"); + // Base::Console().message("QGIV::drawCaption()\n"); prepareGeometryChange(); QRectF displayArea = customChildrenBoundingRect(); m_caption->setDefaultTextColor(m_colCurrent); @@ -629,7 +629,7 @@ void QGIView::drawCaption() void QGIView::drawBorder() { - // Base::Console().Message("QGIV::drawBorder() - %s\n", getViewName()); + // Base::Console().message("QGIV::drawBorder() - %s\n", getViewName()); auto feat = getViewObject(); if (!feat) return; @@ -824,7 +824,7 @@ void QGIView::removeChild(QGIView* child) bool QGIView::getFrameState() { - // Base::Console().Message("QGIV::getFrameState() - %s\n", getViewName()); + // Base::Console().message("QGIV::getFrameState() - %s\n", getViewName()); TechDraw::DrawView* dv = getViewObject(); if (!dv) return true; @@ -932,7 +932,7 @@ int QGIView::calculateFontPixelWidth(const QFont &font) const double QGIView::DefaultFontSizeInMM = 5.0; void QGIView::dumpRect(const char* text, QRectF rect) { - Base::Console().Message("DUMP - %s - rect: (%.3f, %.3f) x (%.3f, %.3f)\n", text, + Base::Console().message("DUMP - %s - rect: (%.3f, %.3f) x (%.3f, %.3f)\n", text, rect.left(), rect.top(), rect.right(), rect.bottom()); } diff --git a/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp b/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp index 8d8a2e3d99..3eea3607aa 100644 --- a/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp @@ -92,7 +92,7 @@ void QGIViewAnnotation::updateView(bool update) void QGIViewAnnotation::draw() { - // Base::Console().Message("QGIVA::draw()\n"); + // Base::Console().message("QGIVA::draw()\n"); if (!isVisible()) { return; } @@ -106,7 +106,7 @@ void QGIViewAnnotation::draw() void QGIViewAnnotation::drawAnnotation() { - // Base::Console().Message("QGIVA::drawAnnotation()\n"); + // Base::Console().message("QGIVA::drawAnnotation()\n"); auto viewAnno(dynamic_cast(getViewObject())); if (!viewAnno) { return; @@ -144,7 +144,7 @@ void QGIViewAnnotation::drawAnnotation() } else if (viewAnno->TextStyle.isValue("Bold-Italic")) { ss << "font-weight:bold; font-style:italic; "; } else { - Base::Console().Warning("%s has invalid TextStyle\n", viewAnno->getNameInDocument()); + Base::Console().warning("%s has invalid TextStyle\n", viewAnno->getNameInDocument()); ss << "font-weight:normal; font-style:normal; "; } ss << "line-height:" << viewAnno->LineSpace.getValue() << "%; "; diff --git a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp index 0276439c22..3060f1212f 100644 --- a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp @@ -331,7 +331,7 @@ bool QGIViewBalloon::getGroupSelection() //Set selection state for this and its children void QGIViewBalloon::setGroupSelection(bool isSelected) { - // Base::Console().Message("QGIVB::setGroupSelection(%d)\n", b); + // Base::Console().message("QGIVB::setGroupSelection(%d)\n", b); setSelected(isSelected); balloonLabel->setSelected(isSelected); balloonLines->setSelected(isSelected); @@ -341,7 +341,7 @@ void QGIViewBalloon::setGroupSelection(bool isSelected) void QGIViewBalloon::select(bool state) { - // Base::Console().Message("QGIVBall::select(%d)\n", state); + // Base::Console().message("QGIVBall::select(%d)\n", state); setSelected(state); draw(); } @@ -354,7 +354,7 @@ void QGIViewBalloon::hover(bool state) void QGIViewBalloon::setViewPartFeature(TechDraw::DrawViewBalloon* balloonFeat) { - // Base::Console().Message("QGIVB::setViewPartFeature()\n"); + // Base::Console().message("QGIVB::setViewPartFeature()\n"); if (!balloonFeat) { return; } @@ -540,7 +540,7 @@ void QGIViewBalloon::balloonLabelDragFinished() //from QGVP::mouseReleaseEvent - pos = eventPos in scene coords? void QGIViewBalloon::placeBalloon(QPointF pos) { - // Base::Console().Message("QGIVB::placeBalloon(%s)\n", + // Base::Console().message("QGIVB::placeBalloon(%s)\n", // DrawUtil::formatVector(pos).c_str()); auto balloon(dynamic_cast(getViewObject())); if (!balloon) { @@ -870,7 +870,7 @@ void QGIViewBalloon::setPrettyPre(void) void QGIViewBalloon::setPrettySel(void) { - // Base::Console().Message("QGIVBal::setPrettySel()\n"); + // Base::Console().message("QGIVBal::setPrettySel()\n"); arrow->setPrettySel(); // balloonShape->setFill(Qt::white, Qt::NoBrush); balloonShape->setPrettySel(); @@ -889,7 +889,7 @@ void QGIViewBalloon::setPrettyNormal(void) void QGIViewBalloon::drawBorder(void) { //Dimensions have no border! - // Base::Console().Message("TRACE - QGIViewDimension::drawBorder - doing nothing!\n"); + // Base::Console().message("TRACE - QGIViewDimension::drawBorder - doing nothing!\n"); } void QGIViewBalloon::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, diff --git a/src/Mod/TechDraw/Gui/QGIViewClip.cpp b/src/Mod/TechDraw/Gui/QGIViewClip.cpp index 4c5d9e1351..6e3aaffdb4 100644 --- a/src/Mod/TechDraw/Gui/QGIViewClip.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewClip.cpp @@ -136,7 +136,7 @@ void QGIViewClip::drawClip() qgiv->show(); } } else { - Base::Console().Warning("Logic error? - drawClip() - qgiv for %s not found\n", (*it).c_str()); //gview for feature !exist + Base::Console().warning("Logic error? - drawClip() - qgiv for %s not found\n", (*it).c_str()); //gview for feature !exist } } diff --git a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp index 3b77f2cf06..5be1fb8d5c 100644 --- a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp @@ -161,7 +161,7 @@ bool QGIViewDimension::getGroupSelection() //Set selection state for this and its children void QGIViewDimension::setGroupSelection(bool isSelected) { - // Base::Console().Message("QGIVD::setGroupSelection(%d)\n", b); + // Base::Console().message("QGIVD::setGroupSelection(%d)\n", b); setSelected(isSelected); datumLabel->setSelected(isSelected); dimLines->setSelected(isSelected); @@ -184,7 +184,7 @@ void QGIViewDimension::hover(bool state) void QGIViewDimension::setViewPartFeature(TechDraw::DrawViewDimension* obj) { - // Base::Console().Message("QGIVD::setViewPartFeature()\n"); + // Base::Console().message("QGIVD::setViewPartFeature()\n"); if (!obj) { return; } @@ -220,7 +220,7 @@ void QGIViewDimension::setNormalColorAll() //and so mouse events need to be ignored. Only the QGIDatumLabel mouse events are relevant. void QGIViewDimension::mousePressEvent(QGraphicsSceneMouseEvent* event) { - // Base::Console().Message("QGIVD::mousePressEvent() - %s\n", getViewName()); + // Base::Console().message("QGIVD::mousePressEvent() - %s\n", getViewName()); QGraphicsItem::mousePressEvent(event); } @@ -231,7 +231,7 @@ void QGIViewDimension::mouseMoveEvent(QGraphicsSceneMouseEvent* event) void QGIViewDimension::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { - // Base::Console().Message("QGIVDim::mouseReleaseEvent() - %s\n", getViewName()); + // Base::Console().message("QGIVDim::mouseReleaseEvent() - %s\n", getViewName()); QGraphicsItem::mouseReleaseEvent(event); } @@ -408,7 +408,7 @@ void QGIViewDimension::draw() drawArea(dim, vp); } else { - Base::Console().Error("QGIVD::draw - this DimensionType is unknown: %s\n", dimType); + Base::Console().error("QGIVD::draw - this DimensionType is unknown: %s\n", dimType); } } else { @@ -713,7 +713,7 @@ bool QGIViewDimension::constructDimensionLine( { // The start position > 0 is not expected, the caller must handle this if (startPosition > 0.0) { - Base::Console().Error( + Base::Console().error( "QGIVD::constructDimLine - Start Position must not be positive! Received: %f\n", startPosition); return false; @@ -785,7 +785,7 @@ bool QGIViewDimension::constructDimensionArc( { // The start rotation > 0 is not expected, the caller must handle this if (startRotation > 0.0) { - Base::Console().Error( + Base::Console().error( "QGIVD::constructDimArc - Start Rotation must not be positive! Received: %f\n", startRotation); return false; @@ -1268,7 +1268,7 @@ void QGIViewDimension::drawDistanceExecutive(const Base::Vector2d& startPoint, labelRectangle, arrowCount, standardStyle, flipArrows); } else { - Base::Console().Error( + Base::Console().error( "QGIVD::drawDistanceExecutive - this Standard&Style is not supported: %d\n", standardStyle); arrowCount = 0; @@ -1480,7 +1480,7 @@ void QGIViewDimension::drawDistanceOverride(const Base::Vector2d& startPoint, labelRectangle, arrowCount, standardStyle, flipArrows); } else { - Base::Console().Error( + Base::Console().error( "QGIVD::drawDistanceExecutive - this Standard&Style is not supported: %d\n", standardStyle); arrowCount = 0; @@ -1728,7 +1728,7 @@ void QGIViewDimension::drawRadiusExecutive(const Base::Vector2d& centerPoint, labelPosition, labelRectangle, 1, standardStyle, flipArrow); } else { - Base::Console().Error( + Base::Console().error( "QGIVD::drawRadiusExecutive - this Standard&Style is not supported: %d\n", standardStyle); } @@ -1801,7 +1801,7 @@ void QGIViewDimension::drawAreaExecutive(const Base::Vector2d& centerPoint, doub drawDimensionLine(areaPath, centerPoint, lineAngle, 0.0, labelPosition, labelRectangle, 1, standardStyle, flipArrow, forcePointStyle); } else { - Base::Console().Error( + Base::Console().error( "QGIVD::drawRadiusExecutive - this Standard&Style is not supported: %d\n", standardStyle); } @@ -2004,7 +2004,7 @@ void QGIViewDimension::drawDiameter(TechDraw::DrawViewDimension* dimension, labelRectangle, 2, standardStyle, flipArrows); } else { - Base::Console().Error("QGIVD::drawRadius - this Standard&Style is not supported: %d\n", + Base::Console().error("QGIVD::drawRadius - this Standard&Style is not supported: %d\n", standardStyle); } @@ -2199,7 +2199,7 @@ void QGIViewDimension::drawAngle(TechDraw::DrawViewDimension* dimension, flipArrows); } else { - Base::Console().Error("QGIVD::drawAngle - this Standard&Style is not supported: %d\n", + Base::Console().error("QGIVD::drawAngle - this Standard&Style is not supported: %d\n", standardStyle); arrowCount = 0; } @@ -2325,14 +2325,14 @@ Base::Vector3d QGIViewDimension::findIsoExt(Base::Vector3d dir) const } //tarfu - Base::Console().Message("QGIVD::findIsoExt - %s - input is not iso axis\n", + Base::Console().message("QGIVD::findIsoExt - %s - input is not iso axis\n", getViewObject()->getNameInDocument()); return Base::Vector3d(1, 0, 0); } void QGIViewDimension::onPrettyChanged(int state) { - // Base::Console().Message("QGIVD::onPrettyChange(%d)\n", state); + // Base::Console().message("QGIVD::onPrettyChange(%d)\n", state); if (state == NORMAL) { setPrettyNormal(); } @@ -2368,7 +2368,7 @@ void QGIViewDimension::setPrettyNormal() void QGIViewDimension::drawBorder() { //Dimensions have no border! - // Base::Console().Message("TRACE - QGIViewDimension::drawBorder - doing nothing!\n"); + // Base::Console().message("TRACE - QGIViewDimension::drawBorder - doing nothing!\n"); } double QGIViewDimension::getDefaultExtensionLineOverhang() const diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.cpp b/src/Mod/TechDraw/Gui/QGIViewPart.cpp index b1d179875c..095fa93f14 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewPart.cpp @@ -111,7 +111,7 @@ QVariant QGIViewPart::itemChange(GraphicsItemChange change, const QVariant& valu bool QGIViewPart::sceneEventFilter(QGraphicsItem *watched, QEvent *event) { - // Base::Console().Message("QGIVP::sceneEventFilter - event: %d watchedtype: %d\n", + // Base::Console().message("QGIVP::sceneEventFilter - event: %d watchedtype: %d\n", // event->type(), watched->type() - QGraphicsItem::UserType); if (event->type() == QEvent::ShortcutOverride) { // if we accept this event, we should get a regular keystroke event next @@ -135,7 +135,7 @@ bool QGIViewPart::sceneEventFilter(QGraphicsItem *watched, QEvent *event) //! selected, remove it from the view. bool QGIViewPart::removeSelectedCosmetic() const { - // Base::Console().Message("QGIVP::removeSelectedCosmetic()\n"); + // Base::Console().message("QGIVP::removeSelectedCosmetic()\n"); auto dvp(dynamic_cast(getViewObject())); if (!dvp) { throw Base::RuntimeError("Graphic has no feature!"); @@ -186,7 +186,7 @@ QPainterPath QGIViewPart::drawPainterPath(TechDraw::BaseGeomPtr baseGeom) const void QGIViewPart::updateView(bool update) { - // Base::Console().Message("QGIVP::updateView() - %s\n", getViewObject()->getNameInDocument()); + // Base::Console().message("QGIVP::updateView() - %s\n", getViewObject()->getNameInDocument()); auto viewPart(dynamic_cast(getViewObject())); if (!viewPart) return; @@ -210,7 +210,7 @@ void QGIViewPart::draw() if (!doc || doc->testStatus(App::Document::Status::Restoring)) { // if the document is still restoring, we may not have all the information // we need to draw the source objects, so we wait until restore is finished. - // Base::Console().Message("QGIVP::draw - document is restoring, do not draw\n"); + // Base::Console().message("QGIVP::draw - document is restoring, do not draw\n"); return; } @@ -231,7 +231,7 @@ void QGIViewPart::drawViewPart() auto viewPart(dynamic_cast(getViewObject())); if (!viewPart) return; - // Base::Console().Message("QGIVP::DVP() - %s / %s\n", viewPart->getNameInDocument(), viewPart->Label.getValue()); + // Base::Console().message("QGIVP::DVP() - %s / %s\n", viewPart->getNameInDocument(), viewPart->Label.getValue()); if (!viewPart->hasGeometry()) { removePrimitives();//clean the slate removeDecorations(); @@ -373,7 +373,7 @@ void QGIViewPart::drawAllEdges() showItem = formatGeomFromCenterLine(cTag, item); } else { - Base::Console().Message("QGIVP::drawVP - cosmetic edge: %d is confused - source: %d\n", + Base::Console().message("QGIVP::drawVP - cosmetic edge: %d is confused - source: %d\n", iEdge, static_cast(source)); } } else { @@ -537,7 +537,7 @@ bool QGIViewPart::showCenterMarks() bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) { - // Base::Console().Message("QGIVP::formatGeomFromCosmetic(%s)\n", cTag.c_str()); + // Base::Console().message("QGIVP::formatGeomFromCosmetic(%s)\n", cTag.c_str()); bool result = true; auto partFeat(dynamic_cast(getViewObject())); TechDraw::CosmeticEdge* ce = partFeat ? partFeat->getCosmeticEdge(cTag) : nullptr; @@ -556,7 +556,7 @@ bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) { -// Base::Console().Message("QGIVP::formatGeomFromCenterLine()\n"); +// Base::Console().message("QGIVP::formatGeomFromCenterLine()\n"); bool result = true; auto partFeat(dynamic_cast(getViewObject())); TechDraw::CenterLine* cl = partFeat ? partFeat->getCenterLine(cTag) : nullptr; @@ -574,7 +574,7 @@ bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) QGIFace* QGIViewPart::drawFace(TechDraw::FacePtr f, int idx) { - // Base::Console().Message("QGIVP::drawFace - %d\n", idx); + // Base::Console().message("QGIVP::drawFace - %d\n", idx); std::vector fWires = f->wires; QPainterPath facePath; for (std::vector::iterator wire = fWires.begin(); wire != fWires.end(); @@ -693,7 +693,7 @@ void QGIViewPart::drawAllSectionLines() void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b) { -// Base::Console().Message("QGIVP::drawSectionLine()\n"); +// Base::Console().message("QGIVP::drawSectionLine()\n"); TechDraw::DrawViewPart* viewPart = static_cast(getViewObject()); if (!viewPart) return; @@ -715,7 +715,7 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b Base::Vector3d l1 = Rez::guiX(sLineEnds.first) * scale; Base::Vector3d l2 = Rez::guiX(sLineEnds.second) * scale; if (l1.IsEqual(l2, EWTOLERANCE) ) { - Base::Console().Message("QGIVP::drawSectionLine - line endpoints are equal. No section line created.\n"); + Base::Console().message("QGIVP::drawSectionLine - line endpoints are equal. No section line created.\n"); return; } @@ -794,7 +794,7 @@ void QGIViewPart::drawComplexSectionLine(TechDraw::DrawViewSection* viewSection, Base::Vector3d vStart = Rez::guiX(ends.first);//already scaled by dcs Base::Vector3d vEnd = Rez::guiX(ends.second); if (vStart.IsEqual(vEnd, EWTOLERANCE) ) { - Base::Console().Message("QGIVP::drawComplexSectionLine - line endpoints are equal. No section line created.\n"); + Base::Console().message("QGIVP::drawComplexSectionLine - line endpoints are equal. No section line created.\n"); return; } @@ -1029,7 +1029,7 @@ void QGIViewPart::drawMatting() //! if this is a broken view, draw the break lines. void QGIViewPart::drawBreakLines() { - // Base::Console().Message("QGIVP::drawBreakLines()\n"); + // Base::Console().message("QGIVP::drawBreakLines()\n"); auto dbv = dynamic_cast(getViewObject()); if (!dbv) { @@ -1141,7 +1141,7 @@ QGIViewPart::faceIsGeomHatched(int i, std::vector geom void QGIViewPart::dumpPath(const char* text, QPainterPath path) { QPainterPath::Element elem; - Base::Console().Message(">>>%s has %d elements\n", text, path.elementCount()); + Base::Console().message(">>>%s has %d elements\n", text, path.elementCount()); const char* typeName; for (int iElem = 0; iElem < path.elementCount(); iElem++) { elem = path.elementAt(iElem); @@ -1157,7 +1157,7 @@ void QGIViewPart::dumpPath(const char* text, QPainterPath path) else { typeName = "CurveData"; } - Base::Console().Message(">>>>> element %d: type:%d/%s pos(%.3f, %.3f) M:%d L:%d C:%d\n", + Base::Console().message(">>>>> element %d: type:%d/%s pos(%.3f, %.3f) M:%d L:%d C:%d\n", iElem, static_cast(elem.type), typeName, elem.x, elem.y, static_cast(elem.isMoveTo()), static_cast(elem.isLineTo()), static_cast(elem.isCurveTo())); } diff --git a/src/Mod/TechDraw/Gui/QGIViewSection.cpp b/src/Mod/TechDraw/Gui/QGIViewSection.cpp index 241de17f39..147ca1a16e 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSection.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewSection.cpp @@ -48,7 +48,7 @@ void QGIViewSection::draw() void QGIViewSection::drawSectionFace() { - // Base::Console().Message("QGIVS::drawSectionFace()\n"); + // Base::Console().message("QGIVS::drawSectionFace()\n"); auto section( dynamic_cast(getViewObject()) ); if (!section) { return; @@ -118,7 +118,7 @@ void QGIViewSection::drawSectionFace() } } } else { - Base::Console().Warning("QGIVS::draw - unknown CutSurfaceDisplay: %d\n", + Base::Console().warning("QGIVS::draw - unknown CutSurfaceDisplay: %d\n", section->CutSurfaceDisplay.getValue()); } diff --git a/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp b/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp index e63bfd3a79..ddaaa66fad 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp @@ -139,7 +139,7 @@ void QGIViewSymbol::symbolToSvg(QByteArray qba) prepareGeometryChange(); if (!m_svgItem->load(&qba)) { - Base::Console().Error("Error - Could not load Symbol into SVG renderer for %s\n", + Base::Console().error("Error - Could not load Symbol into SVG renderer for %s\n", getViewName()); } m_svgItem->centerAt(0., 0.); diff --git a/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp b/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp index 51e785053c..790abcce55 100644 --- a/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp +++ b/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp @@ -123,7 +123,7 @@ void QGIWeldSymbol::updateView(bool update) TechDraw::DrawWeldSymbol *feature = getFeature(); if (!feature) { - Base::Console().Warning("QGIWS::updateView - no feature!\n"); + Base::Console().warning("QGIWS::updateView - no feature!\n"); return; } @@ -161,7 +161,7 @@ void QGIWeldSymbol::draw() void QGIWeldSymbol::drawTile(TechDraw::DrawTileWeld* tileFeat) { if (!tileFeat) { - Base::Console().Message("QGIWS::drawTile - tile is null\n"); + Base::Console().message("QGIWS::drawTile - tile is null\n"); return; } diff --git a/src/Mod/TechDraw/Gui/QGSPage.cpp b/src/Mod/TechDraw/Gui/QGSPage.cpp index 3a37b37193..72766ab4b6 100644 --- a/src/Mod/TechDraw/Gui/QGSPage.cpp +++ b/src/Mod/TechDraw/Gui/QGSPage.cpp @@ -205,7 +205,7 @@ void QGSPage::addChildrenToPage() void QGSPage::attachTemplate(TechDraw::DrawTemplate* obj) { - // Base::Console().Message("QGSP::attachTemplate()\n"); + // Base::Console().message("QGSP::attachTemplate()\n"); setPageTemplate(obj); } @@ -324,7 +324,7 @@ int QGSPage::addQView(QGIView* view) view->updateView(true); } else { - Base::Console().Message("QGSP::addQView - qview already exists\n"); + Base::Console().message("QGSP::addQView - qview already exists\n"); } return 0; } @@ -667,7 +667,7 @@ QGIView* QGSPage::addViewDimension(TechDraw::DrawViewDimension* dimFeat) void QGSPage::addDimToParent(QGIViewDimension* dim, QGIView* parent) { - // Base::Console().Message("QGSP::addDimToParent()\n"); + // Base::Console().message("QGSP::addDimToParent()\n"); assert(dim); assert(parent);//blow up if we don't have Dimension or Parent QPointF posRef(0., 0.); @@ -1141,11 +1141,11 @@ void QGSPage::postProcessXml(QTemporaryFile& temporaryFile, QString fileName, QS QDomDocument exportDoc(QStringLiteral("SvgDoc")); QFile file(temporaryFile.fileName()); if (!file.open(QIODevice::ReadOnly)) { - Base::Console().Error("QGSPage::ppsvg - tempfile open error\n"); + Base::Console().error("QGSPage::ppsvg - tempfile open error\n"); return; } if (!exportDoc.setContent(&file)) { - Base::Console().Error("QGSPage::ppsvg - xml error\n"); + Base::Console().error("QGSPage::ppsvg - xml error\n"); file.close(); return; } @@ -1220,7 +1220,7 @@ void QGSPage::postProcessXml(QTemporaryFile& temporaryFile, QString fileName, QS // Time to save our product QFile outFile(fileName); if (!outFile.open(QIODevice::WriteOnly | QIODevice::Text)) { - Base::Console().Error("QGSP::ppxml - failed to open file for writing: %s\n", + Base::Console().error("QGSP::ppxml - failed to open file for writing: %s\n", qPrintable(fileName)); } diff --git a/src/Mod/TechDraw/Gui/QGTracker.cpp b/src/Mod/TechDraw/Gui/QGTracker.cpp index c1313ded2b..80be154b8a 100644 --- a/src/Mod/TechDraw/Gui/QGTracker.cpp +++ b/src/Mod/TechDraw/Gui/QGTracker.cpp @@ -112,7 +112,7 @@ void QGTracker::mousePressEvent(QGraphicsSceneMouseEvent *event) double someLimit = Rez::guiX(1.0); QPointF manhat = myScenePos - m_lastClick; - if (manhat.manhattanLength() >= someLimit) { + if (manhat.manhattanLength() >= someLimit) { if (event->button() == Qt::LeftButton) { if (event->modifiers() & Qt::ControlModifier) { myScenePos = snapToAngle(myScenePos); @@ -243,7 +243,7 @@ void QGTracker::onMousePress(QPointF pos) //just return pos to caller getPickedQGIV(pos); setCursor(Qt::CrossCursor); //why cross?? - + if (mode == TrackerMode::Point) { setPoint(m_points); //first point is mouse click scene pos terminateDrawing(); @@ -419,7 +419,7 @@ void QGTracker::setCircleFromPoints(std::vector pts) void QGTracker::setPoint(std::vector pts) { if (pts.empty()) { - Base::Console().Message("QGTracker::setPoint - no pts!\n"); + Base::Console().message("QGTracker::setPoint - no pts!\n"); return; } prepareGeometryChange(); diff --git a/src/Mod/TechDraw/Gui/QGVNavStyle.cpp b/src/Mod/TechDraw/Gui/QGVNavStyle.cpp index e145b30814..35280cdf94 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyle.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyle.cpp @@ -109,7 +109,7 @@ void QGVNavStyle::handleFocusOutEvent(QFocusEvent* event) void QGVNavStyle::handleKeyPressEvent(QKeyEvent* event) { - // Base::Console().Message("QGNS::handleKeyPressEvent(%d)\n", event->key()); + // Base::Console().message("QGNS::handleKeyPressEvent(%d)\n", event->key()); if (event->modifiers().testFlag(Qt::ControlModifier)) { switch (event->key()) { case Qt::Key_Plus: { @@ -214,7 +214,7 @@ void QGVNavStyle::handleLeaveEvent(QEvent* event) void QGVNavStyle::handleMousePressEvent(QMouseEvent* event) { - // Base::Console().Message("QGVNS::handleMousePressEvent()\n"); + // Base::Console().message("QGVNS::handleMousePressEvent()\n"); if (!panningActive && (event->button() == Qt::MiddleButton)) { startPan(event->pos()); event->accept(); @@ -223,7 +223,7 @@ void QGVNavStyle::handleMousePressEvent(QMouseEvent* event) void QGVNavStyle::handleMouseMoveEvent(QMouseEvent* event) { - // Base::Console().Message("QGVNS::handleMouseMoveEvent()\n"); + // Base::Console().message("QGVNS::handleMouseMoveEvent()\n"); if (getViewer()->isBalloonPlacing()) { balloonCursorMovement(event); return; @@ -239,7 +239,7 @@ void QGVNavStyle::handleMouseMoveEvent(QMouseEvent* event) //button that caused the event (typically RMB) void QGVNavStyle::handleMouseReleaseEvent(QMouseEvent* event) { - // Base::Console().Message("QGVNS::handleMouseReleaseEvent()\n"); + // Base::Console().message("QGVNS::handleMouseReleaseEvent()\n"); if (getViewer()->isBalloonPlacing()) { placeBalloon(event->pos()); } @@ -253,7 +253,7 @@ void QGVNavStyle::handleMouseReleaseEvent(QMouseEvent* event) bool QGVNavStyle::allowContextMenu(QContextMenuEvent* event) { Q_UNUSED(event) - // Base::Console().Message("QGVNS::allowContextMenu()\n"); + // Base::Console().message("QGVNS::allowContextMenu()\n"); // if (event->reason() == QContextMenuEvent::Mouse) { // //must check for a button combination involving context menu button // } @@ -305,7 +305,7 @@ void QGVNavStyle::zoom(double factor) void QGVNavStyle::startZoom(QPoint p) { - // Base::Console().Message("QGVNS::startZoom(%s)\n", TechDraw::DrawUtil::formatVector(p).c_str()); + // Base::Console().message("QGVNS::startZoom(%s)\n", TechDraw::DrawUtil::formatVector(p).c_str()); zoomOrigin = p; zoomingActive = true; m_zoomPending = false; @@ -314,7 +314,7 @@ void QGVNavStyle::startZoom(QPoint p) void QGVNavStyle::stopZoom() { - // Base::Console().Message("QGVNS::stopZoom()\n"); + // Base::Console().message("QGVNS::stopZoom()\n"); zoomingActive = false; m_zoomPending = false; getViewer()->resetCursor(); @@ -371,7 +371,7 @@ void QGVNavStyle::pan(QPoint p) void QGVNavStyle::stopPan() { - // Base::Console().Message("QGVNS::stopPan()\n"); + // Base::Console().message("QGVNS::stopPan()\n"); panningActive = false; m_panPending = false; getViewer()->resetCursor(); @@ -391,7 +391,7 @@ void QGVNavStyle::stopClick() void QGVNavStyle::placeBalloon(QPoint p) { - // Base::Console().Message("QGVNS::placeBalloon()\n"); + // Base::Console().message("QGVNS::placeBalloon()\n"); getViewer()->getBalloonCursor()->hide(); //balloon was created in Command.cpp. Why are we doing it again? getViewer()->getScene()->createBalloon(getViewer()->mapToScene(p), diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleBlender.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleBlender.cpp index 665669f906..0892ec74ef 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleBlender.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleBlender.cpp @@ -54,12 +54,12 @@ void QGVNavStyleBlender::handleKeyReleaseEvent(QKeyEvent *event) void QGVNavStyleBlender::handleMousePressEvent(QMouseEvent *event) { Q_UNUSED(event) -// Base::Console().Message("QGVNSBlender::handleMousePressEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); +// Base::Console().message("QGVNSBlender::handleMousePressEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); } void QGVNavStyleBlender::handleMouseMoveEvent(QMouseEvent *event) { -// Base::Console().Message("QGVNSBlender::handleMouseMoveEvent() - buttons: %d modifiers: %X\n", +// Base::Console().message("QGVNSBlender::handleMouseMoveEvent() - buttons: %d modifiers: %X\n", // QGuiApplication::mouseButtons() & Qt::MiddleButton, // QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)); @@ -91,7 +91,7 @@ void QGVNavStyleBlender::handleMouseMoveEvent(QMouseEvent *event) void QGVNavStyleBlender::handleMouseReleaseEvent(QMouseEvent *event) { -// Base::Console().Message("QGVNSBlender::handleMouseReleaseEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); +// Base::Console().message("QGVNSBlender::handleMouseReleaseEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); if (getViewer()->isBalloonPlacing()) { placeBalloon(event->pos()); } @@ -115,7 +115,7 @@ void QGVNavStyleBlender::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleBlender::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSBlender::allowContextMenu()\n"); +// Base::Console().message("QGVNSBlender::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QGuiApplication::mouseButtons() & Qt::LeftButton) { diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleCAD.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleCAD.cpp index 3752ae195c..87587a3da0 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleCAD.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleCAD.cpp @@ -62,7 +62,7 @@ void QGVNavStyleCAD::handleKeyReleaseEvent(QKeyEvent *event) void QGVNavStyleCAD::handleMousePressEvent(QMouseEvent *event) { -// Base::Console().Message("QGVNSCAD::handleMousePressEvent() - button: %d\n", event->button()); +// Base::Console().message("QGVNSCAD::handleMousePressEvent() - button: %d\n", event->button()); if (event->button() == Qt::MiddleButton) { startClick(Qt::MiddleButton); //for MMB center view } @@ -131,7 +131,7 @@ void QGVNavStyleCAD::handleMouseMoveEvent(QMouseEvent *event) void QGVNavStyleCAD::handleMouseReleaseEvent(QMouseEvent *event) { -// Base::Console().Message("QGVNSCAD::handleMouseReleaseEvent() - button: %d\n", event->button()); +// Base::Console().message("QGVNSCAD::handleMouseReleaseEvent() - button: %d\n", event->button()); if (getViewer()->isBalloonPlacing()) { placeBalloon(event->pos()); } @@ -174,7 +174,7 @@ void QGVNavStyleCAD::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleCAD::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSCAD::allowContextMenu()\n"); +// Base::Console().message("QGVNSCAD::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) || diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleMaya.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleMaya.cpp index cde2c62bd4..4b62b8add5 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleMaya.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleMaya.cpp @@ -118,7 +118,7 @@ void QGVNavStyleMaya::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleMaya::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSM::allowContextMenu()\n"); +// Base::Console().message("QGVNSM::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QApplication::keyboardModifiers() == Qt::AltModifier) { diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleOCC.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleOCC.cpp index 7b689f1aa2..6aa360ac3c 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleOCC.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleOCC.cpp @@ -128,7 +128,7 @@ void QGVNavStyleOCC::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleOCC::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSOCC::allowContextMenu()\n"); +// Base::Console().message("QGVNSOCC::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ) { diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.cpp index 42e1d41d4b..06edacf6a5 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.cpp @@ -138,7 +138,7 @@ void QGVNavStyleOpenSCAD::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleOpenSCAD::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSCAD::allowContextMenu()\n"); +// Base::Console().message("QGVNSCAD::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QGuiApplication::keyboardModifiers().testFlag(Qt::ShiftModifier)) { diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleRevit.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleRevit.cpp index a6fb0c9fc3..271bb6df3e 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleRevit.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleRevit.cpp @@ -113,7 +113,7 @@ void QGVNavStyleRevit::handleMouseReleaseEvent(QMouseEvent *event) bool QGVNavStyleRevit::allowContextMenu(QContextMenuEvent *event) { -// Base::Console().Message("QGVNSRevit::allowContextMenu()\n"); +// Base::Console().message("QGVNSRevit::allowContextMenu()\n"); if (event->reason() == QContextMenuEvent::Mouse) { //must check for a button combination involving context menu button if (QGuiApplication::mouseButtons() & Qt::LeftButton) { diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleSolidWorks.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleSolidWorks.cpp index ec7602e471..f7e46e0cee 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleSolidWorks.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleSolidWorks.cpp @@ -55,7 +55,7 @@ void QGVNavStyleSolidWorks::handleKeyReleaseEvent(QKeyEvent *event) void QGVNavStyleSolidWorks::handleMousePressEvent(QMouseEvent *event) { Q_UNUSED(event) -// Base::Console().Message("QGVNSSolidWorks::handleMousePressEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); +// Base::Console().message("QGVNSSolidWorks::handleMousePressEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); } void QGVNavStyleSolidWorks::handleMouseMoveEvent(QMouseEvent *event) @@ -78,7 +78,7 @@ void QGVNavStyleSolidWorks::handleMouseMoveEvent(QMouseEvent *event) } else if ((QGuiApplication::mouseButtons() & Qt::MiddleButton) && QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ) { // pan mode 1 - Ctrl + MMB - // I think this block may be unnecessary since pan mode 2 MMB also captures pan mode 1 + // I think this block may be unnecessary since pan mode 2 MMB also captures pan mode 1 // Ctrl + MMB, but I'll leave it in to make it clear that this is what's intended // also nav style OCC has a similar block if (panningActive) { @@ -95,12 +95,12 @@ void QGVNavStyleSolidWorks::handleMouseMoveEvent(QMouseEvent *event) startPan(event->pos()); } event->accept(); - } + } } void QGVNavStyleSolidWorks::handleMouseReleaseEvent(QMouseEvent *event) { -// Base::Console().Message("QGVNSSolidWorks::handleMouseReleaseEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); +// Base::Console().message("QGVNSSolidWorks::handleMouseReleaseEvent() - button: %d buttons: %d\n", event->button(), event->buttons()); if (getViewer()->isBalloonPlacing()) { placeBalloon(event->pos()); } diff --git a/src/Mod/TechDraw/Gui/SymbolChooser.cpp b/src/Mod/TechDraw/Gui/SymbolChooser.cpp index a89a800ee2..e46628f37a 100644 --- a/src/Mod/TechDraw/Gui/SymbolChooser.cpp +++ b/src/Mod/TechDraw/Gui/SymbolChooser.cpp @@ -57,7 +57,7 @@ SymbolChooser::~SymbolChooser() void SymbolChooser::setUiPrimary() { - // Base::Console().Message("SC::setUiPrimary()\n"); + // Base::Console().message("SC::setUiPrimary()\n"); setWindowTitle(QObject::tr("Select a symbol")); resize(QSize(700, 500)); if (!m_symbolDir.isEmpty()) { @@ -103,7 +103,7 @@ void SymbolChooser::onCancelClicked() void SymbolChooser::onItemClicked(QListWidgetItem* item) { Q_UNUSED(item); - // Base::Console().Message("SCS::onItemClicked(%s)\n", qPrintable(item->text())); + // Base::Console().message("SCS::onItemClicked(%s)\n", qPrintable(item->text())); // Are item and currentItem() the same? Should use item? QListWidgetItem* sourceItem = ui->lwSymbols->currentItem(); QString targetText = sourceItem->text(); @@ -112,14 +112,14 @@ void SymbolChooser::onItemClicked(QListWidgetItem* item) QStringLiteral(".svg"); Q_EMIT symbolSelected(m_symbolPath, m_source); - // Base::Console().Message("SC::onOKClicked - symbol: %s\n", qPrintable(m_symbolPath)); + // Base::Console().message("SC::onOKClicked - symbol: %s\n", qPrintable(m_symbolPath)); accept(); } void SymbolChooser::onDirectoryChanged(const QString& newDir) { ui->lwSymbols->clear(); // Remove all previous symbols - // Base::Console().Message("SC::onDirectoryChanged(%s)\n", qPrintable(newDir)); + // Base::Console().message("SC::onDirectoryChanged(%s)\n", qPrintable(newDir)); m_symbolDir = newDir + QStringLiteral("/"); loadSymbolNames(m_symbolDir); } diff --git a/src/Mod/TechDraw/Gui/TaskActiveView.cpp b/src/Mod/TechDraw/Gui/TaskActiveView.cpp index e013239f0c..99790fa7a7 100644 --- a/src/Mod/TechDraw/Gui/TaskActiveView.cpp +++ b/src/Mod/TechDraw/Gui/TaskActiveView.cpp @@ -88,7 +88,7 @@ void TaskActiveView::changeEvent(QEvent* e) void TaskActiveView::setUiPrimary() { - // Base::Console().Message("TAV::setUiPrimary()\n"); + // Base::Console().message("TAV::setUiPrimary()\n"); setWindowTitle(QObject::tr("ActiveView to TD View")); ui->cbCrop->setChecked(false); enableCrop(false); @@ -101,7 +101,7 @@ void TaskActiveView::blockButtons(bool b) { Q_UNUSED(b); } TechDraw::DrawViewImage* TaskActiveView::createActiveView() { - // Base::Console().Message("TAV::createActiveView()\n"); + // Base::Console().message("TAV::createActiveView()\n"); //make sure there is an 3D MDI to grab!! if (!Gui::getMainWindow()) { @@ -205,7 +205,7 @@ TechDraw::DrawViewImage* TaskActiveView::createActiveView() bool success = image.save(QString::fromStdString(tempName)); if (!success) { - Base::Console().Error("ActiveView could not save file: %s\n", fileSpec.c_str()); + Base::Console().error("ActiveView could not save file: %s\n", fileSpec.c_str()); } tempName = DU::cleanFilespecBackslash(tempName); @@ -263,7 +263,7 @@ void TaskActiveView::enableTaskButtons(bool b) bool TaskActiveView::accept() { - // Base::Console().Message("TAV::accept()\n"); + // Base::Console().message("TAV::accept()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create ActiveView")); m_imageFeat = createActiveView(); // m_imageFeat->requestPaint(); @@ -280,7 +280,7 @@ bool TaskActiveView::accept() bool TaskActiveView::reject() { - // Base::Console().Message("TAV::reject()\n"); + // Base::Console().message("TAV::reject()\n"); //nothing to remove. Gui::Command::doCommand(Gui::Command::Gui, "App.activeDocument().recompute()"); diff --git a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp index 2596508963..ab4990a0de 100644 --- a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp @@ -115,7 +115,7 @@ TaskCenterLine::TaskCenterLine(TechDraw::DrawViewPart* partFeat, } else if (geomType == "Vertex") { m_type = Type::VERTEX; } else { - Base::Console().Error("TaskCenterLine - unknown geometry type: %s. Can not proceed.\n", geomType.c_str()); + Base::Console().error("TaskCenterLine - unknown geometry type: %s. Can not proceed.\n", geomType.c_str()); return; } diff --git a/src/Mod/TechDraw/Gui/TaskComplexSection.cpp b/src/Mod/TechDraw/Gui/TaskComplexSection.cpp index a62a1fa41c..55da4ba321 100644 --- a/src/Mod/TechDraw/Gui/TaskComplexSection.cpp +++ b/src/Mod/TechDraw/Gui/TaskComplexSection.cpp @@ -486,7 +486,7 @@ bool TaskComplexSection::apply(bool forceUpdate) if (m_baseView) { if (!DrawComplexSection::canBuild(m_baseView->localVectorToCS(localUnit), m_profileObject)) { - Base::Console().Error( + Base::Console().error( "Can not build Complex Section with this profile and direction (1)\n"); return false; } @@ -496,7 +496,7 @@ bool TaskComplexSection::apply(bool forceUpdate) gp_Ax2 sectionCS(stdOrigin, Base::convertTo(m_saveNormal), Base::convertTo(m_saveXDir)); if (!DrawComplexSection::canBuild(sectionCS, m_profileObject)) { - Base::Console().Error( + Base::Console().error( "Can not build Complex Section with this profile and direction (2)\n"); return false; } diff --git a/src/Mod/TechDraw/Gui/TaskCosVertex.cpp b/src/Mod/TechDraw/Gui/TaskCosVertex.cpp index 01988972e6..6db3c7f74f 100644 --- a/src/Mod/TechDraw/Gui/TaskCosVertex.cpp +++ b/src/Mod/TechDraw/Gui/TaskCosVertex.cpp @@ -104,7 +104,7 @@ void TaskCosVertex::changeEvent(QEvent* event) void TaskCosVertex::setUiPrimary() { -// Base::Console().Message("TCV::setUiPrimary()\n"); +// Base::Console().message("TCV::setUiPrimary()\n"); setWindowTitle(QObject::tr("New Cosmetic Vertex")); if (m_baseFeat) { @@ -149,7 +149,7 @@ void TaskCosVertex::addCosVertex(QPointF qPos) void TaskCosVertex::onTrackerClicked(bool clicked) { Q_UNUSED(clicked); -// Base::Console().Message("TCV::onTrackerClicked() m_pbTrackerState: %d\n", +// Base::Console().message("TCV::onTrackerClicked() m_pbTrackerState: %d\n", // m_pbTrackerState); removeTracker(); @@ -181,7 +181,7 @@ void TaskCosVertex::onTrackerClicked(bool clicked) void TaskCosVertex::startTracker() { -// Base::Console().Message("TCV::startTracker()\n"); +// Base::Console().message("TCV::startTracker()\n"); if (m_trackerMode == QGTracker::TrackerMode::None) { return; } @@ -207,7 +207,7 @@ void TaskCosVertex::onTrackerFinished(std::vector pts, QGIView* qgParen { (void)qgParent; if (pts.empty()) { - Base::Console().Error("TaskCosVertex - no points available\n"); + Base::Console().error("TaskCosVertex - no points available\n"); return; } @@ -255,7 +255,7 @@ void TaskCosVertex::onTrackerFinished(std::vector pts, QGIView* qgParen void TaskCosVertex::removeTracker() { -// Base::Console().Message("TCV::removeTracker()\n"); +// Base::Console().message("TCV::removeTracker()\n"); if (m_tracker && m_tracker->scene()) { m_vpp->getQGSPage()->removeItem(m_tracker); delete m_tracker; diff --git a/src/Mod/TechDraw/Gui/TaskCosmeticCircle.cpp b/src/Mod/TechDraw/Gui/TaskCosmeticCircle.cpp index a1a7604e4f..d9c8f9d2b1 100644 --- a/src/Mod/TechDraw/Gui/TaskCosmeticCircle.cpp +++ b/src/Mod/TechDraw/Gui/TaskCosmeticCircle.cpp @@ -62,7 +62,7 @@ TaskCosmeticCircle::TaskCosmeticCircle(TechDraw::DrawViewPart* partFeat, m_ce = m_partFeat->getCosmeticEdgeBySelection(m_circleName); if (!m_ce) { - Base::Console().Error("TaskCosmeticCircle - bad parameters. Can not proceed.\n"); + Base::Console().error("TaskCosmeticCircle - bad parameters. Can not proceed.\n"); return; } @@ -226,7 +226,7 @@ void TaskCosmeticCircle::enableArcWidgets(bool newState) //****************************************************************************** void TaskCosmeticCircle::createCosmeticCircle(void) { -// Base::Console().Message("TCL::createCosmeticCircle()\n"); +// Base::Console().message("TCL::createCosmeticCircle()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create Cosmetic Circle")); @@ -261,7 +261,7 @@ void TaskCosmeticCircle::createCosmeticCircle(void) void TaskCosmeticCircle::updateCosmeticCircle(void) { - // Base::Console().Message("TCL::updateCosmeticCircle()\n"); + // Base::Console().message("TCL::updateCosmeticCircle()\n"); double x = ui->qsbCenterX->value().getValue(); double y = ui->qsbCenterY->value().getValue(); double z = ui->qsbCenterZ->value().getValue(); @@ -289,7 +289,7 @@ bool TaskCosmeticCircle::accept() { if (ui->qsbRadius->value().getValue() <= 0.0) { // this won't work! - Base::Console().Error("TaskCosmeticCircle - can not create a circle with radius: %.3f\n", + Base::Console().error("TaskCosmeticCircle - can not create a circle with radius: %.3f\n", ui->qsbRadius->value().getValue()); return false; } diff --git a/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp b/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp index a92d86caa9..cae9f9c5d4 100644 --- a/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp @@ -59,7 +59,7 @@ TaskCosmeticLine::TaskCosmeticLine(TechDraw::DrawViewPart* partFeat, m_ce = m_partFeat->getCosmeticEdgeBySelection(m_edgeName); if (!m_ce) { - Base::Console().Error("TaskCosmeticLine - bad parameters. Can not proceed.\n"); + Base::Console().error("TaskCosmeticLine - bad parameters. Can not proceed.\n"); return; } @@ -173,7 +173,7 @@ void TaskCosmeticLine::setUiEdit() //****************************************************************************** void TaskCosmeticLine::createCosmeticLine() { -// Base::Console().Message("TCL::createCosmeticLine()\n"); +// Base::Console().message("TCL::createCosmeticLine()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create Cosmetic Line")); // ui 2d points are interpreted as unscaled, unrotated, uninverted @@ -207,7 +207,7 @@ void TaskCosmeticLine::createCosmeticLine() void TaskCosmeticLine::updateCosmeticLine() { -// Base::Console().Message("TCL::updateCosmeticLine()\n"); +// Base::Console().message("TCL::updateCosmeticLine()\n"); double x = ui->qsbx1->value().getValue(); double y = ui->qsby1->value().getValue(); double z = ui->qsbz1->value().getValue(); diff --git a/src/Mod/TechDraw/Gui/TaskDetail.cpp b/src/Mod/TechDraw/Gui/TaskDetail.cpp index 38963820aa..473674a785 100644 --- a/src/Mod/TechDraw/Gui/TaskDetail.cpp +++ b/src/Mod/TechDraw/Gui/TaskDetail.cpp @@ -79,7 +79,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewPart* baseFeat): m_basePage = m_baseFeat->findParentPage(); //it is possible that the basePage could be unparented and have no corresponding Page if (!m_basePage) { - Base::Console().Error("TaskDetail - bad parameters - base page. Can not proceed.\n"); + Base::Console().error("TaskDetail - bad parameters - base page. Can not proceed.\n"); return; } @@ -146,7 +146,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): { if (!m_detailFeat) { //should be caught in CMD caller - Base::Console().Error("TaskDetail - bad parameters. Can not proceed.\n"); + Base::Console().error("TaskDetail - bad parameters. Can not proceed.\n"); return; } @@ -163,7 +163,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): if (m_baseFeat) { m_baseName = m_baseFeat->getNameInDocument(); } else { - Base::Console().Error("TaskDetail - no BaseView. Can not proceed.\n"); + Base::Console().error("TaskDetail - no BaseView. Can not proceed.\n"); return; } @@ -219,7 +219,7 @@ void TaskDetail::changeEvent(QEvent *e) //save the start conditions void TaskDetail::saveDetailState() { -// Base::Console().Message("TD::saveDetailState()\n"); +// Base::Console().message("TD::saveDetailState()\n"); TechDraw::DrawViewDetail* dvd = getDetailFeat(); m_saveAnchor = dvd->AnchorPoint.getValue(); m_saveRadius = dvd->Radius.getValue(); @@ -228,7 +228,7 @@ void TaskDetail::saveDetailState() void TaskDetail::restoreDetailState() { -// Base::Console().Message("TD::restoreDetailState()\n"); +// Base::Console().message("TD::restoreDetailState()\n"); TechDraw::DrawViewDetail* dvd = getDetailFeat(); dvd->AnchorPoint.setValue(m_saveAnchor); dvd->Radius.setValue(m_saveRadius); @@ -238,7 +238,7 @@ void TaskDetail::restoreDetailState() void TaskDetail::setUiFromFeat() { -// Base::Console().Message("TD::setUIFromFeat()\n"); +// Base::Console().message("TD::setUIFromFeat()\n"); if (m_baseFeat) { std::string baseName = getBaseFeat()->getNameInDocument(); ui->leBaseView->setText(QString::fromStdString(baseName)); @@ -364,9 +364,9 @@ void TaskDetail::onDraggerClicked(bool clicked) void TaskDetail::editByHighlight() { -// Base::Console().Message("TD::editByHighlight()\n"); +// Base::Console().message("TD::editByHighlight()\n"); if (!m_ghost) { - Base::Console().Error("TaskDetail::editByHighlight - no ghost object\n"); + Base::Console().error("TaskDetail::editByHighlight - no ghost object\n"); return; } @@ -382,7 +382,7 @@ void TaskDetail::editByHighlight() //dragEnd is in scene coords. void TaskDetail::onHighlightMoved(QPointF dragEnd) { -// Base::Console().Message("TD::onHighlightMoved(%s) - highlight: %X\n", +// Base::Console().message("TD::onHighlightMoved(%s) - highlight: %X\n", // DrawUtil::formatVector(dragEnd).c_str(), m_ghost); ui->pbDragger->setEnabled(true); @@ -395,7 +395,7 @@ void TaskDetail::onHighlightMoved(QPointF dragEnd) if (dpgi) { DrawProjGroup* dpg = dpgi->getPGroup(); if (!dpg) { - Base::Console().Message("TD::getAnchorScene - projection group is confused\n"); + Base::Console().message("TD::getAnchorScene - projection group is confused\n"); //TODO::throw something. return; } @@ -430,7 +430,7 @@ void TaskDetail::enableTaskButtons(bool button) //***** Feature create & edit stuff ******************************************* void TaskDetail::createDetail() { -// Base::Console().Message("TD::createDetail()\n"); +// Base::Console().message("TD::createDetail()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create Detail View")); const std::string objectName{"Detail"}; @@ -471,7 +471,7 @@ void TaskDetail::createDetail() void TaskDetail::updateDetail() { -// Base::Console().Message("TD::updateDetail()\n"); +// Base::Console().message("TD::updateDetail()\n"); try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update Detail")); double x = ui->qsbX->rawValue(); @@ -494,7 +494,7 @@ void TaskDetail::updateDetail() } catch (...) { //this is probably due to appl closing while dialog is still open - Base::Console().Error("Task Detail - detail feature update failed.\n"); + Base::Console().error("Task Detail - detail feature update failed.\n"); } } @@ -520,7 +520,7 @@ QPointF TaskDetail::getAnchorScene() DrawProjGroup* dpg = dpgi->getPGroup(); if (!dpg) { - Base::Console().Message("TD::getAnchorScene - projection group is confused\n"); + Base::Console().message("TD::getAnchorScene - projection group is confused\n"); //TODO::throw something. return QPointF(0.0, 0.0); } @@ -541,7 +541,7 @@ QPointF TaskDetail::getAnchorScene() // protects against stale pointers DrawViewPart* TaskDetail::getBaseFeat() { -// Base::Console().Message("TD::getBaseFeat()\n"); +// Base::Console().message("TD::getBaseFeat()\n"); if (m_doc) { App::DocumentObject* baseObj = m_doc->getObject(m_baseName.c_str()); @@ -560,7 +560,7 @@ DrawViewPart* TaskDetail::getBaseFeat() // protects against stale pointers DrawViewDetail* TaskDetail::getDetailFeat() { -// Base::Console().Message("TD::getDetailFeat()\n"); +// Base::Console().message("TD::getDetailFeat()\n"); if (m_baseFeat) { App::DocumentObject* detailObj = m_baseFeat->getDocument()->getObject(m_detailName.c_str()); @@ -581,7 +581,7 @@ DrawViewDetail* TaskDetail::getDetailFeat() bool TaskDetail::accept() { -// Base::Console().Message("TD::accept()\n"); +// Base::Console().message("TD::accept()\n"); Gui::Document* doc = Gui::Application::Instance->getDocument(m_basePage->getDocument()); if (!doc) @@ -597,7 +597,7 @@ bool TaskDetail::accept() bool TaskDetail::reject() { -// Base::Console().Message("TD::reject()\n"); +// Base::Console().message("TD::reject()\n"); Gui::Document* doc = Gui::Application::Instance->getDocument(m_basePage->getDocument()); if (!doc) return false; diff --git a/src/Mod/TechDraw/Gui/TaskDimension.cpp b/src/Mod/TechDraw/Gui/TaskDimension.cpp index 1b745307f7..8774948efd 100644 --- a/src/Mod/TechDraw/Gui/TaskDimension.cpp +++ b/src/Mod/TechDraw/Gui/TaskDimension.cpp @@ -269,7 +269,7 @@ void TaskDimension::onArbitraryChanged() void TaskDimension::onFormatSpecifierOverToleranceChanged() { -// Base::Console().Message("TD::onFormatSpecifierOverToleranceChanged()\n"); +// Base::Console().message("TD::onFormatSpecifierOverToleranceChanged()\n"); // if (m_blockToleranceLoop) { return; } m_parent->getDimFeat()->FormatSpecOverTolerance.setValue(ui->leFormatSpecifierOverTolerance->text().toUtf8().constData()); if (ui->cbArbitraryTolerances->isChecked() ) { @@ -288,7 +288,7 @@ void TaskDimension::onFormatSpecifierOverToleranceChanged() void TaskDimension::onFormatSpecifierUnderToleranceChanged() { -// Base::Console().Message("TD::onFormatSpecifierUnderToleranceChanged()\n"); +// Base::Console().message("TD::onFormatSpecifierUnderToleranceChanged()\n"); m_parent->getDimFeat()->FormatSpecUnderTolerance.setValue(ui->leFormatSpecifierUnderTolerance->text().toUtf8().constData()); if (ui->cbArbitraryTolerances->isChecked() ) { // Don't do anything else if tolerance is Arbitrary diff --git a/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp b/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp index cfa5ea99cc..5069c27905 100644 --- a/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp +++ b/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp @@ -70,7 +70,7 @@ void TaskGeomHatch::initUi() if (nameIndex > -1) { ui->cbName->setCurrentIndex(nameIndex); } else { - Base::Console().Warning("Warning - Pattern name *%s* not found in current PAT File\n", m_name.c_str()); + Base::Console().warning("Warning - Pattern name *%s* not found in current PAT File\n", m_name.c_str()); } connect(ui->cbName, qOverload(&QComboBox::currentIndexChanged), this, &TaskGeomHatch::onNameChanged); @@ -152,7 +152,7 @@ void TaskGeomHatch::onColorChanged() bool TaskGeomHatch::accept() { -// Base::Console().Message("TGH::accept()\n"); +// Base::Console().message("TGH::accept()\n"); updateValues(); Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); m_hatch->recomputeFeature(); //create the hatch lines @@ -204,7 +204,7 @@ void TaskGeomHatch::getParameters() //move values from screen to DocObjs void TaskGeomHatch::updateValues() { -// Base::Console().Message("TGH::updateValues()\n"); +// Base::Console().message("TGH::updateValues()\n"); m_file = (ui->fcFile->fileName()).toUtf8().constData(); m_hatch->FilePattern.setValue(m_file); QString cText = ui->cbName->currentText(); diff --git a/src/Mod/TechDraw/Gui/TaskHatch.cpp b/src/Mod/TechDraw/Gui/TaskHatch.cpp index 78f84ed89f..7affb47ef8 100644 --- a/src/Mod/TechDraw/Gui/TaskHatch.cpp +++ b/src/Mod/TechDraw/Gui/TaskHatch.cpp @@ -72,7 +72,7 @@ TaskHatch::TaskHatch(TechDrawGui::ViewProviderHatch* inVp) : ui(new Ui_TaskHatch), m_vp(inVp) { -// Base::Console().Message("TH::TH() - edit\n"); +// Base::Console().message("TH::TH() - edit\n"); ui->setupUi(this); m_hatch = m_vp->getViewObject(); App::DocumentObject* obj = m_hatch->Source.getValue(); @@ -131,7 +131,7 @@ void TaskHatch::saveHatchState() //restore the start conditions void TaskHatch::restoreHatchState() { -// Base::Console().Message("TH::restoreHatchState()\n"); +// Base::Console().message("TH::restoreHatchState()\n"); if (m_hatch) { m_hatch->HatchPattern.setValue(m_saveFile); m_vp->HatchScale.setValue(m_saveScale); @@ -175,7 +175,7 @@ void TaskHatch::onOffsetChanged() void TaskHatch::apply(bool forceUpdate) { Q_UNUSED(forceUpdate) -// Base::Console().Message("TH::apply() - m_hatch: %X\n", m_hatch); +// Base::Console().message("TH::apply() - m_hatch: %X\n", m_hatch); if (!m_hatch) { createHatch(); } @@ -192,7 +192,7 @@ void TaskHatch::apply(bool forceUpdate) void TaskHatch::createHatch() { -// Base::Console().Message("TH::createHatch()\n"); +// Base::Console().message("TH::createHatch()\n"); App::Document* doc = m_dvp->getDocument(); // TODO: the structured label for Hatch (and GeomHatch) should be retired. @@ -226,14 +226,14 @@ void TaskHatch::createHatch() Base::Vector3d offset(ui->dsbOffsetX->value(), ui->dsbOffsetY->value(), 0.0); m_vp->HatchOffset.setValue(offset); } else { - Base::Console().Error("TaskHatch - Hatch has no ViewProvider\n"); + Base::Console().error("TaskHatch - Hatch has no ViewProvider\n"); } Command::commitCommand(); } void TaskHatch::updateHatch() { -// Base::Console().Message("TH::updateHatch()\n"); +// Base::Console().message("TH::updateHatch()\n"); std::string FeatName = m_hatch->getNameInDocument(); Command::openCommand(QT_TRANSLATE_NOOP("Command", "Update Hatch")); @@ -256,7 +256,7 @@ void TaskHatch::updateHatch() bool TaskHatch::accept() { -// Base::Console().Message("TH::accept()\n"); +// Base::Console().message("TH::accept()\n"); apply(true); Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); @@ -266,7 +266,7 @@ bool TaskHatch::accept() bool TaskHatch::reject() { -// Base::Console().Message("TH::reject()\n"); +// Base::Console().message("TH::reject()\n"); restoreHatchState(); Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); return false; diff --git a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp index 63639bd15f..aa649c099f 100644 --- a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp @@ -87,7 +87,7 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : m_basePage = m_lineFeat->findParentPage(); if (!m_basePage) { - Base::Console().Error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); + Base::Console().error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); return; } App::DocumentObject* obj = m_lineFeat->LeaderParent.getValue(); @@ -108,7 +108,7 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : //TODO: when/if leaders are allowed to be parented to Page, check for m_baseFeat will be removed if (!m_baseFeat || !m_basePage) { - Base::Console().Error("TaskLeaderLine - bad parameters (2). Can not proceed.\n"); + Base::Console().error("TaskLeaderLine - bad parameters (2). Can not proceed.\n"); return; } @@ -420,16 +420,16 @@ void TaskLeaderLine::createLeaderFeature(std::vector sceneDeltas void TaskLeaderLine::dumpTrackerPoints(std::vector& tPoints) const { - Base::Console().Message("TTL::dumpTrackerPoints(%d)\n", tPoints.size()); - Base::Console().Message("TTL::dumpTrackerPoints - attach point: %s\n", DU::formatVector(m_attachPoint).c_str()); + Base::Console().message("TTL::dumpTrackerPoints(%d)\n", tPoints.size()); + Base::Console().message("TTL::dumpTrackerPoints - attach point: %s\n", DU::formatVector(m_attachPoint).c_str()); for (auto& point : tPoints) { - Base::Console().Message("TTL::dumpTrackerPoints - a point: %s\n", DU::formatVector(point).c_str()); + Base::Console().message("TTL::dumpTrackerPoints - a point: %s\n", DU::formatVector(point).c_str()); } } void TaskLeaderLine::updateLeaderFeature() { -// Base::Console().Message("TTL::updateLeaderFeature()\n"); +// Base::Console().message("TTL::updateLeaderFeature()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit Leader")); //waypoints & x, y are updated by QGILeaderLine (for edits only!) commonFeatureUpdate(); @@ -458,7 +458,7 @@ void TaskLeaderLine::commonFeatureUpdate() void TaskLeaderLine::removeFeature() { -// Base::Console().Message("TTL::removeFeature()\n"); +// Base::Console().message("TTL::removeFeature()\n"); if (!m_lineFeat) { return; } @@ -472,7 +472,7 @@ void TaskLeaderLine::removeFeature() m_lineFeat->getNameInDocument()); } catch (...) { - Base::Console().Message("TTL::removeFeature - failed to delete feature\n"); + Base::Console().message("TTL::removeFeature - failed to delete feature\n"); return; } } else { @@ -488,7 +488,7 @@ void TaskLeaderLine::onTrackerClicked(bool clicked) { Q_UNUSED(clicked); if (!m_vpp->getMDIViewPage()) { - Base::Console().Message("TLL::onTrackerClicked - no Mdi, no Tracker!\n"); + Base::Console().message("TLL::onTrackerClicked - no Mdi, no Tracker!\n"); return; } @@ -557,7 +557,7 @@ void TaskLeaderLine::onTrackerClicked(bool clicked) if (!qgLead) { //tarfu - Base::Console().Error("TaskLeaderLine - can't find leader graphic\n"); + Base::Console().error("TaskLeaderLine - can't find leader graphic\n"); //now what? throw will generate "unknown unhandled exception" } else { m_qgLeader = qgLead; @@ -595,7 +595,7 @@ void TaskLeaderLine::onTrackerClicked(bool clicked) void TaskLeaderLine::startTracker() { -// Base::Console().Message("TTL::startTracker()\n"); +// Base::Console().message("TTL::startTracker()\n"); if (!m_vpp->getQGSPage()) { return; } @@ -624,9 +624,9 @@ void TaskLeaderLine::onTrackerFinished(std::vector trackerScenePoints, { //in this case, we already know who the parent is. We don't need QGTracker to tell us. (void) qgParent; - // Base::Console().Message("TTL::onTrackerFinished() - parent: %X\n", qgParent); + // Base::Console().message("TTL::onTrackerFinished() - parent: %X\n", qgParent); if (trackerScenePoints.empty()) { - Base::Console().Error("TaskLeaderLine - no points available\n"); + Base::Console().error("TaskLeaderLine - no points available\n"); return; } @@ -636,7 +636,7 @@ void TaskLeaderLine::onTrackerFinished(std::vector trackerScenePoints, m_attachPoint = Base::Vector3d(mapped.x(), mapped.y(), 0.0); m_sceneDeltas = scenePointsToDeltas(trackerScenePoints); } else { - Base::Console().Message("TTL::onTrackerFinished - can't find parent graphic!\n"); + Base::Console().message("TTL::onTrackerFinished - can't find parent graphic!\n"); //blow up!? throw Base::RuntimeError("TaskLeaderLine - can not find parent graphic"); } @@ -663,7 +663,7 @@ void TaskLeaderLine::onTrackerFinished(std::vector trackerScenePoints, // this is called at every possible exit path? void TaskLeaderLine::removeTracker() { -// Base::Console().Message("TTL::removeTracker()\n"); +// Base::Console().message("TTL::removeTracker()\n"); if (!m_vpp->getQGSPage()) { return; } @@ -677,7 +677,7 @@ void TaskLeaderLine::removeTracker() void TaskLeaderLine::onCancelEditClicked(bool clicked) { Q_UNUSED(clicked); -// Base::Console().Message("TTL::onCancelEditClicked() m_pbTrackerState: %d\n", +// Base::Console().message("TTL::onCancelEditClicked() m_pbTrackerState: %d\n", // m_pbTrackerState); abandonEditSession(); if (m_lineFeat) { @@ -752,7 +752,7 @@ std::vector TaskLeaderLine::scenePointsToDeltas(std::vectorgetDocument(m_partFeat->getDocument()); if (!doc) return false; @@ -247,7 +247,7 @@ bool TaskLineDecor::accept() bool TaskLineDecor::reject() { -// Base::Console().Message("TLD::reject()\n"); +// Base::Console().message("TLD::reject()\n"); Gui::Document* doc = Gui::Application::Instance->getDocument(m_partFeat->getDocument()); if (!doc) return false; @@ -308,7 +308,7 @@ void TaskRestoreLines::initUi() void TaskRestoreLines::onAllPressed() { -// Base::Console().Message("TRL::onAllPressed()\n"); +// Base::Console().message("TRL::onAllPressed()\n"); onGeometryPressed(); onCosmeticPressed(); onCenterPressed(); @@ -316,7 +316,7 @@ void TaskRestoreLines::onAllPressed() void TaskRestoreLines::onGeometryPressed() { -// Base::Console().Message("TRL::onGeometryPressed()\n"); +// Base::Console().message("TRL::onGeometryPressed()\n"); restoreInvisibleGeoms(); ui->l_Geometry->setText(QString::number(0)); ui->l_All->setText(QString::number(countInvisibleLines())); @@ -324,7 +324,7 @@ void TaskRestoreLines::onGeometryPressed() void TaskRestoreLines::onCosmeticPressed() { -// Base::Console().Message("TRL::onCosmeticPressed()\n"); +// Base::Console().message("TRL::onCosmeticPressed()\n"); restoreInvisibleCosmetics(); ui->l_Cosmetic->setText(QString::number(0)); ui->l_All->setText(QString::number(countInvisibleLines())); @@ -332,7 +332,7 @@ void TaskRestoreLines::onCosmeticPressed() void TaskRestoreLines::onCenterPressed() { -// Base::Console().Message("TRL::onCenterPressed()\n"); +// Base::Console().message("TRL::onCenterPressed()\n"); restoreInvisibleCenters(); ui->l_Center->setText(QString::number(0)); ui->l_All->setText(QString::number(countInvisibleLines())); @@ -429,13 +429,13 @@ void TaskRestoreLines::restoreInvisibleCenters() bool TaskRestoreLines::accept() { -// Base::Console().Message("TRL::accept()\n"); +// Base::Console().message("TRL::accept()\n"); return true; } bool TaskRestoreLines::reject() { -// Base::Console().Message("TRL::reject()\n"); +// Base::Console().message("TRL::reject()\n"); return false; } @@ -487,14 +487,14 @@ void TaskDlgLineDecor::clicked(int i) bool TaskDlgLineDecor::accept() { -// Base::Console().Message("TDLD::accept()\n"); +// Base::Console().message("TDLD::accept()\n"); widget->accept(); return true; } bool TaskDlgLineDecor::reject() { -// Base::Console().Message("TDLD::reject()\n"); +// Base::Console().message("TDLD::reject()\n"); widget->reject(); return true; } diff --git a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp index 6f3aede92a..afc00010a9 100644 --- a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp +++ b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp @@ -215,23 +215,23 @@ void TaskLinkDim::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem Q_UNUSED(current); Q_UNUSED(previous); // if (previous) { -// Base::Console().Message("TRACE - TLD::onCurrent - text: %s data: %s is previous\n", +// Base::Console().message("TRACE - TLD::onCurrent - text: %s data: %s is previous\n", // qPrintable(previous->text(0)), qPrintable(previous->data(0, Qt::UserRole).toString())); // if (previous->treeWidget() == ui->selector->selectedTreeWidget()) { -// Base::Console().Message("TRACE - TLD::onCurrent - previous belongs to selected\n"); +// Base::Console().message("TRACE - TLD::onCurrent - previous belongs to selected\n"); // } // if (previous->treeWidget() == ui->selector->availableTreeWidget()) { -// Base::Console().Message("TRACE - TLD::onCurrent - previous belongs to available\n"); +// Base::Console().message("TRACE - TLD::onCurrent - previous belongs to available\n"); // } // } // if (current) { -// Base::Console().Message("TRACE - TLD::onCurrent - text: %s data: %s is current\n", +// Base::Console().message("TRACE - TLD::onCurrent - text: %s data: %s is current\n", // qPrintable(current->text(0)), qPrintable(current->data(0, Qt::UserRole).toString())); // if (current->treeWidget() == ui->selector->selectedTreeWidget()) { -// Base::Console().Message("TRACE - TLD::onCurrent - current belongs to selected\n"); +// Base::Console().message("TRACE - TLD::onCurrent - current belongs to selected\n"); // } // if (current->treeWidget() == ui->selector->availableTreeWidget()) { -// Base::Console().Message("TRACE - TLD::onCurrent - current belongs to available\n"); +// Base::Console().message("TRACE - TLD::onCurrent - current belongs to available\n"); // } // } } diff --git a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp index 2ae4c86b6e..831f10be24 100644 --- a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp @@ -75,7 +75,7 @@ TaskRichAnno::TaskRichAnno(TechDrawGui::ViewProviderRichAnno* annoVP) : m_basePage = m_annoFeat->findParentPage(); if (!m_basePage) { - Base::Console().Error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); + Base::Console().error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); return; } @@ -160,7 +160,7 @@ void TaskRichAnno::changeEvent(QEvent *event) void TaskRichAnno::setUiPrimary() { -// Base::Console().Message("TRA::setUiPrimary()\n"); +// Base::Console().message("TRA::setUiPrimary()\n"); enableVPUi(false); setWindowTitle(m_title); @@ -198,7 +198,7 @@ void TaskRichAnno::enableVPUi(bool enable) void TaskRichAnno::setUiEdit() { -// Base::Console().Message("TRA::setUiEdit()); +// Base::Console().message("TRA::setUiEdit()); enableVPUi(true); setWindowTitle(m_title); enableTextUi(true); @@ -224,7 +224,7 @@ void TaskRichAnno::setUiEdit() void TaskRichAnno::onEditorClicked(bool clicked) { -// Base::Console().Message("TL::onEditorClicked(%d)\n", b); +// Base::Console().message("TL::onEditorClicked(%d)\n", b); Q_UNUSED(clicked); m_textDialog = new QDialog(nullptr); QString leadText = ui->teAnnoText->toHtml(); @@ -278,7 +278,7 @@ Base::Color TaskRichAnno::prefLineColor() //****************************************************************************** void TaskRichAnno::createAnnoFeature() { -// Base::Console().Message("TRA::createAnnoFeature()"); +// Base::Console().message("TRA::createAnnoFeature()"); const std::string objectName{QT_TR_NOOP("RichTextAnnotation")}; std::string annoName = m_basePage->getDocument()->getUniqueObjectName(objectName.c_str()); std::string generatedSuffix {annoName.substr(objectName.length())}; @@ -347,7 +347,7 @@ void TaskRichAnno::createAnnoFeature() void TaskRichAnno::updateAnnoFeature() { -// Base::Console().Message("TRA::updateAnnoFeature()\n"); +// Base::Console().message("TRA::updateAnnoFeature()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit Anno")); commonFeatureUpdate(); Base::Color ac; @@ -362,7 +362,7 @@ void TaskRichAnno::updateAnnoFeature() void TaskRichAnno::commonFeatureUpdate() { -// Base::Console().Message("TRA::commonFeatureUpdate()\n"); +// Base::Console().message("TRA::commonFeatureUpdate()\n"); m_annoFeat->setPosition(Rez::appX(m_attachPoint.x), Rez::appX(- m_attachPoint.y), true); m_annoFeat->AnnoText.setValue(ui->teAnnoText->toHtml().toUtf8()); m_annoFeat->MaxWidth.setValue(ui->dsbMaxWidth->value().getValue()); @@ -371,7 +371,7 @@ void TaskRichAnno::commonFeatureUpdate() void TaskRichAnno::removeFeature() { -// Base::Console().Message("TRA::removeFeature()\n"); +// Base::Console().message("TRA::removeFeature()\n"); if (!m_annoFeat) return; @@ -385,7 +385,7 @@ void TaskRichAnno::removeFeature() m_annoFeat->getNameInDocument()); } catch (...) { - Base::Console().Warning("TRA::removeFeature - failed to delete feature\n"); + Base::Console().warning("TRA::removeFeature - failed to delete feature\n"); return; } } else { @@ -401,7 +401,7 @@ void TaskRichAnno::removeFeature() QPointF TaskRichAnno::calcTextStartPos(double scale) { Q_UNUSED(scale) -// Base::Console().Message("TRA::calcTextStartPos(%.3f)\n", scale); +// Base::Console().message("TRA::calcTextStartPos(%.3f)\n", scale); double textWidth = 100.0; double textHeight = 20.0; double horizGap(20.0); @@ -419,17 +419,17 @@ QPointF TaskRichAnno::calcTextStartPos(double scale) TechDraw::DrawLeaderLine* dll = static_cast(m_baseFeat); points = dll->WayPoints.getValues(); } else { -// Base::Console().Message("TRA::calcTextPos - m_baseFeat is not Leader\n"); +// Base::Console().message("TRA::calcTextPos - m_baseFeat is not Leader\n"); return QPointF(0.0, 0.0); } } else { -// Base::Console().Message("TRA::calcStartPos - no m_baseFeat\n"); +// Base::Console().message("TRA::calcStartPos - no m_baseFeat\n"); if (m_basePage) { double w = Rez::guiX(m_basePage->getPageWidth() / 2.0); double h = Rez::guiX(m_basePage->getPageHeight() / 2.0); return QPointF(w, h); } else { - Base::Console().Message("TRA::calcStartPos - no m_basePage\n"); //shouldn't happen. caught elsewhere + Base::Console().message("TRA::calcStartPos - no m_basePage\n"); //shouldn't happen. caught elsewhere } } @@ -466,9 +466,9 @@ void TaskRichAnno::enableTaskButtons(bool enable) bool TaskRichAnno::accept() { -// Base::Console().Message("TRA::accept()\n"); +// Base::Console().message("TRA::accept()\n"); if (m_inProgressLock) { -// Base::Console().Message("TRA::accept - edit in progress!!\n"); +// Base::Console().message("TRA::accept - edit in progress!!\n"); //TODO: kill MRTE dialog? return true; } @@ -492,9 +492,9 @@ bool TaskRichAnno::accept() bool TaskRichAnno::reject() { -// Base::Console().Message("TRA::reject()\n"); +// Base::Console().message("TRA::reject()\n"); if (m_inProgressLock) { -// Base::Console().Message("TRA::reject - edit in progress!!\n"); +// Base::Console().message("TRA::reject - edit in progress!!\n"); return false; } diff --git a/src/Mod/TechDraw/Gui/TaskSectionView.cpp b/src/Mod/TechDraw/Gui/TaskSectionView.cpp index 7a98c2f53f..735bab1506 100644 --- a/src/Mod/TechDraw/Gui/TaskSectionView.cpp +++ b/src/Mod/TechDraw/Gui/TaskSectionView.cpp @@ -437,7 +437,7 @@ bool TaskSectionView::apply(bool forceUpdate) //this should never happen std::string msg = tr("Nothing to apply. No section direction picked yet").toStdString(); - Base::Console().Error((msg + "\n").c_str()); + Base::Console().error((msg + "\n").c_str()); return false; } if (!m_section) { diff --git a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp index 7bb0cd3d64..015e2b796b 100644 --- a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp +++ b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp @@ -96,7 +96,7 @@ TaskWeldingSymbol::TaskWeldingSymbol(TechDraw::DrawWeldSymbol* weld) : App::DocumentObject* obj = m_weldFeat->Leader.getValue(); if (!obj || !obj->isDerivedFrom() ) { - Base::Console().Error("TaskWeldingSymbol - no leader for welding symbol. Can not proceed.\n"); + Base::Console().error("TaskWeldingSymbol - no leader for welding symbol. Can not proceed.\n"); return; } @@ -162,7 +162,7 @@ void TaskWeldingSymbol::changeEvent(QEvent *event) void TaskWeldingSymbol::setUiPrimary() { -// Base::Console().Message("TWS::setUiPrimary()\n"); +// Base::Console().message("TWS::setUiPrimary()\n"); setWindowTitle(QObject::tr("Create Welding Symbol")); m_currDir = PreferencesGui::weldingDirectory(); ui->fcSymbolDir->setFileName(m_currDir); @@ -181,7 +181,7 @@ void TaskWeldingSymbol::setUiPrimary() void TaskWeldingSymbol::setUiEdit() { -// Base::Console().Message("TWS::setUiEdit()\n"); +// Base::Console().message("TWS::setUiEdit()\n"); setWindowTitle(QObject::tr("Edit Welding Symbol")); m_currDir = PreferencesGui::weldingDirectory(); @@ -370,14 +370,14 @@ void TaskWeldingSymbol::onWeldingChanged() void TaskWeldingSymbol::onDirectorySelected(const QString& newDir) { -// Base::Console().Message("TWS::onDirectorySelected(%s)\n", qPrintable(newDir)); +// Base::Console().message("TWS::onDirectorySelected(%s)\n", qPrintable(newDir)); m_currDir = newDir + QStringLiteral("/"); } void TaskWeldingSymbol::onSymbolSelected(QString symbolPath, QString source) { -// Base::Console().Message("TWS::onSymbolSelected(%s) - source: %s\n", +// Base::Console().message("TWS::onSymbolSelected(%s) - source: %s\n", // qPrintable(symbolPath), qPrintable(source)); QIcon targetIcon(symbolPath); QSize iconSize(32, 32); @@ -399,7 +399,7 @@ void TaskWeldingSymbol::onSymbolSelected(QString symbolPath, void TaskWeldingSymbol::collectArrowData() { -// Base::Console().Message("TWS::collectArrowData()\n"); +// Base::Console().message("TWS::collectArrowData()\n"); m_arrowOut.toBeSaved = true; m_arrowOut.arrowSide = false; m_arrowOut.row = 0; @@ -413,7 +413,7 @@ void TaskWeldingSymbol::collectArrowData() void TaskWeldingSymbol::collectOtherData() { -// Base::Console().Message("TWS::collectOtherData()\n"); +// Base::Console().message("TWS::collectOtherData()\n"); m_otherOut.toBeSaved = true; m_otherOut.arrowSide = false; m_otherOut.row = -1; @@ -427,7 +427,7 @@ void TaskWeldingSymbol::collectOtherData() void TaskWeldingSymbol::getTileFeats() { -// Base::Console().Message("TWS::getTileFeats()\n"); +// Base::Console().message("TWS::getTileFeats()\n"); std::vector tiles = m_weldFeat->getTiles(); m_arrowFeat = nullptr; m_otherFeat = nullptr; @@ -455,7 +455,7 @@ void TaskWeldingSymbol::getTileFeats() //****************************************************************************** TechDraw::DrawWeldSymbol* TaskWeldingSymbol::createWeldingSymbol() { -// Base::Console().Message("TWS::createWeldingSymbol()\n"); +// Base::Console().message("TWS::createWeldingSymbol()\n"); App::Document *doc = Application::Instance->activeDocument()->getDocument(); auto weldSymbol = doc->addObject("WeldSymbol"); if (!weldSymbol) { @@ -486,11 +486,11 @@ void TaskWeldingSymbol::updateWeldingSymbol() void TaskWeldingSymbol::updateTiles() { -// Base::Console().Message("TWS::updateTiles()\n"); +// Base::Console().message("TWS::updateTiles()\n"); getTileFeats(); if (!m_arrowFeat) { - Base::Console().Message("TWS::updateTiles - no arrow tile!\n"); + Base::Console().message("TWS::updateTiles - no arrow tile!\n"); } else { collectArrowData(); if (m_arrowOut.toBeSaved) { @@ -514,7 +514,7 @@ void TaskWeldingSymbol::updateTiles() } if (!m_otherFeat) { -// Base::Console().Message("TWS::updateTiles - no other tile!\n"); +// Base::Console().message("TWS::updateTiles - no other tile!\n"); } else { if (m_otherDirty) { collectOtherData(); @@ -556,7 +556,7 @@ void TaskWeldingSymbol::enableTaskButtons(bool enable) bool TaskWeldingSymbol::accept() { -// Base::Console().Message("TWS::accept()\n"); +// Base::Console().message("TWS::accept()\n"); if (m_createMode) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create WeldSymbol")); m_weldFeat = createWeldingSymbol(); @@ -572,7 +572,7 @@ bool TaskWeldingSymbol::accept() updateTiles(); } catch (...) { - Base::Console().Error("TWS::accept - failed to update symbol\n"); + Base::Console().error("TWS::accept - failed to update symbol\n"); } Gui::Command::updateActive(); @@ -587,7 +587,7 @@ bool TaskWeldingSymbol::accept() bool TaskWeldingSymbol::reject() { -// Base::Console().Message("TWS::reject()\n"); +// Base::Console().message("TWS::reject()\n"); //nothing to remove. Gui::Command::doCommand(Gui::Command::Gui, "App.activeDocument().recompute()"); diff --git a/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp b/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp index 1c5f952823..384f998e67 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp @@ -172,7 +172,7 @@ bool ViewProviderBalloon::canDelete(App::DocumentObject *obj) const bool ViewProviderBalloon::onDelete(const std::vector & parms) { Q_UNUSED(parms) -// Base::Console().Message("VPB::onDelete() - parms: %d\n", parms.size()); +// Base::Console().message("VPB::onDelete() - parms: %d\n", parms.size()); if (Gui::Control().activeDialog()) { // TODO: make this selective so only a dialog involving this vp's // feature is blocked. As is, this will prevent deletion during any diff --git a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp index c04bef344f..23813978a3 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp @@ -39,6 +39,8 @@ #include #include +#include +#include #include #include "ViewProviderDrawingView.h" @@ -57,7 +59,7 @@ PROPERTY_SOURCE(TechDrawGui::ViewProviderDrawingView, Gui::ViewProviderDocumentO ViewProviderDrawingView::ViewProviderDrawingView() : m_myName(std::string()) { -// Base::Console().Message("VPDV::VPDV\n"); +// Base::Console().message("VPDV::VPDV\n"); initExtension(this); sPixmap = "TechDraw_TreeView"; @@ -78,7 +80,7 @@ ViewProviderDrawingView::~ViewProviderDrawingView() void ViewProviderDrawingView::attach(App::DocumentObject *pcFeat) { -// Base::Console().Message("VPDV::attach(%s)\n", pcFeat->getNameInDocument()); +// Base::Console().message("VPDV::attach(%s)\n", pcFeat->getNameInDocument()); ViewProviderDocumentObject::attach(pcFeat); //NOLINTBEGIN @@ -99,7 +101,7 @@ void ViewProviderDrawingView::attach(App::DocumentObject *pcFeat) // but parent page might. we may not be part of the document yet though! // :( we're not part of the page yet either! } else { - Base::Console().Warning("VPDV::attach has no Feature!\n"); + Base::Console().warning("VPDV::attach has no Feature!\n"); } } @@ -293,7 +295,7 @@ Gui::MDIView *ViewProviderDrawingView::getMDIView() const void ViewProviderDrawingView::onGuiRepaint(const TechDraw::DrawView* dv) { -// Base::Console().Message("VPDV::onGuiRepaint(%s) - this: %x\n", dv->getNameInDocument(), this); +// Base::Console().message("VPDV::onGuiRepaint(%s) - this: %x\n", dv->getNameInDocument(), this); Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); if (!guiDoc) return; @@ -366,12 +368,12 @@ void ViewProviderDrawingView::showProgressMessage(const std::string featureName, .arg(QString::fromStdString(featureName), QString::fromStdString(text)); if (Gui::getMainWindow()) { - //neither of these work! Base::Console().Message() output preempts these messages?? + //neither of these work! Base::Console().message() output preempts these messages?? // Gui::getMainWindow()->showMessage(msg, 3000); // Gui::getMainWindow()->showStatus(Gui::MainWindow::Msg, msg); //Temporary implementation. This works, but the messages are queued up and //not displayed in the report window in real time?? - Base::Console().Message("%s\n", qPrintable(msg)); + Base::Console().message("%s\n", qPrintable(msg)); } } @@ -477,3 +479,55 @@ TechDraw::DrawView* ViewProviderDrawingView::getViewObject() const { return dynamic_cast(pcObject); } + + +//! it can happen that child graphic items can lose their parent item if the +//! the parent is deleted, then undo is invoked. The linkages on the App side are +//! handled by the undo mechanism, but the QGraphicsScene parentage is not reset. +void ViewProviderDrawingView::fixSceneDependencies() +{ + Base::Console().message("VPDV::fixSceneDependencies()\n"); + auto page = getViewProviderPage(); + if (!page) { + return; + } + + auto scene = page->getQGSPage(); + auto ourQView = getQView(); + + // this is the logic for items other than Dimensions and Balloons + auto children = getViewObject()->getUniqueChildren(); + for (auto& child : children) { + if (child->isDerivedFrom() || + child->isDerivedFrom() ) { + // these are handled by ViewProviderViewPart + continue; + } + auto* childQView = scene->findQViewForDocObj(child); + auto* childGraphicParent = scene->findParent(childQView); + if (childGraphicParent != ourQView) { + scene->addItemToParent(childQView, ourQView); + } + } +} + + +std::vector ViewProviderDrawingView::claimChildren() const +{ + std::vector temp; + const std::vector &potentialChildren = getViewObject()->getInList(); + try { + for(auto& child : potentialChildren) { + auto* view = freecad_cast(child); + if (view && view->claimParent() == getViewObject()) { + temp.push_back(view); + continue; + } + } + } + catch (...) { + return {}; + } + return temp; +} + diff --git a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h index 1ea582d749..195026c57d 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h +++ b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h @@ -99,6 +99,10 @@ public: const char* whoAmI() const; + virtual void fixSceneDependencies(); + std::vector claimChildren() const override; + + private: void multiParentPaint(std::vector& pages); void singleParentPaint(const TechDraw::DrawView* dv); diff --git a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp index f604b4eabb..fcd471d082 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp @@ -79,7 +79,7 @@ ViewProviderLeader::ViewProviderLeader() bool ViewProviderLeader::setEdit(int ModNum) { -// Base::Console().Message("VPL::setEdit(%d)\n", ModNum); +// Base::Console().message("VPL::setEdit(%d)\n", ModNum); if (ModNum != ViewProvider::Default) { return ViewProviderDrawingView::setEdit(ModNum); } @@ -95,7 +95,7 @@ bool ViewProviderLeader::setEdit(int ModNum) bool ViewProviderLeader::doubleClicked() { -// Base::Console().Message("VPL::doubleClicked()\n"); +// Base::Console().message("VPL::doubleClicked()\n"); setEdit(ViewProvider::Default); return true; } diff --git a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp index d6db537377..773ca636c9 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp @@ -73,7 +73,7 @@ ViewProviderRichAnno::ViewProviderRichAnno() bool ViewProviderRichAnno::doubleClicked() { -// Base::Console().Message("VPRA::doubleClicked()\n"); +// Base::Console().message("VPRA::doubleClicked()\n"); setEdit(ViewProvider::Default); return true; } diff --git a/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp b/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp index 06cc8e5672..88b45e0462 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp @@ -69,7 +69,7 @@ ViewProviderTemplate::ViewProviderTemplate() : m_myName(std::string()) void ViewProviderTemplate::attach(App::DocumentObject* pcFeat) { - // Base::Console().Message("VPT::attach(%s)\n", pcFeat->getNameInDocument()); + // Base::Console().message("VPT::attach(%s)\n", pcFeat->getNameInDocument()); ViewProviderDocumentObject::attach(pcFeat); auto feature = getTemplate(); @@ -164,7 +164,7 @@ QGITemplate* ViewProviderTemplate::getQTemplate() void ViewProviderTemplate::setMarkers(bool state) { - // Base::Console().Message("VPT::setMarkers(%d)\n", state); + // Base::Console().message("VPT::setMarkers(%d)\n", state); QGITemplate* qTemplate = getQTemplate(); QGISVGTemplate* qSvgTemplate = dynamic_cast(qTemplate); if (qSvgTemplate) { diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp index b6854b30f0..10e6d080c2 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp @@ -212,7 +212,7 @@ void ViewProviderViewPart::onChanged(const App::Property* prop) void ViewProviderViewPart::attach(App::DocumentObject *pcFeat) { -// Base::Console().Message("VPVP::attach(%s)\n", pcFeat->getNameInDocument()); +// Base::Console().message("VPVP::attach(%s)\n", pcFeat->getNameInDocument()); TechDraw::DrawViewMulti* dvm = dynamic_cast(pcFeat); TechDraw::DrawViewDetail* dvd = dynamic_cast(pcFeat); if (dvm) { @@ -290,7 +290,7 @@ bool ViewProviderViewPart::setEdit(int ModNum) TechDraw::DrawViewDetail* dvd = dynamic_cast(dvp); if (dvd) { if (!dvd->BaseView.getValue()) { - Base::Console().Error("DrawViewDetail - %s - has no BaseView!\n", dvd->getNameInDocument()); + Base::Console().error("DrawViewDetail - %s - has no BaseView!\n", dvd->getNameInDocument()); return false; } Gui::Control().showDialog(new TaskDlgDetail(dvd)); @@ -357,7 +357,7 @@ void ViewProviderViewPart::handleChangedPropertyType(Base::XMLReader &reader, co bool ViewProviderViewPart::onDelete(const std::vector & subNames) { - // Base::Console().Message("VPVP::onDelete(%d subNames)\n", subNames.size()); + // Base::Console().message("VPVP::onDelete(%d subNames)\n", subNames.size()); // we cannot delete if the view has a section or detail view (void) subNames; QString bodyMessage; diff --git a/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp b/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp index a0678bbcc6..154fb47f5b 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp @@ -94,7 +94,7 @@ std::vector ViewProviderWeld::claimChildren() const bool ViewProviderWeld::setEdit(int ModNum) { -// Base::Console().Message("VPW::setEdit(%d)\n", ModNum); +// Base::Console().message("VPW::setEdit(%d)\n", ModNum); if (ModNum != ViewProvider::Default ) { return ViewProviderDrawingView::setEdit(ModNum); } @@ -109,7 +109,7 @@ bool ViewProviderWeld::setEdit(int ModNum) bool ViewProviderWeld::doubleClicked() { -// Base::Console().Message("VPW::doubleClicked()\n"); +// Base::Console().message("VPW::doubleClicked()\n"); setEdit(ViewProvider::Default); return true; } diff --git a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp index 29999791c2..43fae90a78 100644 --- a/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp +++ b/src/Mod/TechDraw/Gui/Widgets/CompassWidget.cpp @@ -170,7 +170,7 @@ void CompassWidget::paintEvent(QPaintEvent* event) // set the compass dial and spinbox to a new angle void CompassWidget::setDialAngle(double newAngle) { - // Base::Console().Message("CW::setDialAngle(%.3f)\n", newAngle); + // Base::Console().message("CW::setDialAngle(%.3f)\n", newAngle); m_angle = newAngle; if (compassDial) { compassDial->setAngle(m_angle); @@ -183,7 +183,7 @@ void CompassWidget::setDialAngle(double newAngle) //slot for updates from spinbox on Enter/Return press. void CompassWidget::slotSpinBoxEnter(double newAngle) { - // Base::Console().Message("CW::slotSpinBoxEnter(%.3f)\n", newAngle); + // Base::Console().message("CW::slotSpinBoxEnter(%.3f)\n", newAngle); if (dsbAngle) { m_angle = newAngle; Q_EMIT angleChanged(m_angle); diff --git a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp index 3f1086883d..4135e54389 100644 --- a/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp +++ b/src/Mod/TechDraw/Gui/Widgets/VectorEditWidget.cpp @@ -105,7 +105,7 @@ void VectorEditWidget::setLabel(QString newLabel) void VectorEditWidget::setValue(Base::Vector3d newValue) { -// Base::Console().Message("VEW::setValue(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); +// Base::Console().message("VEW::setValue(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); m_value = newValue; dsbX->setValue(m_value.x); dsbY->setValue(m_value.y); @@ -115,7 +115,7 @@ void VectorEditWidget::setValue(Base::Vector3d newValue) void VectorEditWidget::setValueNoNotify(Base::Vector3d newValue) { -// Base::Console().Message("VEW::setValueNoNotify(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); +// Base::Console().message("VEW::setValueNoNotify(%.6f, %.6f, %.6f)\n", newValue.x, newValue.y, newValue.z); m_value = newValue; m_blockNotify = true; dsbX->setValue(m_value.x); @@ -127,7 +127,7 @@ void VectorEditWidget::setValueNoNotify(Base::Vector3d newValue) void VectorEditWidget::slotExpandButtonToggled(bool checked) { -// Base::Console().Message("VEW::slotExpand - checked: %d\n", checked); +// Base::Console().message("VEW::slotExpand - checked: %d\n", checked); if (checked) { vectorEditLayout->addLayout(VectorEditItemLayout); vectorEditLayout->addItem(verticalSpacer); @@ -144,7 +144,7 @@ void VectorEditWidget::slotExpandButtonToggled(bool checked) //to tell the world about the change if it comes from the Ui. void VectorEditWidget::slotXValueChanged(double newValue) { -// Base::Console().Message("VEW::xValueChanged(%.6f) - m_value.x: %.6f\n", newValue, m_value.x); +// Base::Console().message("VEW::xValueChanged(%.6f) - m_value.x: %.6f\n", newValue, m_value.x); if (!m_blockNotify) { //this is a change from the dsb m_value.x = newValue; @@ -154,7 +154,7 @@ void VectorEditWidget::slotXValueChanged(double newValue) } void VectorEditWidget::slotYValueChanged(double newValue) { -// Base::Console().Message("VEW::yValueChanged(%.6f) - m_value.y: %.6f\n", newValue, m_value.y); +// Base::Console().message("VEW::yValueChanged(%.6f) - m_value.y: %.6f\n", newValue, m_value.y); if (!m_blockNotify) { //this is a change from the dsb m_value.y = newValue; @@ -164,7 +164,7 @@ void VectorEditWidget::slotYValueChanged(double newValue) } void VectorEditWidget::slotZValueChanged(double newValue) { -// Base::Console().Message("VEW::zValueChanged(%.6f)\n", newValue); +// Base::Console().message("VEW::zValueChanged(%.6f)\n", newValue); if (!m_blockNotify) { //this is a change from the dsb m_value.z = newValue; @@ -175,7 +175,7 @@ void VectorEditWidget::slotZValueChanged(double newValue) void VectorEditWidget::updateDisplay() { -// Base::Console().Message("VEW::updateDisplay() - m_value: %s\n", DrawUtil::formatVector(m_value).c_str()); +// Base::Console().message("VEW::updateDisplay() - m_value: %s\n", DrawUtil::formatVector(m_value).c_str()); QString qNewDisplayString = QString::fromStdString(DrawUtil::formatVector(m_value)); leVectorDisplay->setText(qNewDisplayString); } diff --git a/src/Mod/Test/Gui/AppTestGui.cpp b/src/Mod/Test/Gui/AppTestGui.cpp index 8f115e0028..f78e70064d 100644 --- a/src/Mod/Test/Gui/AppTestGui.cpp +++ b/src/Mod/Test/Gui/AppTestGui.cpp @@ -36,10 +36,10 @@ class ILoggerBlockerTest: public Base::ILogger public: ~ILoggerBlockerTest() override { - Base::Console().DetachObserver(this); + Base::Console().detachObserver(this); } - const char* Name() override + const char* name() override { return "ILoggerBlockerTest"; } @@ -50,7 +50,7 @@ public: buffer.clear(); } - void SendLog(const std::string& notifiername, + void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, Base::IntendedRecipient recipient, @@ -84,13 +84,13 @@ public: void runSingleTest(const char* comment, std::string expectedResult) { - Base::Console().Log(comment); + Base::Console().log(comment); flush(); - Base::Console().Log("LOG"); - Base::Console().Message("MSG"); - Base::Console().Warning("WRN"); - Base::Console().Error("ERR"); - Base::Console().Critical("CMS"); + Base::Console().log("LOG"); + Base::Console().message("MSG"); + Base::Console().warning("WRN"); + Base::Console().error("ERR"); + Base::Console().critical("CMS"); if (buffer.str() != expectedResult) { throw Py::RuntimeError("ILoggerTest: " + buffer.str() + " different from " + expectedResult); @@ -135,7 +135,7 @@ public: runSingleTest("Print all", "LOGMSGWRNERRCMS"); { Base::ILoggerBlocker blocker("ILoggerBlockerTest"); - Base::Console().SetEnabledMsgType("ILoggerBlockerTest", + Base::Console().setEnabledMsgType("ILoggerBlockerTest", Base::ConsoleSingleton::MsgType_Log, true); runSingleTest("Log is enabled but a warning is triggered in debug mode", "LOG"); @@ -218,8 +218,8 @@ private: { (void)args; ILoggerBlockerTest iltest; - Base::Console().AttachObserver(static_cast(&iltest)); - Base::Console().SetConnectionMode(Base::ConsoleSingleton::Direct); + Base::Console().attachObserver(static_cast(&iltest)); + Base::Console().setConnectionMode(Base::ConsoleSingleton::Direct); iltest.runTest(); return Py::None(); } @@ -247,7 +247,7 @@ PyMOD_INIT_FUNC(QtUnitGui) // with the Python runtime system PyObject* mod = TestGui::initModule(); - Base::Console().Log("Loading GUI of Test module... done\n"); + Base::Console().log("Loading GUI of Test module... done\n"); // add resources and reloads the translators loadTestResource(); diff --git a/src/Mod/Test/UnitTests.py b/src/Mod/Test/UnitTests.py index 4c3a3003c8..b2a22043b5 100644 --- a/src/Mod/Test/UnitTests.py +++ b/src/Mod/Test/UnitTests.py @@ -96,9 +96,9 @@ class UnitBasicCases(unittest.TestCase): qu2 = FreeCAD.Units.Quantity("m/s") self.assertTrue(qu1 / qu2, 1) - def testSchemes(self): - schemes = FreeCAD.Units.listSchemas() - num = len(schemes) + def testSchemas(self): + schemas = FreeCAD.Units.listSchemas() + num = len(schemas) psi = FreeCAD.Units.parseQuantity("1psi") for i in range(num): @@ -108,7 +108,7 @@ class UnitBasicCases(unittest.TestCase): 1, v.Value, msg='Failed with "{0}" scheme: {1} != 1 (delta: {2})'.format( - schemes[i], v.Value, self.delta + schemas[i], v.Value, self.delta ), delta=self.delta, ) @@ -121,7 +121,7 @@ class UnitBasicCases(unittest.TestCase): 1, v.Value, msg='Failed with "{0}" scheme: {1} != 1 (delta: {2})'.format( - schemes[i], v.Value, self.delta + schemas[i], v.Value, self.delta ), delta=self.delta, ) @@ -135,7 +135,7 @@ class UnitBasicCases(unittest.TestCase): 1, v.Value, msg='Failed with "{0}" scheme: {1} != 1 (delta: {2})'.format( - schemes[i], v.Value, self.delta + schemas[i], v.Value, self.delta ), delta=self.delta, ) @@ -146,12 +146,12 @@ class UnitBasicCases(unittest.TestCase): if issubclass(type(getattr(FreeCAD.Units, i)), FreeCAD.Units.Quantity): quantities.append(i) - schemes = FreeCAD.Units.listSchemas() + schemas = FreeCAD.Units.listSchemas() for i in quantities: q1 = getattr(FreeCAD.Units, i) q1 = FreeCAD.Units.Quantity(q1) q1.Format = {"Precision": 16} - for idx, val in enumerate(schemes): + for idx, val in enumerate(schemas): [t, amountPerUnit, unit] = FreeCAD.Units.schemaTranslate(q1, idx) try: q2 = FreeCAD.Units.Quantity(t) diff --git a/src/Mod/Tux/NavigationIndicatorGui.py b/src/Mod/Tux/NavigationIndicatorGui.py index a5fde4439f..84b7f3db7b 100644 --- a/src/Mod/Tux/NavigationIndicatorGui.py +++ b/src/Mod/Tux/NavigationIndicatorGui.py @@ -657,11 +657,11 @@ aRoundedArcball = QtGui.QAction(gOrbit) aRoundedArcball.setObjectName("NavigationIndicator_RoundedArcball") aRoundedArcball.setCheckable(True) -menuOrbit.addAction(aTurntable) -menuOrbit.addAction(aTrackball) -menuOrbit.addAction(aFreeTurntable) -menuOrbit.addAction(aTrackballClassic) menuOrbit.addAction(aRoundedArcball) +menuOrbit.addAction(aTrackball) +menuOrbit.addAction(aTrackballClassic) +menuOrbit.addAction(aTurntable) +menuOrbit.addAction(aFreeTurntable) menuSettings.addMenu(menuOrbit) menuSettings.addSeparator() @@ -814,7 +814,7 @@ def onOrbit(): def onOrbitShow(): """Set turntable or trackball orbit style.""" - OrbitStyle = pView.GetInt("OrbitStyle", 1) + OrbitStyle = pView.GetInt("OrbitStyle", 4) gOrbit.blockSignals(True) if OrbitStyle == 0: aTurntable.setChecked(True) diff --git a/src/Mod/Web/App/AppWeb.cpp b/src/Mod/Web/App/AppWeb.cpp index b5a298ff75..fff8c4c787 100644 --- a/src/Mod/Web/App/AppWeb.cpp +++ b/src/Mod/Web/App/AppWeb.cpp @@ -187,6 +187,6 @@ PyMOD_INIT_FUNC(Web) // // PyObject* mod = Web::initModule(); - Base::Console().Log("Loading Web module... done\n"); + Base::Console().log("Loading Web module... done\n"); PyMOD_Return(mod); } diff --git a/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp b/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp index e4f4e0e6f6..25ecde2108 100644 --- a/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp +++ b/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp @@ -67,6 +67,6 @@ PyMOD_INIT_FUNC(_TEMPLATE_) // // PyObject* mod = _TEMPLATE_::initModule(); - Base::Console().Log("Loading _TEMPLATE_ module... done\n"); + Base::Console().log("Loading _TEMPLATE_ module... done\n"); PyMOD_Return(mod); } diff --git a/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp b/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp index da3fc6cd6f..52d3053a72 100644 --- a/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp +++ b/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp @@ -81,6 +81,6 @@ PyMOD_INIT_FUNC(_TEMPLATE_Gui) // // PyObject* mod = _TEMPLATE_Gui::initModule(); - Base::Console().Log("Loading GUI of _TEMPLATE_ module... done\n"); + Base::Console().log("Loading GUI of _TEMPLATE_ module... done\n"); PyMOD_Return(mod); } diff --git a/src/Tools/_TEMPLATE_/Gui/Command.cpp b/src/Tools/_TEMPLATE_/Gui/Command.cpp index 88bc81e8bc..008c0973b5 100644 --- a/src/Tools/_TEMPLATE_/Gui/Command.cpp +++ b/src/Tools/_TEMPLATE_/Gui/Command.cpp @@ -53,7 +53,7 @@ Cmd_TEMPLATE_Test::Cmd_TEMPLATE_Test() void Cmd_TEMPLATE_Test::activated(int) { - Base::Console().Message("Hello, World!\n"); + Base::Console().message("Hello, World!\n"); } void Create_TEMPLATE_Commands(void) diff --git a/src/Tools/bindings/templates/templateModuleAppMain.py b/src/Tools/bindings/templates/templateModuleAppMain.py index 5c16038321..144a39498a 100644 --- a/src/Tools/bindings/templates/templateModuleAppMain.py +++ b/src/Tools/bindings/templates/templateModuleAppMain.py @@ -40,7 +40,7 @@ extern struct PyMethodDef @self.module.Name@_methods[]; extern "C" { void App@self.module.Name@Export init@self.module.Name@() { - Base::Console().Log("Mod: Loading @self.module.Name@ module... done\\n"); + Base::Console().log("Mod: Loading @self.module.Name@ module... done\\n"); PyObject* partModule = Py_InitModule3("@self.module.Name@", @self.module.Name@_methods, module_@self.module.Name@_doc); /* mod name, table ptr */ + for i in self.module.Content.Feature: diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 6feae931e7..069498dfa8 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,10 +1,10 @@ -if ( EXISTS "${CMAKE_SOURCE_DIR}/tests/lib/googletest" ) - include_directories( ${CMAKE_SOURCE_DIR}/tests/lib/googletest/include/ ) - include_directories( ${CMAKE_SOURCE_DIR}/tests/lib/googlemock/include/ ) +if(FREECAD_USE_EXTERNAL_GTEST) + find_package(GTest REQUIRED) + set(Google_Tests_LIBS ${GTEST_LIBRARIES} ${GMOCK_LIBRARIES}) else() - find_package(GTest) - if( GTest_FOUND ) - message( STATUS "Found Google Test: version ${GTest_VERSION}" ) + if ( EXISTS "${CMAKE_SOURCE_DIR}/tests/lib/googletest" ) + include_directories( ${CMAKE_SOURCE_DIR}/tests/lib/googletest/include/ ) + include_directories( ${CMAKE_SOURCE_DIR}/tests/lib/googlemock/include/ ) else() message( SEND_ERROR "The Google Test submodule is not available. Please run git submodule update --init" ) endif() @@ -124,7 +124,7 @@ foreach (exe ${TestExecutables}) add_executable(${exe}) endforeach() -if ( EXISTS "${CMAKE_SOURCE_DIR}/tests/lib/googletest" ) +if ( NOT FREECAD_USE_EXTERNAL_GTEST ) add_subdirectory(lib) endif() add_subdirectory(src) diff --git a/tests/src/Base/CMakeLists.txt b/tests/src/Base/CMakeLists.txt index 154831216f..9bc17b29ec 100644 --- a/tests/src/Base/CMakeLists.txt +++ b/tests/src/Base/CMakeLists.txt @@ -15,6 +15,7 @@ target_sources(Tests_run PRIVATE Quantity.cpp Reader.cpp Rotation.cpp + SchemaTests.cpp ServiceProvider.cpp Stream.cpp TimeInfo.cpp diff --git a/tests/src/Base/Quantity.cpp b/tests/src/Base/Quantity.cpp index 525c57541b..7e555d7e71 100644 --- a/tests/src/Base/Quantity.cpp +++ b/tests/src/Base/Quantity.cpp @@ -1,16 +1,18 @@ #include #include #include -#include -#include #include -#include -// NOLINTBEGIN +using Base::ParserError; +using Base::Quantity; +using Base::Unit; +using Base::UnitsMismatchError; + + TEST(BaseQuantity, TestValid) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - Base::Quantity q2 {1.0, Base::Unit::Area}; + const Quantity q1 {1.0, Unit::Length}; + Quantity q2 {1.0, Unit::Area}; q2.setInvalid(); EXPECT_EQ(q1.isValid(), true); @@ -19,77 +21,87 @@ TEST(BaseQuantity, TestValid) TEST(BaseQuantity, TestParse) { - Base::Quantity q1 = Base::Quantity::parse("1,234 kg"); - - EXPECT_EQ(q1, Base::Quantity(1.2340, Base::Unit::Mass)); - EXPECT_THROW(boost::ignore_unused(Base::Quantity::parse("1,234,500.12 kg")), Base::ParserError); + const Quantity q1 = Quantity::parse("1,234 kg"); + constexpr auto val {1.2340}; + EXPECT_EQ(q1, Quantity(val, Unit::Mass)); + EXPECT_THROW(auto rew [[maybe_unused]] = Quantity::parse("1,234,500.12 kg"), ParserError); } TEST(BaseQuantity, TestDim) { - Base::Quantity q1 {0, Base::Unit::Area}; + const Quantity q1 {0, Unit::Area}; EXPECT_EQ(q1.isQuantity(), true); } TEST(BaseQuantity, TestNoDim) { - Base::Quantity q1 {}; + const Quantity q1 {}; - EXPECT_EQ(q1.pow(2), Base::Quantity {0}); + EXPECT_EQ(q1.pow(2), Quantity {0}); EXPECT_EQ(q1.isDimensionless(), true); } TEST(BaseQuantity, TestPowEQ1) { - Base::Quantity q1 {2, Base::Unit::Area}; - EXPECT_EQ(q1.pow(1), Base::Quantity(2, Base::Unit::Area)); + const Quantity q1 {2, Unit::Area}; + const auto expect = Quantity {2, Unit::Area}; + EXPECT_EQ(q1.pow(1), expect); } TEST(BaseQuantity, TestPowEQ0) { - Base::Quantity q1 {2, Base::Unit::Area}; - EXPECT_EQ(q1.pow(0), Base::Quantity {1}); + const Quantity q1 {2, Unit::Area}; + EXPECT_EQ(q1.pow(0), Quantity {1}); } TEST(BaseQuantity, TestPowGT1) { - Base::Quantity q1 {2, Base::Unit::Length}; - EXPECT_EQ(q1.pow(2), Base::Quantity(4, Base::Unit::Area)); + constexpr auto v2 {2}; + constexpr auto v4 {4}; + const Quantity q1 {v2, Unit::Length}; + EXPECT_EQ(q1.pow(v2), Quantity(v4, Unit::Area)); } TEST(BaseQuantity, TestPowLT1) { - Base::Quantity q1 {8, Base::Unit::Volume}; - EXPECT_EQ(q1.pow(1.0 / 3.0), Base::Quantity(2, Base::Unit::Length)); + constexpr auto v8 {8}; + constexpr auto v2 {2}; + constexpr auto v3 {3.0}; + const Quantity q1 {v8, Unit::Volume}; + EXPECT_EQ(q1.pow(1.0 / v3), Quantity(v2, Unit::Length)); } TEST(BaseQuantity, TestPow3DIV2) { - Base::Quantity unit {8, Base::Unit::Volume}; - EXPECT_THROW(unit.pow(3.0 / 2.0), Base::UnitsMismatchError); + constexpr auto v2 {2.0}; + constexpr auto v3 {3.0}; + constexpr auto v8 {8}; + const Quantity unit {v8, Unit::Volume}; + EXPECT_THROW(unit.pow(v3 / v2), UnitsMismatchError); } TEST(BaseQuantity, TestString) { - Base::Quantity q1 {2, "kg*m/s^2"}; - EXPECT_EQ(q1.getUnit(), Base::Unit::Force); + constexpr auto v2 {2}; + const Quantity q1 {v2, "kg*m/s^2"}; + EXPECT_EQ(q1.getUnit(), Unit::Force); - Base::Quantity q2 {2, "kg*m^2/s^2"}; - EXPECT_EQ(q2.getUnit(), Base::Unit::Work); + const Quantity q2 {v2, "kg*m^2/s^2"}; + EXPECT_EQ(q2.getUnit(), Unit::Work); } TEST(BaseQuantity, TestCopy) { - Base::Quantity q1 {1.0, Base::Unit::Length}; + const Quantity q1 {1.0, Unit::Length}; - EXPECT_EQ(Base::Quantity {q1}, q1); + EXPECT_EQ(Quantity {q1}, q1); } TEST(BaseQuantity, TestEqual) { - Base::Quantity q1 {1.0, Base::Unit::Force}; - Base::Quantity q2 {1.0, "kg*mm/s^2"}; + const Quantity q1 {1.0, Unit::Force}; + const Quantity q2 {1.0, "kg*mm/s^2"}; EXPECT_EQ(q1 == q1, true); EXPECT_EQ(q1 == q2, true); @@ -97,9 +109,10 @@ TEST(BaseQuantity, TestEqual) TEST(BaseQuantity, TestNotEqual) { - Base::Quantity q1 {1.0, Base::Unit::Force}; - Base::Quantity q2 {2.0, "kg*m/s^2"}; - Base::Quantity q3 {1.0, Base::Unit::Work}; + constexpr auto v2 {2.0}; + const Quantity q1 {1.0, Unit::Force}; + const Quantity q2 {v2, "kg*m/s^2"}; + const Quantity q3 {1.0, Unit::Work}; EXPECT_EQ(q1 != q2, true); EXPECT_EQ(q1 != q3, true); @@ -107,73 +120,77 @@ TEST(BaseQuantity, TestNotEqual) TEST(BaseQuantity, TestLessOrGreater) { - Base::Quantity q1 {1.0, Base::Unit::Force}; - Base::Quantity q2 {2.0, "kg*m/s^2"}; - Base::Quantity q3 {2.0, Base::Unit::Work}; + constexpr auto v2 {2.0}; + Quantity q1 {1.0, Unit::Force}; + Quantity q2 {v2, "kg*m/s^2"}; + Quantity q3 {v2, Unit::Work}; EXPECT_EQ(q1 < q2, true); EXPECT_EQ(q1 > q2, false); EXPECT_EQ(q1 <= q1, true); EXPECT_EQ(q1 >= q1, true); - EXPECT_THROW(boost::ignore_unused(q1 < q3), Base::UnitsMismatchError); - EXPECT_THROW(boost::ignore_unused(q1 > q3), Base::UnitsMismatchError); - EXPECT_THROW(boost::ignore_unused(q1 <= q3), Base::UnitsMismatchError); - EXPECT_THROW(boost::ignore_unused(q1 >= q3), Base::UnitsMismatchError); + EXPECT_THROW(auto res [[maybe_unused]] = (q1 < q3), UnitsMismatchError); + EXPECT_THROW(auto res [[maybe_unused]] = (q1 > q3), UnitsMismatchError); + EXPECT_THROW(auto res [[maybe_unused]] = (q1 <= q3), UnitsMismatchError); + EXPECT_THROW(auto res [[maybe_unused]] = (q1 >= q3), UnitsMismatchError); } TEST(BaseQuantity, TestAdd) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - Base::Quantity q2 {1.0, Base::Unit::Area}; - EXPECT_THROW(q1 + q2, Base::UnitsMismatchError); - EXPECT_THROW(q1 += q2, Base::UnitsMismatchError); - EXPECT_EQ(q1 + q1, Base::Quantity(2, Base::Unit::Length)); - EXPECT_EQ(q1 += q1, Base::Quantity(2, Base::Unit::Length)); + Quantity q1 {1.0, Unit::Length}; + Quantity q2 {1.0, Unit::Area}; + EXPECT_THROW(q1 + q2, UnitsMismatchError); + EXPECT_THROW(q1 += q2, UnitsMismatchError); + EXPECT_EQ(q1 + q1, Quantity(2, Unit::Length)); + EXPECT_EQ(q1 += q1, Quantity(2, Unit::Length)); } TEST(BaseQuantity, TestSub) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - Base::Quantity q2 {1.0, Base::Unit::Area}; - EXPECT_THROW(q1 - q2, Base::UnitsMismatchError); - EXPECT_THROW(q1 -= q2, Base::UnitsMismatchError); - EXPECT_EQ(q1 - q1, Base::Quantity(0, Base::Unit::Length)); - EXPECT_EQ(q1 -= q1, Base::Quantity(0, Base::Unit::Length)); + Quantity q1 {1.0, Unit::Length}; + Quantity q2 {1.0, Unit::Area}; + EXPECT_THROW(q1 - q2, UnitsMismatchError); + EXPECT_THROW(q1 -= q2, UnitsMismatchError); + EXPECT_EQ(q1 - q1, Quantity(0, Unit::Length)); + EXPECT_EQ(q1 -= q1, Quantity(0, Unit::Length)); } TEST(BaseQuantity, TestNeg) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - EXPECT_EQ(-q1, Base::Quantity(-1.0, Base::Unit::Length)); + const Quantity q1 {1.0, Unit::Length}; + EXPECT_EQ(-q1, Quantity(-1.0, Unit::Length)); } TEST(BaseQuantity, TestMult) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - Base::Quantity q2 {1.0, Base::Unit::Area}; - EXPECT_EQ(q1 * q2, Base::Quantity(1.0, Base::Unit::Volume)); - EXPECT_EQ(q1 * 2.0, Base::Quantity(2.0, Base::Unit::Length)); + const Quantity q1 {1.0, Unit::Length}; + const Quantity q2 {1.0, Unit::Area}; + EXPECT_EQ(q1 * q2, Quantity(1.0, Unit::Volume)); + EXPECT_EQ(q1 * 2.0, Quantity(2.0, Unit::Length)); } TEST(BaseQuantity, TestDiv) { - Base::Quantity q1 {1.0, Base::Unit::Length}; - Base::Quantity q2 {1.0, Base::Unit::Area}; - EXPECT_EQ(q1 / q2, Base::Quantity(1.0, Base::Unit::InverseLength)); - EXPECT_EQ(q1 / 2.0, Base::Quantity(0.5, Base::Unit::Length)); + const Quantity q1 {1.0, Unit::Length}; + const Quantity q2 {1.0, Unit::Area}; + EXPECT_EQ(q1 / q2, Quantity(1.0, Unit::InverseLength)); + EXPECT_EQ(q1 / 2.0, Quantity(0.5, Unit::Length)); } TEST(BaseQuantity, TestPow) { - Base::Quantity q1 {2.0, Base::Unit::Length}; - Base::Quantity q2 {2.0, Base::Unit::Area}; - Base::Quantity q3 {0.0}; - EXPECT_EQ(q1.pow(q3), Base::Quantity {1}); - EXPECT_EQ(q1.pow(2.0), Base::Quantity(4, Base::Unit::Area)); - EXPECT_THROW(q1.pow(q2), Base::UnitsMismatchError); + constexpr auto v2 {2.0}; + constexpr auto v4 {4}; + + Quantity q1 {v2, Unit::Length}; + Quantity q2 {v2, Unit::Area}; + Quantity q3 {0.0}; + EXPECT_EQ(q1.pow(q3), Quantity {1}); + EXPECT_EQ(q1.pow(v2), Quantity(v4, Unit::Area)); + EXPECT_THROW(q1.pow(q2), UnitsMismatchError); } -class Quantity: public ::testing::Test +class BaseQuantityLoc: public ::testing::Test { protected: void SetUp() override @@ -185,60 +202,77 @@ protected: {} }; -TEST_F(Quantity, TestSchemeImperialTwo) +TEST_F(BaseQuantityLoc, psi_parse_spaced) { - Base::Quantity quantity {1.0, Base::Unit::Length}; - - double factor {}; - std::string unitString; - auto scheme = Base::UnitsApi::createSchema(Base::UnitSystem::ImperialDecimal); - std::string result = scheme->schemaTranslate(quantity, factor, unitString); - EXPECT_EQ(result, "0.04 in"); + const auto qParsed = Quantity::parse("1 psi"); + EXPECT_EQ(qParsed.getValue(), 6.8947448254939996); } -TEST_F(Quantity, TestSchemeImperialOne) +TEST_F(BaseQuantityLoc, psi_parse_no_space) { - Base::Quantity quantity {1.0, Base::Unit::Length}; - - Base::QuantityFormat format = quantity.getFormat(); - format.precision = 1; - quantity.setFormat(format); - - double factor {}; - std::string unitString; - auto scheme = Base::UnitsApi::createSchema(Base::UnitSystem::ImperialDecimal); - std::string result = scheme->schemaTranslate(quantity, factor, unitString); - - EXPECT_EQ(result, "0.0 in"); + const auto qParsed = Quantity::parse("1psi"); + EXPECT_EQ(qParsed.getValue(), 6.8947448254939996); } -TEST_F(Quantity, TestSafeUserString) +TEST_F(BaseQuantityLoc, psi_parse_user_str) { - Base::UnitsApi::setSchema(Base::UnitSystem::ImperialDecimal); - - Base::Quantity quantity {1.0, Base::Unit::Length}; - Base::QuantityFormat format = quantity.getFormat(); - format.precision = 1; - quantity.setFormat(format); - - std::string result = quantity.getSafeUserString(); - - EXPECT_EQ(result, "1 mm"); - - Base::UnitsApi::setSchema(Base::UnitSystem::Imperial1); - - quantity = Base::Quantity {304.8, Base::Unit::Length}; - quantity.setFormat(format); - - result = quantity.getSafeUserString(); - - EXPECT_EQ(result, "1.0 \\'"); - - quantity = Base::Quantity {25.4, Base::Unit::Length}; - quantity.setFormat(format); - - result = quantity.getSafeUserString(); - - EXPECT_EQ(result, "1.0 \\\""); + const auto qParsed = Quantity::parse("1 psi"); + EXPECT_EQ(qParsed.getUserString(), "6894.74 Pa"); +} + +TEST_F(BaseQuantityLoc, psi_parse_safe_user_str) +{ + const auto qParsed = Quantity::parse("1 psi"); + EXPECT_EQ(qParsed.getSafeUserString(), "6894.74 Pa"); +} + +TEST_F(BaseQuantityLoc, psi_parse_unit_type) +{ + const auto qParsed = Quantity::parse("1 psi"); + EXPECT_EQ(qParsed.getUnit().getTypeString(), "Pressure"); +} + +TEST_F(BaseQuantityLoc, psi_to_Pa) +{ + const auto result = Quantity::parse("1 psi").getValueAs(Quantity::Pascal); + const auto expect = 6894.7448254939991; + + EXPECT_EQ(result, expect); +} + +TEST_F(BaseQuantityLoc, psi_to_KPa) +{ + const auto result = Quantity::parse("1 psi").getValueAs(Quantity::KiloPascal); + const auto expect = 6.8947448254939996; + + EXPECT_EQ(result, expect); +} + +TEST_F(BaseQuantityLoc, psi_to_MPa) +{ + const auto result = Quantity::parse("1 psi").getValueAs(Quantity::MegaPascal); + const auto expect = 0.0068947448254939999; + + EXPECT_EQ(result, expect); +} + +TEST_F(BaseQuantityLoc, voltage_unit) +{ + const auto qq = Quantity::parse("1e20 V"); + + EXPECT_EQ(qq.getUnit(), Unit::ElectricPotential); +} + +TEST_F(BaseQuantityLoc, voltage_val) +{ + const auto qq = Quantity::parse("1e20 V"); + + EXPECT_EQ(qq.getValue(), 1e+26); +} + +TEST_F(BaseQuantityLoc, voltage_val_smaller) +{ + const auto qq = Quantity::parse("1e3 V"); + + EXPECT_EQ(qq.getValue(), 1e+9); } -// NOLINTEND diff --git a/tests/src/Base/SchemaTests.cpp b/tests/src/Base/SchemaTests.cpp new file mode 100644 index 0000000000..8cfc3644c3 --- /dev/null +++ b/tests/src/Base/SchemaTests.cpp @@ -0,0 +1,373 @@ +/************************************************************************ + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ************************************************************************/ + +#include +#include "Base/Exception.h" +#include "Base/Unit.h" +#include "Base/Quantity.h" +#include "Base/UnitsApi.h" +#include "Base/UnitsSchemasData.h" +#include "Base/UnitsSchemas.h" + +#include +#include + +using Base::Quantity; +using Base::QuantityFormat; +using Base::RuntimeError; +using Base::Unit; +using Base::UnitsApi; +using Base::UnitsSchema; +using Base::UnitsSchemas; + +class SchemaTest: public testing::Test +{ +protected: + void SetUp() override + { + const QLocale loc(QLocale::C); + QLocale::setDefault(loc); + } + + void TearDown() override + {} + + static std::string + set(const std::string& schemaName, const Unit unit, const double value) // NOLINT + { + UnitsApi::setSchema(schemaName); + const auto quantity = Quantity {value, unit}; + return quantity.getSafeUserString(); + } + + static std::string setWithPrecision(const std::string& name, + const double value, + const Unit unit, + const int precision) + { + UnitsApi::setSchema(name); + Quantity quantity {value, unit}; + QuantityFormat format = quantity.getFormat(); + format.precision = precision; + quantity.setFormat(format); + return quantity.getSafeUserString(); + } + + std::unique_ptr schemas; // NOLINT +}; + +TEST_F(SchemaTest, imperial_decimal_1_mm_default_precision) +{ + const std::string result = set("ImperialDecimal", Unit::Length, 1.0); + const auto expect {"0.04 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, internal_1_mm_precision_0) +{ + const std::string result = setWithPrecision("Internal", 1.0, Unit::Length, 0); + const auto expect {"1 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, internal_100_mm_precision_0) +{ + const std::string result = setWithPrecision("Internal", 100.0, Unit::Length, 0); + const auto expect {"100 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, internal_100_mm_precision_1) +{ + const std::string result = setWithPrecision("Internal", 100.0, Unit::Length, 1); + const auto expect {"100.0 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, internal_20000_mm_precision_2) +{ + const std::string result = setWithPrecision("Internal", 20000.0, Unit::Length, 2); + const auto expect {"20.00 m"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_1_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialDecimal", 1.0, Unit::Length, 0); + const auto expect {"1 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_10_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialDecimal", 10.0, Unit::Length, 0); + const auto expect {"10 mm"}; + // https://github.com/FreeCAD/FreeCAD/commit/569154b73f818c6a88b010def687d5e684ce64c2 + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_20_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialDecimal", 20.0, Unit::Length, 0); + const auto expect {"1 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_1_mm_precision_0) +{ + const std::string result = setWithPrecision("Imperial", 1.0, Unit::Length, 0); + const auto expect {"39 thou"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_0_mm_precision_0) +{ + const std::string result = setWithPrecision("Imperial", 0.0, Unit::Length, 0); + const auto expect {"0 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_0_mm_precision_1) +{ + const std::string result = setWithPrecision("Imperial", 0.0, Unit::Length, 1); + const auto expect {"0.0 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_0_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialDecimal", 0.0, Unit::Length, 0); + const auto expect {"0 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_0_mm_precision_1) +{ + const std::string result = setWithPrecision("ImperialDecimal", 0.0, Unit::Length, 1); + const auto expect {"0.0 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_0_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialCivil", 0.0, Unit::Length, 0); + const auto expect {"0 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_0_mm_precision_1) +{ + const std::string result = setWithPrecision("ImperialCivil", 0.0, Unit::Length, 1); + const auto expect {"0.0 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_0_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialBuilding", 0.0, Unit::Length, 0); + const auto expect {"0"}; // don't know why + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_0_mm_precision_1) +{ + const std::string result = setWithPrecision("ImperialBuilding", 0.0, Unit::Length, 1); + const auto expect {"0"}; // don't know why + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_1_mm_precision_1) +{ + const std::string result = setWithPrecision("ImperialDecimal", 1.0, Unit::Length, 1); + const auto expect {"1 mm"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_100_mm_precision_0) +{ + const std::string result = setWithPrecision("ImperialDecimal", 100.0, Unit::Length, 0); + const auto expect {"4 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_100_mm_precision_1) +{ + const std::string result = setWithPrecision("ImperialDecimal", 100.0, Unit::Length, 1); + const auto expect {"3.9 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_100_mm_precision_2) +{ + const std::string result = setWithPrecision("ImperialDecimal", 100.0, Unit::Length, 2); + const auto expect {"3.94 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_1_mm_precision_2) +{ + const std::string result = setWithPrecision("ImperialDecimal", 1.0, Unit::Length, 2); + const auto expect {"0.04 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_decimal_1_mm_precision_4) +{ + const std::string result = setWithPrecision("ImperialDecimal", 1.0, Unit::Length, 4); + const auto expect {"0.0394 in"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_safe_user_str_same) +{ + constexpr auto val {304.8}; + const auto result = set("Imperial", Unit::Length, val); + const auto expect {"1.00′"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_safe_user_str_more) +{ + constexpr auto val {310.0}; + const auto result = set("Imperial", Unit::Length, val); + const auto expect {"1.02′"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_safe_user_str_less) +{ + constexpr auto val {300.0}; + const auto result = set("Imperial", Unit::Length, val); + const auto expect {"11.81″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_safe_user_str_one_inch) +{ + constexpr auto val {25.4}; + const auto result = set("Imperial", Unit::Length, val); + const auto expect {"1.00″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_special_function_length_inch) +{ + constexpr auto val {25.4}; + const auto result = set("ImperialBuilding", Unit::Length, val); + const auto expect {"1″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_special_function_length_foot) +{ + constexpr auto val {25.4 * 12}; + const auto result = set("ImperialBuilding", Unit::Length, val); + const auto expect {"1′"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_special_function_length) +{ + constexpr auto val {360.6}; + const auto result = set("ImperialBuilding", Unit::Length, val); + const auto expect {"1′2-1/4″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_building_special_function_length_neg) +{ + constexpr auto val {-360.6}; + const auto result = set("ImperialBuilding", Unit::Length, val); + const auto expect {"-1′2-1/4″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_special_function_angle_degrees) +{ + constexpr auto val {180}; + const auto result = set("ImperialCivil", Unit::Angle, val); + const auto expect {"180°"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_special_function_angle_minutes) +{ + constexpr auto val {180.5}; + const auto result = set("ImperialCivil", Unit::Angle, val); + const auto expect {"180°30′"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_special_function_angle_seconds) +{ + constexpr auto val {180.11}; + const auto result = set("ImperialCivil", Unit::Angle, val); + const auto expect {"180°6′36″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, imperial_civil_special_function_angle_no_degrees) +{ + constexpr auto val {0.11}; + const auto result = set("ImperialCivil", Unit::Angle, val); + const auto expect {"0°6′36″"}; + + EXPECT_EQ(result, expect); +} + +TEST_F(SchemaTest, unknown_schema_name_throws) +{ + EXPECT_THROW(UnitsApi::setSchema("Unknown"), RuntimeError); +} diff --git a/tests/src/Mod/Material/App/TestMaterialValue.cpp b/tests/src/Mod/Material/App/TestMaterialValue.cpp index 1a5d1d12e4..9a6cbe79ef 100644 --- a/tests/src/Mod/Material/App/TestMaterialValue.cpp +++ b/tests/src/Mod/Material/App/TestMaterialValue.cpp @@ -130,7 +130,7 @@ TEST_F(TestMaterialValue, TestQuantityType) EXPECT_EQ(variant.toString().size(), 0); auto quantity = variant.value(); EXPECT_FALSE(quantity.isValid()); - EXPECT_EQ(quantity.getUserString(), "nan "); + EXPECT_EQ(quantity.getUserString(), "nan"); EXPECT_TRUE(std::isnan(quantity.getValue())); // Test a copy @@ -146,7 +146,7 @@ TEST_F(TestMaterialValue, TestQuantityType) EXPECT_EQ(variant.toString().size(), 0); quantity = variant.value(); EXPECT_FALSE(quantity.isValid()); - EXPECT_EQ(quantity.getUserString(), "nan "); + EXPECT_EQ(quantity.getUserString(), "nan"); EXPECT_TRUE(std::isnan(quantity.getValue())); }